4c19e6fe by Jeff Balicki

ddd

1 parent b439f946
Showing 52 changed files with 11003 additions and 0 deletions
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>.
/* FVM 3 */
#fastvelocity-min{margin-top:10px}
#fastvelocity-min .clear{clear:both}
.fvm-settings label{font-size:15px;color:#222;padding-top:1px}
.fvm-settings span.note-info{font-size:15px;margin-left:8px;color:#666;font-style:italic}
.fvm-settings p.description{font-size:15px;color:#666;font-style:italic}
#tab-info h4{font-size:15px;margin-bottom:-10px}
.fvm-hide{max-height:1px;overflow:none;position:absolute;top:-9999px;left:-9999px;visibility:hidden}
.fvm-warning{font-weight:500;color:#A00}
h3.fvm-bold-green{font-weight:500;font-size:15px;color:#1196A3}
.fvm-bold-green{font-weight:500;color:#1196A3}
.fvm-label-special{line-height:38px}
.fvm-label-pad{line-height:21px}
.fvm-rowintro{padding-bottom:10px;font-size:15px}
table.fvm-settings td,table.fvm-settings td p,table.fvm-settings th{font-size:15px}
.fvm-wrapper{font-size:16px;padding:18px}
.fvm-wrapper h4{font-size:16px;margin:0;color:#1196A3}
.fvm-wrapper .accordion p,.fvm-wrapper .accordion code{font-size:16px;line-height:1.3}
.fvm-wrapper .accordion a, .fvm-wrapper .accordion a:hover { color: #0073aa; }
.fvm-code-full{width:100%;padding:8px;background:#F3F3F3;box-sizing:border-box;font-family:Consolas,Monaco,monospace;font-size:13px;line-height:1.5;margin-bottom:15px}
#status .fvm-cache-stats{margin:10px 0 0}
#status textarea.row-log{display:block;margin:0;padding:6px;border:none;background:#23282d;color:#ccc;height:300px;max-width:100%;overflow:auto;line-height:1.5;font-size:.8125rem;white-space:pre;font-family:monospace}
#status textarea.row-log::-webkit-scrollbar{width:8px;height:8px;background-color:#222}
#status textarea.row-log::-webkit-scrollbar-thumb{background-color:#000}
#status textarea.row-log::-webkit-scrollbar-track{background-color:#999}
/* jQuery UI */
.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}
.ui-icon{display:inline-block;vertical-align:middle;margin-top:-.25em;position:relative;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}
.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin:2px 0 0;padding:.5em .5em .5em .7em;font-size:100%}
.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto}
.ui-widget{font-size:1em}
.ui-widget-content{border:1px solid #ddd;background:#fff;color:#333}
.ui-widget-content a{color:#333}
.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default,.ui-button,html .ui-button.ui-state-disabled:hover,html .ui-button.ui-state-disabled:active{border:1px solid #c5c5c5;background:#f6f6f6;font-weight:400;color:#454545}
.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus,.ui-button:hover,.ui-button:focus{border:1px solid #ccc;background:#ededed;font-weight:400;color:#2b2b2b}
.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active,a.ui-button:active,.ui-button:active,.ui-button.ui-state-active:hover{border:1px solid #bbb;background:#0073aa;font-weight:400;color:#fff}
.ui-icon{width:16px;height:16px}
.ui-icon,.ui-widget-content .ui-icon{background-image:url(images/ui-icons_444444_256x240.png)}
.ui-state-hover .ui-icon,.ui-state-focus .ui-icon,.ui-button:hover .ui-icon,.ui-button:focus .ui-icon{background-image:url(images/ui-icons_555555_256x240.png)}
.ui-state-active .ui-icon,.ui-button:active .ui-icon{background-image:url(images/ui-icons_ffffff_256x240.png)}
.ui-icon-triangle-1-e{background-position:-32px -16px}
.ui-icon-triangle-1-s{background-position:-65px -16px}
.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:3px}
.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:3px}
.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:3px}
.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:3px}
.ui-state-focus:focus{outline:none}
/* Mobile */
@media screen and (max-width:520px) {
.fvm-label-special { line-height: inherit; }
}
// get logs via ajax
function fvm_get_logs() {
// ajax request
jQuery( document ).ready(function() {
var data = { 'action': 'fvm_get_logs' };
jQuery.post(ajaxurl, data, function(resp) {
if(resp.success == 'OK') {
// logs
jQuery('.log-stats textarea').val(resp.log);
jQuery('.log-stats textarea').scrollTop(jQuery('.log-stats textarea')[0].scrollHeight);
} else {
// error log
console.error(resp.success);
}
});
});
}
jQuery( document ).ready(function() {
// help section
jQuery( ".accordion" ).accordion({ active: false, collapsible: true, heightStyle: "content" });
});
\ No newline at end of file
<?php
/*
Plugin Name: Fast Velocity Minify
Plugin URI: http://fastvelocity.com
Description: Improve your speed score on GTmetrix, Pingdom Tools and Google PageSpeed Insights by merging and minifying CSS and JavaScript files into groups, compressing HTML and other speed optimizations.
Author: Raul Peixoto
Author URI: http://fastvelocity.com
Text Domain: fast-velocity-minify
Version: 3.2.2
License: GPL2
------------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# Invalidate OPCache for current file on WP 5.5+
if(function_exists('wp_opcache_invalidate') && stripos(__FILE__, '/fvm.php') !== false) {
wp_opcache_invalidate(__FILE__, true);
}
# info, variables, paths
$fvm_var_file = __FILE__; # /home/path/plugins/pluginname/wpr.php
$fvm_var_basename = plugin_basename($fvm_var_file); # pluginname/wpr.php
$fvm_var_dir_path = plugin_dir_path($fvm_var_file); # /home/path/plugins/pluginname/
$fvm_var_url_path = plugins_url(dirname($fvm_var_basename)) . '/'; # https://example.com/wp-content/plugins/pluginname/
$fvm_var_plugin_version = get_file_data($fvm_var_file, array('Version' => 'Version'), false)['Version'];
$fvm_var_inc_dir = $fvm_var_dir_path . 'inc' . DIRECTORY_SEPARATOR; # /home/path/plugins/pluginname/inc/
$fvm_var_inc_lib = $fvm_var_dir_path . 'libs' . DIRECTORY_SEPARATOR; # /home/path/plugins/pluginname/libs/
# global functions for backend, frontend, ajax, etc
require_once($fvm_var_inc_dir . 'common.php');
require_once($fvm_var_inc_dir . 'updates.php');
# wp-cli support
if (defined('WP_CLI') && WP_CLI) {
require_once($fvm_var_inc_dir . 'wp-cli.php');
}
# get all options from database
$fvm_settings = fvm_get_settings();
# site url, domain name
$fvm_urls = array('wp_site_url'=>trailingslashit(site_url()), 'wp_domain'=>fvm_get_domain());
# only on backend
if(is_admin()) {
# admin functionality
require_once($fvm_var_inc_dir . 'admin.php');
require_once($fvm_var_inc_dir . 'serverinfo.php');
# both backend and frontend, as long as user can manage options
add_action('admin_bar_menu', 'fvm_admintoolbar', 100);
add_action('init', 'fvm_process_cache_purge_request');
# do admin stuff, as long as user can manage options
add_action('admin_init', 'fvm_save_settings');
add_action('admin_init', 'fvm_check_minimum_requirements');
add_action('admin_init', 'fvm_check_misconfiguration');
add_action('admin_init', 'fvm_update_changes');
add_action('admin_enqueue_scripts', 'fvm_add_admin_jscss');
add_action('admin_menu', 'fvm_add_admin_menu');
add_action('admin_notices', 'fvm_show_admin_notice_from_transient');
add_action('wp_ajax_fvm_get_logs', 'fvm_get_logs_callback');
# purge everything
add_action('switch_theme', 'fvm_purge_all');
add_action('customize_save', 'fvm_purge_all');
add_action('avada_clear_dynamic_css_cache', 'fvm_purge_all');
add_action('upgrader_process_complete', 'fvm_purge_all');
add_action('update_option_theme_mods_' . get_option('stylesheet'), 'fvm_purge_all');
}
# frontend only, any user permissions
if(!is_admin()) {
# frontend functionality
require_once($fvm_var_inc_dir . 'frontend.php');
# both back and front, as long as the option is enabled
add_action('init', 'fvm_disable_emojis');
add_action('wp_loaded', 'fvm_ajax_optimizer');
# both backend and frontend, as long as user can manage options
add_action('admin_bar_menu', 'fvm_admintoolbar', 100);
add_action('init', 'fvm_process_cache_purge_request');
# actions for frontend only
add_action('template_redirect', 'fvm_start_buffer', -PHP_INT_MAX);
}
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# check for minimum requirements and prevent activation or disable if not fully compatible
function fvm_check_minimum_requirements() {
if(current_user_can('manage_options')) {
# defaults
$error = '';
# php version requirements
if (version_compare( PHP_VERSION, '5.6', '<' )) {
$error = __( 'FVM requires PHP 5.6 or higher. You’re still on', 'fast-velocity-minify' ) .' '. PHP_VERSION;
}
# php extension requirements
if (!extension_loaded('mbstring')) {
$error = __( 'FVM requires the PHP mbstring module to be installed on the server.', 'fast-velocity-minify' );
}
# wp version requirements
if ( version_compare( $GLOBALS['wp_version'], '4.9', '<' ) ) {
$error = __( 'FVM requires WP 4.9 or higher. You’re still on', 'fast-velocity-minify' ) .' '. $GLOBALS['wp_version'];
}
# check cache directory
$ch_info = fvm_get_cache_location();
if(isset($ch_info['ch_url']) && !empty($ch_info['ch_url']) && isset($ch_info['ch_dir']) && !empty($ch_info['ch_dir'])) {
if(is_dir($ch_info['ch_dir']) && !is_writable($ch_info['ch_dir'])) {
$error = __( 'FVM needs writing permissions on ', 'fast-velocity-minify' ). ' ['.$ch_info['ch_dir'].']';
}
}
# deactivate plugin forcefully
global $fvm_var_basename;
if ((is_plugin_active($fvm_var_basename) && !empty($error)) || !empty($error)) {
if (isset($_GET['activate'])) { unset($_GET['activate']); }
deactivate_plugins($fvm_var_basename);
add_settings_error( 'fvm_admin_notice', 'fvm_admin_notice', $error, 'success' );
}
}
}
# check for soft errors and misconfiguration
function fvm_check_misconfiguration() {
try {
# plugin version
global $fvm_var_plugin_version;
if(is_null($fvm_var_plugin_version)) { return false; }
# if no database version, regenerate
$plugin_meta = get_option('fvm_plugin_meta');
if($plugin_meta === false) {
# startup routines
fvm_plugin_deactivate();
fvm_plugin_activate();
# save
update_option('fvm_plugin_meta', json_encode(array('dbv'=>0)) );
}
# updates
if($plugin_meta !== false) {
# future updates
$meta = json_decode($plugin_meta, true);
$previous_version = $meta['dbv'];
if($fvm_var_plugin_version != $previous_version) {
# startup routines
fvm_plugin_deactivate();
fvm_plugin_activate();
# save
update_option('fvm_plugin_meta', json_encode(array('dbv'=>$fvm_var_plugin_version)) );
}
}
} catch (Exception $e) {
error_log('Caught exception (fvm_initialize_database): '.$e->getMessage(), 0);
}
}
# save plugin settings on wp-admin
function fvm_save_settings() {
# save settings
if(isset($_POST['fvm_action']) && isset($_POST['fvm_settings_nonce']) && $_POST['fvm_action'] == 'save_settings') {
if(!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.', 'fast-velocity-minify'), __('Error:', 'fast-velocity-minify'), array('response'=>200));
}
if(!wp_verify_nonce($_POST['fvm_settings_nonce'], 'fvm_settings_nonce')) {
wp_die( __('Invalid nounce. Please refresh and try again.', 'fast-velocity-minify'), __('Error:', 'fast-velocity-minify'), array('response'=>200));
}
# update fvm_settings in the global scope
if(isset($_POST['fvm_settings']) && is_array($_POST['fvm_settings'])) {
# sanitize recursively
if(is_array($_POST['fvm_settings'])) {
foreach ($_POST['fvm_settings'] as $group=>$arr) {
if(is_array($arr)) {
foreach ($arr as $k=>$v) {
# only numeric, string or arrays allowed at this level
if(!is_string($v) && !is_numeric($v) && !is_array($v)) { $_POST['fvm_settings'][$group][$k] = ''; }
# numeric fields, only positive integers allowed
if(is_numeric($v)) { $_POST['fvm_settings'][$group][$k] = abs(intval($v)); }
# sanitize text area content
if(is_string($v)) { $_POST['fvm_settings'][$group][$k] = strip_tags($v); }
# clean cdn url
if($group == 'cdn' && $k == 'url') {
$_POST['fvm_settings'][$group][$k] = trim(trim(str_replace(array('http://', 'https://'), '', $v), '/'));
}
}
}
}
}
# get mandatory default exclusions
global $fvm_settings;
$fvm_settings = fvm_get_default_settings($_POST['fvm_settings']);
# purge caches
fvm_purge_all();
# save settings
update_option('fvm_settings', json_encode($fvm_settings), false);
add_settings_error( 'fvm_admin_notice', 'fvm_admin_notice', 'Settings saved successfully!', 'success' );
} else {
wp_die( __('Invalid data!', 'fast-velocity-minify'), __('Error:', 'fast-velocity-minify'), array('response'=>200));
}
}
}
# return checked, or empty for checkboxes in admin
function fvm_get_settings_checkbox($value) {
if($value == 1) { return 'checked'; }
return '';
}
# return checked, or empty for checkboxes in admin
function fvm_get_settings_radio($key, $value) {
if($key == $value) { return 'checked'; }
return '';
}
# add settings link on plugins listing page
add_filter("plugin_action_links_".$fvm_var_basename, 'fvm_min_settings_link' );
function fvm_min_settings_link($links) {
global $fvm_var_basename;
if (is_plugin_active($fvm_var_basename)) {
$settings_link = '<a href="'.admin_url('admin.php?page=fvm').'">Settings</a>';
array_unshift($links, $settings_link);
}
return $links;
}
# Enqueue plugin UI CSS and JS files
function fvm_add_admin_jscss($hook) {
if(current_user_can('manage_options')) {
if ('settings_page_fvm' != $hook) { return; }
global $fvm_var_dir_path, $fvm_var_url_path;
# ui
wp_enqueue_script( 'jquery-ui-core' );
wp_enqueue_script( 'jquery-ui-accordion' );
# js
wp_enqueue_script('fvm', $fvm_var_url_path . 'assets/fvm.js', array('jquery'), filemtime($fvm_var_dir_path.'assets'. DIRECTORY_SEPARATOR .'fvm.js'));
# css
wp_enqueue_style('fvm', $fvm_var_url_path . 'assets/fvm.css', array(), filemtime($fvm_var_dir_path.'assets'. DIRECTORY_SEPARATOR .'fvm.css'));
}
}
# create sidebar admin menu and add templates to admin
function fvm_add_admin_menu() {
if (current_user_can('manage_options')) {
add_options_page('FVM Settings', 'Fast Velocity Minify', 'manage_options', 'fvm', 'fvm_add_settings_admin');
}
}
# print admin notices when needed (json)
function fvm_show_admin_notice_from_transient() {
if(current_user_can('manage_options')) {
$inf = get_transient('fvm_admin_notice');
if($inf != false && !empty($inf)) {
$jsonarr = json_decode($inf, true);
if(!is_null($jsonarr) && is_array($jsonarr)){
# add all
$jsonarr = array_unique($jsonarr);
foreach ($jsonarr as $notice) {
add_settings_error( 'fvm_admin_notice', 'fvm_admin_notice', 'FVM: '.$notice, 'info' );
}
# output on other pages
if(!isset($_GET['page']) || (isset($_GET['page']) && $_GET['page'] != 'fvm')) {
settings_errors( 'fvm_admin_notice' );
}
}
# remove
delete_transient('fvm_admin_notice');
}
}
}
# manage settings page
function fvm_add_settings_admin() {
# admin only
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.'), __('Error:'), array('response'=>200));
}
# include admin html template
global $fvm_settings, $fvm_var_dir_path;
# admin html templates
include($fvm_var_dir_path . 'layout' . DIRECTORY_SEPARATOR . 'admin-layout.php');
}
# function to list all cache files on the status page (js ajax code)
function fvm_get_logs_callback() {
# must be able to cleanup cache
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.'), __('Error:'), array('response'=>200));
}
# must have
if(!defined('WP_CONTENT_DIR')) {
wp_die( __('WP_CONTENT_DIR is undefined!'), __('Error:'), array('response'=>200));
}
# defaults
global $wpdb;
if(is_null($wpdb)) {
wp_die( __('Database error!'), __('Error:'), array('response'=>200));
}
# initialize log
$log = '';
# build css logs from database
$results = $wpdb->get_results("SELECT date, msg FROM ".$wpdb->prefix."fvm_logs ORDER BY id DESC LIMIT 500", 'ARRAY_A');
# build log
if(is_array($results)) {
foreach (array_reverse($results, true) as $r) {
$log.= 'PROCESSED ON - ' . date('r', $r['date']) . PHP_EOL;
$log.= $r['msg'] . PHP_EOL . PHP_EOL;
}
}
# default message
if(empty($log)) { $log = 'No logs generated yet.'; }
# build info
$result = array(
'log' => $log,
'success' => 'OK'
);
# return result
header('Content-Type: application/json');
echo json_encode($result);
exit();
}
# run during activation
register_activation_hook($fvm_var_file, 'fvm_plugin_activate');
function fvm_plugin_activate() {
global $wpdb;
if(is_null($wpdb)) { return false; }
# defauls
$sql = array();
$wpdb_collate = $wpdb->collate;
# create cache table
$sqla_table_name = $wpdb->prefix . 'fvm_cache';
$sqla = "CREATE TABLE IF NOT EXISTS {$sqla_table_name} (
`id` bigint(20) unsigned NOT NULL auto_increment ,
`uid` varchar(64) NOT NULL,
`date` bigint(10) unsigned NOT NULL,
`type` varchar(3) NOT NULL,
`content` mediumtext NOT NULL,
`meta` mediumtext NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uid (uid),
KEY date (date), KEY type (type)
)
COLLATE {$wpdb_collate}";
# create logs table
$sqlb_table_name = $wpdb->prefix . 'fvm_logs';
$sqlb = "CREATE TABLE IF NOT EXISTS {$sqlb_table_name} (
`id` bigint(20) unsigned NOT NULL auto_increment,
`uid` varchar(64) NOT NULL,
`date` bigint(10) unsigned NOT NULL,
`type` varchar(10) NOT NULL,
`msg` mediumtext NOT NULL,
`meta` mediumtext NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uid (uid),
KEY date (date),
KEY type (type)
)
COLLATE {$wpdb_collate}";
# run sql
$wpdb->query($sqla);
$wpdb->query($sqlb);
}
# run during deactivation
register_deactivation_hook($fvm_var_file, 'fvm_plugin_deactivate');
function fvm_plugin_deactivate() {
global $wpdb;
if(is_null($wpdb)) { return false; }
# remove options and tables
$wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE option_name = 'fvm_last_cache_update'");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}fvm_cache");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}fvm_logs");
# process cache settings
fvm_purge_static_files();
}
# run during uninstall
register_uninstall_hook($fvm_var_file, 'fvm_plugin_uninstall');
function fvm_plugin_uninstall() {
global $wpdb;
if(is_null($wpdb)) { return false; }
# remove options and tables
$wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE option_name = 'fvm_settings'");
$wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE option_name = 'fvm_last_cache_update'");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}fvm_cache");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}fvm_logs");
# process cache settings
fvm_purge_static_files();
}
# get all known roles
function fvm_get_user_roles_checkboxes() {
global $wp_roles, $fvm_settings;
$roles_list = array();
if(is_object($wp_roles)) {
$roles = (array) $wp_roles->get_names();
foreach ($roles as $role=>$rname) {
$roles_list[] = '<label for="fvm_settings_minify_'.$role.'"><input name="fvm_settings[minify]['.$role.']" type="checkbox" id="fvm_settings_minify_'.$role.'" value="1" '. fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'minify', $role)).'> '.$rname.' </label><br />';
}
}
# return
if(!empty($roles_list)) { return implode(PHP_EOL, $roles_list); } else { return __( 'No roles detected!', 'fast-velocity-minify' ); }
}
\ No newline at end of file
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# functions needed for both frontend or backend
# top admin toolbar for cache purging
function fvm_admintoolbar() {
if(current_user_can('manage_options')) {
global $wp_admin_bar;
# Add top menu to admin bar
$wp_admin_bar->add_node(array(
'id' => 'fvm_menu',
'title' => __("FVM", 'fvm') . '</span>',
'href' => wp_nonce_url(add_query_arg('fvm_do', 'clear_all'), 'fvm_clear', '_wpnonce')
));
# Add submenu
$wp_admin_bar->add_node(array(
'id' => 'fvm_submenu_purge_all',
'parent' => 'fvm_menu',
'title' => __("Clear Everything", 'fvm'),
'href' => wp_nonce_url(add_query_arg('fvm_do', 'clear_all'), 'fvm_clear', '_wpnonce')
));
# Add submenu
$wp_admin_bar->add_node(array(
'id' => 'fvm_submenu_settings',
'parent' => 'fvm_menu',
'title' => __("FVM Settings", 'fvm'),
'href' => admin_url('admin.php?page=fvm')
));
/*
# Add submenu
$wp_admin_bar->add_node(array(
'id' => 'fvm_submenu_upgrade',
'parent' => 'fvm_menu',
'title' => __("Upgrade", 'fvm'),
'href' => admin_url('admin.php?page=fvm&tab=upgrade')
));
*/
# Add submenu
$wp_admin_bar->add_node(array(
'id' => 'fvm_submenu_help',
'parent' => 'fvm_menu',
'title' => __("Help", 'fvm'),
'href' => admin_url('admin.php?page=fvm&tab=help')
));
}
}
# get cache directory
function fvm_get_cache_location() {
# custom path
if (defined('FVM_DIR') && defined('FVM_URL')){
# define paths and url
$sep = DIRECTORY_SEPARATOR;
$dir = trim(rtrim(FVM_DIR, '/\\')). $sep . 'cache' . $sep . 'fvm'. $sep . 'min';
$durl = trim(rtrim(FVM_URL, '/')). '/cache/fvm/min';
# create and return
if(!is_dir($dir) && function_exists('wp_mkdir_p')) { wp_mkdir_p($dir); }
return array('ch_dir'=>$dir,'ch_url'=>$durl);
}
# /wp-content/cache
if (defined('WP_CONTENT_DIR') && defined('WP_CONTENT_URL')){
# define paths and url
$sep = DIRECTORY_SEPARATOR;
$dir = trim(rtrim(WP_CONTENT_DIR, '/\\')). $sep . 'cache' . $sep . 'fvm'. $sep . 'min';
$durl = trim(rtrim(WP_CONTENT_URL, '/')). '/cache/fvm/min';
# create and return
if(!is_dir($dir) && function_exists('wp_mkdir_p')) { wp_mkdir_p($dir); }
return array('ch_dir'=>$dir,'ch_url'=>$durl);
}
# uploads directory
$ch_info = wp_upload_dir();
if(isset($ch_info['basedir']) && isset($ch_info['baseurl']) && !empty($ch_info['basedir'])) {
# define and create directory
$sep = DIRECTORY_SEPARATOR;
$dir = $ch_info['basedir'] . $sep . 'cache' . $sep . 'fvm'. $sep . 'min';
$durl = $ch_info['baseurl'] . '/cache/fvm/min';
# create and return
if(!is_dir($dir) && function_exists('wp_mkdir_p')) { wp_mkdir_p($dir); }
return array('ch_dir'=>$dir,'ch_url'=>$durl);
}
# error
return false;
}
# purge all caches when clicking the button on the admin bar
function fvm_process_cache_purge_request(){
if(isset($_GET['fvm_do']) && isset($_GET['_wpnonce'])) {
# must be able to cleanup cache
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.', 'fast-velocity-minify'), __('Error:', 'fast-velocity-minify'), array('response'=>200));
}
# validate nonce
if(!wp_verify_nonce($_GET['_wpnonce'], 'fvm_clear')) {
wp_die( __('Invalid or expired request... please go back and refresh before trying again!', 'fast-velocity-minify'), __('Error:', 'fast-velocity-minify'), array('response'=>200));
}
# Purge All
if($_GET['fvm_do'] == 'clear_all') {
# purge everything
$cache = fvm_purge_static_files();
$others = fvm_purge_others();
if(is_admin()) {
# merge notices
$notices = array();
if(is_string($cache)) { $notices[] = $cache; }
if(is_string($others)) { $notices[] = $others; }
# save transient for after the redirect
if(count($notices) == 0) { $notices[] = __( 'All supported caches have been purged ', 'fast-velocity-minify' ) . ' ('.date("D, d M Y @ H:i:s e").')'; }
set_transient( 'fvm_admin_notice', json_encode($notices), 10);
}
}
# https://developer.wordpress.org/reference/functions/wp_safe_redirect/
nocache_headers();
wp_safe_redirect(remove_query_arg('_wpnonce', remove_query_arg('_fvm', wp_get_referer())));
exit();
}
}
# Purge everything
function fvm_purge_all() {
fvm_purge_static_files();
fvm_purge_others();
return true;
}
# purge supported hosting and plugins
function fvm_purge_others(){
# third party plugins
# Purge all W3 Total Cache
if (function_exists('w3tc_pgcache_flush')) {
w3tc_pgcache_flush();
return __( 'All caches on <strong>W3 Total Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge WP Super Cache
if (function_exists('wp_cache_clear_cache')) {
wp_cache_clear_cache();
return __( 'All caches on <strong>WP Super Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge WP Rocket
if (function_exists('rocket_clean_domain')) {
rocket_clean_domain();
return __( 'All caches on <strong>WP Rocket</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge Cachify
if (function_exists('cachify_flush_cache')) {
cachify_flush_cache();
return __( 'All caches on <strong>Cachify</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge Comet Cache
if ( class_exists("comet_cache") ) {
comet_cache::clear();
return __( 'All caches on <strong>Comet Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge Zen Cache
if ( class_exists("zencache") ) {
zencache::clear();
return __( 'All caches on <strong>Comet Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge LiteSpeed Cache
if ( has_action('litespeed_purge_all') ) {
do_action('litespeed_purge_all');
return __( 'All caches on <strong>LiteSpeed Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge WP Cloudflare Super Page Cache
if( class_exists('SW_CLOUDFLARE_PAGECACHE') ) {
do_action("swcfpc_purge_everything");
return __( 'All caches on <strong>WP Cloudflare Super Page Cache</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge Hyper Cache
if (class_exists( 'HyperCache' )) {
do_action( 'autoptimize_action_cachepurged' );
return __( 'All caches on <strong>HyperCache</strong> have been purged.', 'fast-velocity-minify' );
}
# purge cache enabler
if ( has_action('ce_clear_cache') ) {
do_action('ce_clear_cache');
return __( 'All caches on <strong>Cache Enabler</strong> have been purged.', 'fast-velocity-minify' );
}
# purge wpfc
if (function_exists('wpfc_clear_all_cache')) {
wpfc_clear_all_cache(true);
}
# add breeze cache purge support
if (class_exists("Breeze_PurgeCache")) {
Breeze_PurgeCache::breeze_cache_flush();
return __( 'All caches on <strong>Breeze</strong> have been purged.', 'fast-velocity-minify' );
}
# swift
if (class_exists("Swift_Performance_Cache")) {
Swift_Performance_Cache::clear_all_cache();
return __( 'All caches on <strong>Swift Performance</strong> have been purged.', 'fast-velocity-minify' );
}
# Hummingbird
if(has_action('wphb_clear_page_cache')) {
do_action('wphb_clear_page_cache');
return __( 'All caches on <strong>Hummingbird</strong> have been purged.', 'fast-velocity-minify' );
}
# WP-Optimize
if(has_action('wpo_cache_flush')) {
do_action('wpo_cache_flush');
return __( 'All caches on <strong>WP-Optimize</strong> have been purged.', 'fast-velocity-minify' );
}
# hosting companies
# Purge SG Optimizer (Siteground)
if (function_exists('sg_cachepress_purge_everything')) {
sg_cachepress_purge_everything();
return __( 'All caches on <strong>SG Optimizer</strong> have been purged.', 'fast-velocity-minify' );
}
# Purge Godaddy Managed WordPress Hosting (Varnish + APC)
if (class_exists('WPaaS\Plugin') && method_exists( 'WPass\Plugin', 'vip' )) {
fvm_godaddy_request('BAN');
return __( 'A cache purge request has been sent to <strong>Go Daddy Varnish</strong>', 'fast-velocity-minify' );
}
# Purge WP Engine
if (class_exists("WpeCommon")) {
if (method_exists('WpeCommon', 'purge_memcached')) { WpeCommon::purge_memcached(); }
if (method_exists('WpeCommon', 'purge_varnish_cache')) { WpeCommon::purge_varnish_cache(); }
if (method_exists('WpeCommon', 'purge_memcached') || method_exists('WpeCommon', 'purge_varnish_cache')) {
return __( 'A cache purge request has been sent to <strong>WP Engine</strong>', 'fast-velocity-minify' );
}
}
# Purge Kinsta
global $kinsta_cache;
if ( isset($kinsta_cache) && class_exists('\\Kinsta\\CDN_Enabler')) {
if (!empty( $kinsta_cache->kinsta_cache_purge)){
$kinsta_cache->kinsta_cache_purge->purge_complete_caches();
return __( 'A cache purge request has been sent to <strong>Kinsta</strong>', 'fast-velocity-minify' );
}
}
# Purge Pagely
if ( class_exists( 'PagelyCachePurge' ) ) {
$purge_pagely = new PagelyCachePurge();
$purge_pagely->purgeAll();
return __( 'A cache purge request has been sent to <strong>Pagely</strong>', 'fast-velocity-minify' );
}
# Purge Pressidum
if (defined('WP_NINUKIS_WP_NAME') && class_exists('Ninukis_Plugin')){
$purge_pressidum = Ninukis_Plugin::get_instance();
$purge_pressidum->purgeAllCaches();
return __( 'A cache purge request has been sent to <strong>Pressidium</strong>', 'fast-velocity-minify' );
}
# Purge Savvii
if (defined( '\Savvii\CacheFlusherPlugin::NAME_DOMAINFLUSH_NOW')) {
$purge_savvii = new \Savvii\CacheFlusherPlugin();
if ( method_exists( $plugin, 'domainflush' ) ) {
$purge_savvii->domainflush();
return __( 'A cache purge request has been sent to <strong>Savvii</strong>', 'fast-velocity-minify' );
}
}
# Purge Pantheon Advanced Page Cache plugin
if(function_exists('pantheon_wp_clear_edge_all')) {
pantheon_wp_clear_edge_all();
}
# wordpress default cache
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
}
# Purge Godaddy Managed WordPress Hosting (Varnish)
function fvm_godaddy_request( $method) {
$url = home_url();
$host = wpraiser_get_domain();
$url = set_url_scheme( str_replace( $host, WPaas\Plugin::vip(), $url ), 'http' );
update_option( 'gd_system_last_cache_flush', time(), 'no'); # purge apc
wp_remote_request( esc_url_raw( $url ), array('method' => $method, 'blocking' => false, 'headers' => array('Host' => $host)) );
}
# check if we can minify the page
function fvm_can_minify_js() {
# check if we hit any exclusions from the compatibility page
if(!fvm_can_process_common()) { return false; }
if(fvm_is_amp_page() === true) { return false; }
# url exclusions
if(!fvm_can_process_query_string('js')) { return false; }
# check if user role is allowed
if(!fvm_user_role_processing_allowed('js')) { return false; }
# settings
global $fvm_settings;
# disabled?
if(!isset($fvm_settings['js']['enable']) || (isset($fvm_settings['js']['enable']) && $fvm_settings['js']['enable'] != true)) {
return false;
}
# default
return true;
}
# check if we can minify the page
function fvm_can_process_html() {
# check if we hit any exclusions from the compatibility page
if(!fvm_can_process_common()) { return false; }
if(fvm_is_amp_page() === true) { return false; }
# url exclusions
if(!fvm_can_process_query_string('html')) { return false; }
# settings
global $fvm_settings;
# disabled?
if(!isset($fvm_settings['html']['enable']) || (isset($fvm_settings['html']['enable']) && $fvm_settings['html']['enable'] != true)) {
return false;
}
# check if user role is allowed
if(!fvm_user_role_processing_allowed('html')) { return false; }
# default
return true;
}
# check if we can minify the page
function fvm_can_process_cdn() {
# check if we hit any exclusions from the compatibility page
if(!fvm_can_process_common()) { return false; }
if(fvm_is_amp_page() === true) { return false; }
# url exclusions
if(!fvm_can_process_query_string('cdn')) { return false; }
# settings
global $fvm_settings;
# disabled?
if(!isset($fvm_settings['cdn']['enable']) || (isset($fvm_settings['cdn']['enable']) && $fvm_settings['cdn']['enable'] != true)) {
return false;
}
# no domain
if(!isset($fvm_settings['cdn']['domain']) || (isset($fvm_settings['cdn']['domain']) && empty($fvm_settings['cdn']['domain']))) {
return false;
}
# check if user role is allowed
if(!fvm_user_role_processing_allowed('cdn')) { return false; }
# default
return true;
}
# check if we can minify the page
function fvm_can_minify_css() {
# check if we hit any exclusions from the compatibility page
if(!fvm_can_process_common()) { return false; }
if(fvm_is_amp_page() === true) { return false; }
# url exclusions
if(!fvm_can_process_query_string('css')) { return false; }
# check if user role is allowed
if(!fvm_user_role_processing_allowed('css')) { return false; }
# settings
global $fvm_settings;
# disabled?
if(!isset($fvm_settings['css']['enable']) || (isset($fvm_settings['css']['enable']) && $fvm_settings['css']['enable'] != true)) { return false; }
# default
return true;
}
# save minified code, if not yet available
function fvm_generate_min_url($url, $tkey, $type, $code) {
# cache date
$tvers = get_option('fvm_last_cache_update', '0');
# parse uripath and check if it matches against our rewrite format
$filename = $tvers.'-'.$tkey .'.'. $type;
# check cache directory
$ch_info = fvm_get_cache_location();
if(isset($ch_info['ch_url']) && !empty($ch_info['ch_url']) && isset($ch_info['ch_dir']) && !empty($ch_info['ch_dir'])) {
if(is_dir($ch_info['ch_dir']) && is_writable($ch_info['ch_dir'])) {
# filename
$file = $ch_info['ch_dir'] . DIRECTORY_SEPARATOR . $filename;
$public = $ch_info['ch_url'] . '/' .$filename;
# wordpress functions
require_once (ABSPATH . DIRECTORY_SEPARATOR . 'wp-admin'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'class-wp-filesystem-base.php');
require_once (ABSPATH . DIRECTORY_SEPARATOR .'wp-admin'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'class-wp-filesystem-direct.php');
# initialize
$fileSystemDirect = new WP_Filesystem_Direct(false);
# create if doesn't exist
if(!$fileSystemDirect->exists($file) || ($fileSystemDirect->exists($file) && $fileSystemDirect->mtime($file) < $tvers)) {
$fileSystemDirect->put_contents($file, $code);
}
# return url
return $public;
}
}
# default
return $url;
}
# check if PHP has some functions disabled
function fvm_function_available($func) {
if (ini_get('safe_mode')) return false;
$disabled = ini_get('disable_functions');
if ($disabled) {
$disabled = explode(',', $disabled);
$disabled = array_map('trim', $disabled);
return !in_array($func, $disabled);
}
return true;
}
# open a multiline string, order, filter duplicates and return as array
function fvm_string_toarray($value){
$arr = explode(PHP_EOL, $value);
return fvm_array_order($arr);}
# filter duplicates, order and return array
function fvm_array_order($arr){
if(!is_array($arr)) { return array(); }
$a = array_map('trim', $arr);
$b = array_filter($a);
$c = array_unique($b);
sort($c);
return $c;
}
# return size in human format
function fvm_format_filesize($bytes, $decimals = 2) {
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
for ($i = 0; ($bytes / 1024) > 0.9; $i++, $bytes /= 1024) {}
if($i == 0) { $i = 1; $bytes = $bytes / 1024; } # KB+ only
return sprintf( "%1.{$decimals}f %s", round( $bytes, $decimals ), $units[$i] );
}
# purge static cache files directory
function fvm_purge_static_files() {
# globals
global $fvm_settings;
# truncate cache table
global $wpdb;
if(is_null($wpdb)) { return false; }
try {
$wpdb->query("TRUNCATE TABLE {$wpdb->prefix}fvm_cache");
$wpdb->query("TRUNCATE TABLE {$wpdb->prefix}fvm_logs");
} catch (Exception $e) {
error_log('Error: '.$e->getMessage(), 0);
}
# increment
update_option('fvm_last_cache_update', time());
# check cache directory
$ch_info = fvm_get_cache_location();
if(isset($ch_info['ch_url']) && !empty($ch_info['ch_url']) && isset($ch_info['ch_dir']) && !empty($ch_info['ch_dir'])) {
if(is_dir($ch_info['ch_dir']) && is_writable($ch_info['ch_dir'])) {
# wordpress functions
require_once (ABSPATH . DIRECTORY_SEPARATOR . 'wp-admin'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'class-wp-filesystem-base.php');
require_once (ABSPATH . DIRECTORY_SEPARATOR .'wp-admin'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'class-wp-filesystem-direct.php');
# start
$fileSystemDirect = new WP_Filesystem_Direct(false);
# instant purge
global $fvm_settings;
if(isset($fvm_settings['cache']['min_instant_purge']) && $fvm_settings['cache']['min_instant_purge'] == true) {
$fileSystemDirect->rmdir($ch_info['ch_dir'], true);
return true;
} else {
# older than 24h and not matching current timestamp
$list = $fileSystemDirect->dirlist($ch_info['ch_dir'], false, true);
if(is_array($list) && count($list) > 0) {
foreach($list as $k=>$arr) {
if(isset($arr['lastmodunix']) && $arr['type'] == 'f' && intval($arr['lastmodunix']) <= time()-86400) {
if(substr($arr['name'], 0, 10) !== time()) {
$fileSystemDirect->delete($ch_info['ch_dir'] . DIRECTORY_SEPARATOR . $arr['name'], false, 'f');
}
}
}
}
}
}
}
}
# Fix the permission bits on generated files
function fvm_fix_permission_bits($file){
# must be on the allowed path
if(empty($file) || !defined('WP_CONTENT_DIR') || stripos($file, DIRECTORY_SEPARATOR . 'fvm') === false) {
return __( 'Requested path is not allowed!', 'fast-velocity-minify' );
}
if(function_exists('stat') && fvm_function_available('stat')) {
if ($stat = @stat(dirname($file))) {
$perms = $stat['mode'] & 0007777;
@chmod($file, $perms);
clearstatcache();
return true;
}
}
# get permissions from parent directory
$perms = 0777;
if(function_exists('stat') && fvm_function_available('stat')) {
if ($stat = @stat(dirname($file))) { $perms = $stat['mode'] & 0007777; }
}
if (file_exists($file)){
if ($perms != ($perms & ~umask())){
$folder_parts = explode( DIRECTORY_SEPARATOR, substr( $file, strlen(dirname($file)) + 1 ) );
for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
@chmod(dirname($file) . DIRECTORY_SEPARATOR . implode( DIRECTORY_SEPARATOR, array_slice( $folder_parts, 0, $i ) ), $perms );
}
}
return true;
}
return false;
}
# get options into an array
function fvm_get_settings() {
$fvm_settings = json_decode(get_option('fvm_settings'), true);
# mandatory default exclusions
$fvm_settings_default = fvm_get_default_settings($fvm_settings);
# check if there are any pending field update routines
$fvm_settings_default = fvm_get_updated_field_routines($fvm_settings_default);
# update database if needed
if($fvm_settings != $fvm_settings_default) {
update_option('fvm_settings', json_encode($fvm_settings_default), false);
}
# return
return $fvm_settings;
}
# return value from section and key name
function fvm_get_settings_value($fvm_settings, $section, $key) {
if($fvm_settings != false && is_array($fvm_settings) && count($fvm_settings) > 1) {
if(isset($fvm_settings[$section][$key])) {
return $fvm_settings[$section][$key];
}
}
return '';
}
# default exclusions by seting name
function fvm_get_default_settings($fvm_settings) {
if(!is_array($fvm_settings) || empty($fvm_settings)){
# initialize
$fvm_settings = array();
# global
$fvm_settings['global']['preserve_settings'] = 1;
# html
$fvm_settings['html']['enable'] = 1;
$fvm_settings['html']['nocomments'] = 1;
$fvm_settings['html']['cleanup_header'] = 1;
$fvm_settings['html']['disable_emojis'] = 1;
# css
$fvm_settings['css']['enable'] = 1;
$fvm_settings['css']['noprint'] = 1;
}
# return
return $fvm_settings;
}
# update routines for new fields and replacements
function fvm_get_updated_field_routines($fvm_settings) {
# current version
global $fvm_var_plugin_version;
# must have
if(!is_array($fvm_settings)) { return $fvm_settings; }
# Version 3.0 routines start
# settings migration
if (get_option("fastvelocity_upgraded") === false) {
if (get_option("fastvelocity_plugin_version") !== false) {
# cache path
if (get_option("fastvelocity_min_change_cache_path") !== false && !isset($fvm_settings['cache']['path'])) {
$fvm_settings['cache']['path'] = get_option("fastvelocity_min_change_cache_path");
}
# cache base_url
if (get_option("fastvelocity_min_change_cache_base_url") !== false && !isset($fvm_settings['cache']['url'])) {
$fvm_settings['cache']['url'] = get_option("fastvelocity_min_change_cache_base_url");
}
# disable html minification
if (get_option("fastvelocity_min_skip_html_minification") !== false && !isset($fvm_settings['html']['min_disable'])) {
$fvm_settings['html']['min_disable'] = 1;
}
# do not remove html comments
if (get_option("fastvelocity_min_strip_htmlcomments") !== false && !isset($fvm_settings['html']['nocomments'])) {
$fvm_settings['html']['nocomments'] = 1;
}
# cdn url
$oldcdn = get_option("fastvelocity_min_fvm_cdn_url");
if ($oldcdn !== false && !empty($oldcdn)) {
if (!isset($fvm_settings['cdn']['domain']) || (isset($fvm_settings['cdn']['domain']) && empty($fvm_settings['cdn']['domain']))) {
$fvm_settings['cdn']['enable'] = 1;
$fvm_settings['cdn']['cssok'] = 1;
$fvm_settings['cdn']['jsok'] = 1;
$fvm_settings['cdn']['domain'] = $oldcdn;
}
}
# force https
if (get_option("fastvelocity_min_default_protocol") == 'https' && !isset($fvm_settings['global']['force-ssl'])) {
$fvm_settings['global']['force-ssl'] = 1;
}
# preserve settings on uninstall
if (get_option("fastvelocity_preserve_settings_on_uninstall") !== false && !isset($fvm_settings['global']['preserve_settings'])) {
$fvm_settings['global']['preserve_settings'] = 1;
}
# inline all css
if (get_option("fastvelocity_min_force_inline_css") !== false && !isset($fvm_settings['css']['inline-all'])) {
$fvm_settings['css']['inline-all'] = 1;
}
# remove google fonts
if (get_option("fastvelocity_min_remove_googlefonts") !== false && !isset($fvm_settings['css']['remove'])) {
# add fonts.gstatic.com
$arr = array('fonts.gstatic.com');
$fvm_settings['css']['remove'] = implode(PHP_EOL, fvm_array_order($arr));
}
# Skip deferring the jQuery library, add them to the header render blocking
if (get_option("fastvelocity_min_exclude_defer_jquery") !== false && !isset($fvm_settings['js']['merge_header'])) {
# add jquery + jquery migrate
$arr = array('/jquery-migrate-', '/jquery-migrate.js', '/jquery-migrate.min.js', '/jquery.js', '/jquery.min.js');
$fvm_settings['js']['merge_header'] = implode(PHP_EOL, fvm_array_order($arr));
}
# new users, add recommended default scripts settings
if ( (!isset($fvm_settings['js']['merge_header']) || isset($fvm_settings['js']['merge_header']) && empty($fvm_settings['js']['merge_header'])) && (!isset($fvm_settings['js']['merge_defer']) || (isset($fvm_settings['js']['merge_defer']) && empty($fvm_settings['js']['merge_defer']))) ) {
# header
$arr = array('/jquery-migrate-', '/jquery-migrate.js', '/jquery-migrate.min.js', '/jquery.js', '/jquery.min.js');
$fvm_settings['js']['merge_header'] = implode(PHP_EOL, fvm_array_order($arr));
# defer
$arr = array('/ajax.aspnetcdn.com/ajax/', '/ajax.googleapis.com/ajax/libs/', '/cdnjs.cloudflare.com/ajax/libs/', '/stackpath.bootstrapcdn.com/bootstrap/', '/wp-admin/', '/wp-content/', '/wp-includes/');
$fvm_settings['js']['merge_defer'] = implode(PHP_EOL, fvm_array_order($arr));
# js footer dependencies
$arr = array('wp.i18n');
$fvm_settings['js']['defer_dependencies'] = implode(PHP_EOL, fvm_array_order($arr));
# recommended delayed scripts
$arr = array('function(f,b,e,v,n,t,s)', 'function(w,d,s,l,i)', 'function(h,o,t,j,a,r)', 'connect.facebook.net', 'www.googletagmanager.com', 'gtag(', 'fbq(', 'assets.pinterest.com/js/pinit_main.js', 'pintrk(');
$fvm_settings['js']['thirdparty'] = implode(PHP_EOL, fvm_array_order($arr));
}
# mark as done
update_option('fastvelocity_upgraded', true);
}
}
# Version 3.0 routines end
# return settings array
return $fvm_settings;
}
# save log to database
# usage: $arr = array('type'=>'js', 'msg'=>'', 'meta'=>json_encode(array('loc'=>'function')));
function fvm_save_log($arr) {
# must have
if(is_null($arr) || !is_array($arr) || !isset($arr['msg'])) { return false; }
# uid, prevent duplicate or unique by date
if(!isset($arr['date'])) {
$arr['date'] = time();
$arr['uid'] = fvm_generate_hash_with_prefix($arr['msg'], 'log');
} else {
$arr['uid'] = fvm_generate_hash_with_prefix($arr['date'] . ' / ' . $arr['msg'], 'log');
}
# initialize arrays (fields, types, values)
$fld = array();
$tpe = array();
$vls = array();
# define possible fields
$all = array('date', 'uid', 'type', 'msg', 'meta');
# process only recognized columns
foreach($arr as $k=>$v) {
if(in_array($k, $all)) {
$tpe[] = '%s';
$fld[] = $k;
$vls[] = $v;
}
}
try {
# connect
global $wpdb;
if(is_null($wpdb)) { return false; }
# check if exists before inserting
$result = $wpdb->get_row($wpdb->prepare("SELECT id FROM ".$wpdb->prefix."fvm_logs WHERE uid = %s LIMIT 1", $arr['uid']));
if(!isset($result->id)) {
# prepare and insert to database
$wpdb->query($wpdb->prepare("INSERT IGNORE INTO ".$wpdb->prefix."fvm_logs (".implode(', ', $fld).") VALUES (".implode(', ', $tpe).")", $vls));
return true;
}
} catch (Exception $e) {
error_log('Error: '.$e->getMessage(), 0);
}
# fallback
return false;
}
# generate a 64 char string with prefix
function fvm_generate_hash_with_prefix($uid, $prefix) {
return substr($prefix .hash('sha256', $uid), 0, 64);
}
# replace css imports with origin css code
function fvm_replace_css_imports($css, $rq=null) {
# globals
global $fvm_urls, $fvm_settings;
# reset
$cssimports = array();
$cssimports_prepend = array();
$css = trim($css);
# handle import url rules
preg_match_all ("/@import[ ]*['\"]{0,}(url\()*['\"]*([^\(\{'\"\)]*)['\"\)]*[;]{0,}/ui", $css, $cssimports);
if(isset($cssimports[0]) && isset($cssimports[2])) {
foreach($cssimports[0] as $k=>$cssimport) {
# if @import url rule, or guess full url
if(stripos($cssimport, 'import url') !== false && isset($cssimports[2][$k])) {
$url = trim($cssimports[2][$k]);
} else {
if(!is_null($rq) && !empty($rq)) {
$url = dirname($rq) . '/' . trim($cssimports[2][$k]);
}
}
# must have
if(!empty($url)) {
# make sure we have a complete url
$href = fvm_normalize_url($url);
# download, minify, cache (no ver query string)
$tkey = fvm_generate_hash_with_prefix($href, 'css');
$subcss = fvm_get_transient($tkey);
if ($subcss === false) {
# get minification settings for files
if(isset($fvm_settings['css']['css_enable_min_files'])) {
$enable_css_minification = $fvm_settings['css']['css_enable_min_files'];
}
# force minification on google fonts
if(stripos($href, 'fonts.googleapis.com') !== false) {
$enable_css_minification = true;
}
# download file, get contents, merge
$ddl = array();
$ddl = fvm_maybe_download($href);
# error
if(isset($ddl['error'])) {
return trim($css);
}
# if success
if(isset($ddl['content'])) {
# contents
$subcss = $ddl['content'];
# minify
$subcss = fvm_maybe_minify_css_file($subcss, $href, $enable_css_minification);
# trim code
$subcss = trim($subcss);
# save
fvm_set_transient(array('uid'=>$tkey, 'date'=>$tvers, 'type'=>'css', 'content'=>$subcss));
}
}
# remove import rule and prepend imported code
if ($subcss !== false && !empty($subcss)) {
$css = str_replace($cssimport, '', $css);
$cssimports_prepend[] = '/* Import rule from: '.$href . ' */' . PHP_EOL . $subcss;
}
}
}
}
# prepend import rules
# https://www.w3.org/TR/CSS2/cascade.html#at-import
if(count($cssimports_prepend) > 0) {
$css = implode(PHP_EOL, $cssimports_prepend) . $css;
}
# return
return trim($css);
}
# remove fonts and icons from final css
function fvm_extract_fonts($css_code) {
global $fvm_settings, $fvm_urls;
$critical_fonts = array();
$mff = array();
$css_preload = array();
$css_code_ff = '';
# get list of fonts that are on the critical path and are to be left alone
if( isset($fvm_settings['css']['css_optimize_critical_fonts']) &&
!empty($fvm_settings['css']['css_optimize_critical_fonts'])) {
$critical_fonts = fvm_string_toarray($fvm_settings['css']['css_optimize_critical_fonts']);
}
# extract font faces
preg_match_all('/\@\s*font-face\s*\{([^}]+)\}/iUu', $css_code, $mff);
if(isset($mff[0]) && is_array($mff[0])) {
foreach($mff[0] as $ff) {
# strip and collect
$css_code = str_replace($ff, '', $css_code);
$css_code_ff.= $ff . PHP_EOL;
}
}
# relative paths
$css_code_ff = str_replace('https://'.$fvm_urls['wp_domain'], '', $css_code_ff);
$css_code_ff = str_replace('http://'.$fvm_urls['wp_domain'], '', $css_code_ff);
$css_code_ff = str_replace('//'.$fvm_urls['wp_domain'], '', $css_code_ff);
# fixes
$css_code_ff = str_replace('/./', '/', $css_code_ff);
# return
$result = array('code'=>$css_code, 'fonts'=>$css_code_ff);
return $result;
}
# rewrite assets to cdn
function fvm_process_cdn($html) {
# settings
global $fvm_settings, $fvm_urls;
# html must be an object
if (!is_object($html)) {
$nobj = 1;
$html = str_get_html($html, true, true, 'UTF-8', false, PHP_EOL, ' ');
}
# default integration
$integration_defaults = array('a[data-interchange*=/wp-content/], div[data-background-image], section[data-background-image], form[data-product_variations], image[height], img[src*=/wp-content/], img[data-src*=/wp-content/], img[data-srcset*=/wp-content/], link[rel=icon], link[rel=apple-touch-icon], meta[name=msapplication-TileImage], picture source[srcset*=/wp-content/], rs-slide[data-thumb], video source[type*=video]');
# html integration
if(isset($fvm_urls['wp_domain']) && isset($fvm_settings['cdn']['domain']) && isset($fvm_settings['cdn']['integration'])) {
if(!empty($fvm_settings['cdn']['domain']) && !empty($fvm_urls['wp_domain'])) {
$arr = fvm_string_toarray($fvm_settings['cdn']['integration']);
$arr = array_unique(array_merge($arr, $integration_defaults)); # add defaults
if(is_array($arr) && count($arr) > 0) {
foreach($html->find(implode(', ', $arr) ) as $elem) {
# preserve some attributes but replace others
if (is_object($elem) && isset($elem->attr)) {
# get all attributes
foreach ($elem->attr as $key=>$val) {
# skip href attribute for links
if($key == 'href' && stripos($elem->outertext, '<a ') !== false) { continue; }
# skip certain attributes
if(in_array($key, array('id', 'class', 'action'))) { continue; }
# scheme + site url
$fcdn = str_replace($fvm_urls['wp_domain'], $fvm_settings['cdn']['domain'], $fvm_urls['wp_site_url']);
# known replacements
$elem->{$key} = str_ireplace('url(/wp-content/', 'url('.$fcdn.'/wp-content/', $elem->{$key});
$elem->{$key} = str_ireplace('url("/wp-content/', 'url("'.$fcdn.'/wp-content/', $elem->{$key});
$elem->{$key} = str_ireplace('url(\'/wp-content/', 'url(\''.$fcdn.'/wp-content/', $elem->{$key});
# normalize certain field
if(in_array($key, array('src', 'data-bg', 'data-lazy-src', 'audio', 'poster'))) {
$elem->{$key} = fvm_normalize_url($elem->{$key});
}
# replace other attributes
$elem->{$key} = str_replace('//'.$fvm_urls['wp_domain'], '//'.$fvm_settings['cdn']['domain'], $elem->{$key});
$elem->{$key} = str_replace('\/\/'.$fvm_urls['wp_domain'], '\/\/'.$fvm_settings['cdn']['domain'], $elem->{$key});
}
}
}
}
}
}
# add CDN support to Styles, CSS and JS files
# css
if(isset($fvm_settings['cdn']['cssok']) && $fvm_settings['cdn']['cssok'] == true) {
# scheme + site url
$fcdn = str_replace($fvm_urls['wp_domain'], $fvm_settings['cdn']['domain'], $fvm_urls['wp_site_url']);
# replace inside styles
foreach($html->find('style') as $elem) {
# fetch
$css = $elem->outertext;
# known replacements
$css = str_ireplace('url(/wp-content/', 'url('.$fcdn.'/wp-content/', $css);
$css = str_ireplace('url("/wp-content/', 'url("'.$fcdn.'/wp-content/', $css);
$css = str_ireplace('url(\'/wp-content/', 'url(\''.$fcdn.'/wp-content/', $css);
$css = str_replace('//'.$fvm_urls['wp_domain'], '//'.$fvm_settings['cdn']['domain'], $css);
# save
$elem->outertext = $css;
}
# replace link stylesheets
if(isset($fvm_settings['cdn']['enable_css']) && $fvm_settings['cdn']['enable_css'] == true) {
foreach($html->find('link[rel=stylesheet], link[rel=preload]') as $elem) {
if(isset($elem->href)) {
$elem->href = str_replace($fvm_urls['wp_site_url'], $fcdn, $elem->href);
}
}
}
}
# js
if(isset($fvm_settings['cdn']['jsok']) && $fvm_settings['cdn']['jsok'] == true) {
# replace script files
foreach($html->find('script') as $elem) {
# js files
if(isset($fvm_settings['cdn']['enable_js']) && $fvm_settings['cdn']['enable_js'] == true) {
if(isset($elem->src) && stripos($elem->src, $fvm_urls['wp_domain']) !== false) {
$elem->src = str_replace('//'.$fvm_urls['wp_domain'], '//'.$fvm_settings['cdn']['domain'], $elem->src);
}
}
}
}
# convert html object to string, only when needed
if(isset($nobj) && $nobj == 1) {
$html = trim($html->save());
}
# return
return $html;
}
# rewrite url with cdn
function fvm_rewrite_cdn_url($url) {
global $fvm_settings, $fvm_urls;
if(isset($fvm_settings['cdn']['enable']) && $fvm_settings['cdn']['enable'] == true && isset($fvm_settings['cdn']['domain']) && !empty($fvm_settings['cdn']['domain'])) {
$url = str_replace('//'.$fvm_urls['wp_domain'], '//'.$fvm_settings['cdn']['domain'], $url);
}
return $url;
}
# get css font-face rules, original + simplified
function fvm_simplify_fontface($css_code) {
$mff = array();
$before = array();
$after = array();
# extract font faces
preg_match_all('/\@\s*font-face\s*\{([^}]+)\}/iUu', $css_code, $mff);
if(isset($mff[0]) && isset($mff[1]) && is_array($mff[1])) {
foreach($mff[1] as $kf=>$ff) {
# simplify font urls
$cssrules = preg_split("/;(?![^(]*\))/iu", $ff);
foreach ($cssrules as $k=>$csr) {
if(preg_match('/src\s*\:\s*url/Uui', $csr)) {
# woff
$fonts = array();
preg_match('/url\s*\(\s*[\'\"]*([^\'\"]*)[\'\"]*\)\s*format\s*\([\'\"]*woff[\'\"]*\s*\)/Uui', $csr, $fonts);
if(isset($fonts[0])) { $cssrules[$k] = 'src:'.$fonts[0]; break; }
# woff2
$fonts = array();
preg_match('/url\s*\(\s*[\'\"]*([^\'\"]*)[\'\"]*\)\s*format\s*\([\'\"]*woff2[\'\"]*\s*\)/Uui', $csr, $fonts);
if(isset($fonts[0])) { $cssrules[$k] = 'src:'.$fonts[0]; break; }
# svg
$fonts = array();
preg_match('/url\s*\(\s*[\'\"]*([^\'\"]*)[\'\"]*\)\s*format\s*\([\'\"]*svg[\'\"]*\s*\)/Uui', $csr, $fonts);
if(isset($fonts[0])) { $cssrules[$k] = 'src:'.$fonts[0]; break; }
# truetype
$fonts = array();
preg_match('/url\s*\(\s*[\'\"]*([^\'\"]*)[\'\"]*\)\s*format\s*\([\'\"]*truetype[\'\"]*\s*\)/Uui', $csr, $fonts);
if(isset($fonts[0])) { $cssrules[$k] = 'src:'.$fonts[0]; break; }
# delete other src:url rules
if(stripos($csr, 'format') === false) {
unset($cssrules[$k]);
}
}
}
# merge and create font face rule
$after[] = '@font-face{'.implode(';', $cssrules).'}';
# strip and collect
$before[] = $mff[0][$kf];
}
}
# return
if(count($before) > 0) {
return array('before'=>$before, 'after'=>$after);
} else {
return false;
}
}
# get css code from css file
function fvm_get_css_from_file($tag) {
# globals
global $fvm_settings;
# variables
$tvers = get_option('fvm_last_cache_update', '0');
# make sure we have a complete url
$href = fvm_normalize_url($tag->href);
# download, minify, cache (no ver query string)
$tkey = fvm_generate_hash_with_prefix($href, 'css');
$css = fvm_get_transient($tkey);
# download
if ($css === false) {
$ddl = array();
$ddl = fvm_maybe_download($href);
# error
if(isset($ddl['error'])) {
return array('error'=>$ddl['error'], 'tkey'=>$tkey, 'url'=> $href);
}
# success
if(isset($ddl['content'])) {
# minify flag
$min = true;
if(isset($fvm_settings['css']['min_disable']) && $fvm_settings['css']['min_disable'] == true) {
$min = false;
}
# minify
$css = fvm_maybe_minify_css_file($ddl['content'], $href, $min);
# quick integrity check
if($css !== false) {
# handle import rules
$css = fvm_replace_css_imports($css, $href);
$meta = json_encode(array('href'=>$href));
# save transient
$verify = fvm_set_transient(array('uid'=>$tkey, 'date'=>$tvers, 'type'=>'css', 'content'=>$css, 'meta'=>$meta));
# success, from download
return array('code'=>$css, 'tkey'=>$tkey, 'url'=> $href);
}
}
} else {
# success, from transient
return array('code'=>$css, 'tkey'=>$tkey, 'url'=> $href);
}
}
# get js code from css file
function fvm_get_js_from_file($tag) {
# globals
global $fvm_settings;
# variables
$tvers = get_option('fvm_last_cache_update', '0');
# make sure we have a complete url
$href = fvm_normalize_url($tag->src);
# download, minify, cache (no ver query string)
$tkey = fvm_generate_hash_with_prefix($href, 'js');
$js = fvm_get_transient($tkey);
# download
if ($js === false) {
$ddl = array();
$ddl = fvm_maybe_download($href);
# error
if(isset($ddl['error'])) {
return array('error'=>$ddl['error'], 'tkey'=>$tkey, 'url'=> $href);
}
# success
if(isset($ddl['content'])) {
# minify flag
$min = true;
if(isset($fvm_settings['js']['min_disable']) && $fvm_settings['js']['min_disable'] == true) {
$min = false;
}
# minify
$js = fvm_maybe_minify_js($ddl['content'], $href, $min);
# wrap with try catch
$js = fvm_try_catch_wrap($js, $href);
# quick integrity check
if($js !== false) {
# meta
$meta = json_encode(array('href'=>$href));
# save transient
$verify = fvm_set_transient(array('uid'=>$tkey, 'date'=>$tvers, 'type'=>'js', 'content'=>$js, 'meta'=>$meta));
# success, from download
return array('code'=>$js, 'tkey'=>$tkey, 'url'=> $href);
}
}
} else {
# success, from transient
return array('code'=>$js, 'tkey'=>$tkey, 'url'=> $href);
}
# fallback
return false;
}
# get transients
function fvm_get_transient($key, $check=null, $with_meta=null) {
# must have
global $wpdb;
if(is_null($wpdb)) { return false; }
$db_prefix = $wpdb->prefix;
try {
# check or fetch
if(!is_null($check)) {
$sql = $wpdb->prepare("SELECT id FROM {$db_prefix}fvm_cache WHERE uid = %s LIMIT 1", $key);
} else if (!is_null($with_meta)) {
$sql = $wpdb->prepare("SELECT date, content, meta FROM {$db_prefix}fvm_cache WHERE uid = %s LIMIT 1", $key);
} else {
$sql = $wpdb->prepare("SELECT content FROM {$db_prefix}fvm_cache WHERE uid = %s LIMIT 1", $key);
}
# get result from database
$result = $wpdb->get_row($sql);
# return true if just checking
if(!is_null($check) && isset($result->id)) {
return true;
}
# return content only
if(is_null($check) && is_null($with_meta) && isset($result->content)) {
return $result->content;
}
# return content and meta
if(is_null($check) && !is_null($with_meta) && isset($result->date) && isset($result->content) && isset($result->meta)) {
return array('date'=>$result->date, 'content'=>$result->content, 'meta'=>json_decode($result->meta, true), 'cache-method'=>$cache_method);
}
} catch (Exception $e) {
error_log('Error: '.$e->getMessage(), 0);
return false;
}
# fallback
return false;
}
# set cache
function fvm_set_transient($arr) {
# must have
if(!is_array($arr) || (is_array($arr) && (count($arr) == 0 || empty($arr)))) { return false; }
if(!isset($arr['uid']) || !isset($arr['date']) || !isset($arr['type']) || !isset($arr['content'])) { return false; }
# normalize unknown keys
if(strlen($arr['uid']) != 64) { $arr['uid'] = fvm_generate_hash_with_prefix($arr['uid'], $arr['type']); }
# check if it already exists, return early if it does
$status = fvm_get_transient($arr['uid'], true);
if($status) { return $arr['uid']; }
# must have
global $wpdb;
if(is_null($wpdb)) { return false; }
$db_prefix = $wpdb->prefix;
# initialize arrays (fields, types, values)
$fld = array();
$tpe = array();
$vls = array();
# define possible data types
$str = array('uid', 'type', 'content', 'meta');
$int = array('date');
$all = array_merge($str, $int);
# process only recognized columns
foreach($arr as $k=>$v) {
if(in_array($k, $all)) {
if(in_array($k, $str)) { $tpe[] = '%s'; } else { $tpe[] = '%d'; }
$fld[] = $k;
$vls[] = $v;
}
}
try {
# prepare and insert to database
$result = $wpdb->query($wpdb->prepare("INSERT IGNORE INTO {$db_prefix}fvm_cache (".implode(', ', $fld).") VALUES (".implode(', ', $tpe).")", $vls));
# success
if($result) {
return $arr['uid'];
}
} catch (Exception $e) {
error_log('Error: '.$e->getMessage(), 0);
}
# fallback
return false;
}
# delete transient
function fvm_del_transient($key) {
# normalize unknown keys
if(strlen($key) != 64) { $key = fvm_generate_hash_with_prefix($key, ''); }
# must have
global $wpdb;
if(is_null($wpdb)) { return false; }
$db_prefix = $wpdb->prefix;
try {
# delete
$wpdb->query($wpdb->prepare("DELETE FROM {$db_prefix}fvm_cache WHERE uid = %s", $key));
return true;
} catch (Exception $e) {
error_log('Error: '.$e->getMessage(), 0);
}
# fallback
return false;
}
# functions, get full url
function fvm_normalize_url($href, $purl=null) {
# preserve empty source handles
$href = trim($href);
if(empty($href)) { return false; }
# some fixes
$href = str_replace(array('&#038;', '&amp;'), '&', $href);
# external url
if(!is_null($purl) && !empty($purl)) {
$parse = parse_url($purl);
} else {
# local url
global $fvm_urls;
$parse = parse_url($fvm_urls['wp_site_url']);
}
# domain info
$scheme = $parse['scheme'];
$host = $parse['host'];
$path = $parse['path'];
# relative to full urls
if (substr($href, 0, 2) === "//") {
$href = $scheme.':'.$href; # scheme missing
} else if (substr($href, 0, 1) === "/") {
$href = $scheme.'://'.$host . $href; # scheme and domain missing
} else if (substr($href, 0, 3) === '../' && !is_null($purl) && !empty($purl)) {
$href = $scheme.':'.$host . dirname($path) . '/' . $href;
} else if ($scheme == 'https' && substr($href, 0, 4) == 'http' && substr($href, 0, 5) !== $scheme) {
$href = str_replace('http://', 'https://', $href); # force https
} else {
# url should be fine
}
# prevent double forward slashes in the middle
$href = str_replace('###', '://', str_replace('//', '/', str_replace('://', '###', $href)));
return $href;
}
# minify ld+json scripts
function fvm_minify_microdata($data) {
$data = trim(preg_replace('/(\v)+(\h)+[\/]{2}(.*)+(\v)+/u', '', $data));
$data = trim(preg_replace('/\s+/u', ' ', $data));
$data = str_replace(array('" ', ' "'), '"', $data);
$data = str_replace(array('[ ', ' ['), '[', $data);
$data = str_replace(array('] ', ' ]'), ']', $data);
$data = str_replace(array('} ', ' }'), '}', $data);
$data = str_replace(array('{ ', ' {'), '{', $data);
return $data;
}
# check for php or html, skip if found
function fvm_not_php_html($code) {
# return early if not html
$code = trim($code);
$a = '<!doctype'; # start
$b = '<html'; # start
$c = '<?xml'; # start
$d = '<?php'; # anywhere
if ( strcasecmp(substr($code, 0, strlen($a)), $a) != 0 && strcasecmp(substr($code, 0, strlen($b)), $b) != 0 && strcasecmp(substr($code, 0, strlen($c)), $c) != 0 && stripos($code, $d) === false ) {
return true;
}
return false;
}
# find if a string looks like HTML content
function fvm_is_html($html) {
# return early if it's html
$html = trim($html);
$a = '<!doctype';
$b = '<html';
if ( strcasecmp(substr($html, 0, strlen($a)), $a) == 0 || strcasecmp(substr($html, 0, strlen($b)), $b) == 0 ) {
return true;
}
# must have html
$hfound = array(); preg_match_all('/<\s?(html)+(.*)>(.*)<\s?\/\s?html\s?>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { return false; }
# must have head
$hfound = array(); preg_match_all('/<\s?(head)+(.*)>(.*)<\s?\/\s?head\s?>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { return false; }
# must have body
$hfound = array(); preg_match_all('/<\s?(body)+(.*)>(.*)<\s?\/\s?body\s?>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { return false; }
# must have at least one of these
$count = 0;
# css link
$hfound = array(); preg_match_all('/<\s?(link)+(.*)(rel|href)+(.*)>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { $count++; }
# style
$hfound = array(); preg_match_all('/<\s?(style)+(.*)(src)+(.*)>(.*)<\s?\/\s?style\s?>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { $count++; }
# script
$hfound = array(); preg_match_all('/<\s?(script)+(.*)(src)+(.*)>(.*)<\s?\/\s?script\s?>/Uuis', $html, $hfound);
if(!isset($hfound[0][0])) { $count++; }
# return if not
if($count == 0) { return false; }
# else, it's likely html
return true;
}
# ensure that string is utf8
function fvm_ensure_utf8($str) {
$enc = mb_detect_encoding($str, mb_list_encodings(), true);
if ($enc === false){
return false; // could not detect encoding
} else if ($enc !== "UTF-8") {
return mb_convert_encoding($str, "UTF-8", $enc); // converted to utf8
} else {
return $str; // already utf8
}
# fail
return false;
}
# check if we can process the page, minimum filters
function fvm_can_process_common() {
global $fvm_settings, $fvm_urls;
# only GET requests allowed
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
return false;
}
# always skip on these tasks
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){ return false; }
if( defined('WP_INSTALLING') && WP_INSTALLING ){ return false; }
if( defined('WP_REPAIRING') && WP_REPAIRING ){ return false; }
if( defined('WP_IMPORTING') && WP_IMPORTING ){ return false; }
if( defined('DOING_AJAX') && DOING_AJAX ){ return false; }
if( defined('WP_CLI') && WP_CLI ){ return false; }
if( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ){ return false; }
if( defined('WP_ADMIN') && WP_ADMIN ){ return false; }
if( defined('SHORTINIT') && SHORTINIT ){ return false; }
if( defined('IFRAME_REQUEST') && IFRAME_REQUEST ){ return false; }
# detect api requests (only defined after parse_request hook)
if( defined('REST_REQUEST') && REST_REQUEST ){ return false; }
# don't minify specific WordPress areas
if(function_exists('is_404') && is_404()){ return false; }
if(function_exists('is_feed') && is_feed()){ return false; }
if(function_exists('is_comment_feed') && is_comment_feed()){ return false; }
if(function_exists('is_attachment') && is_attachment()){ return false; }
if(function_exists('is_trackback') && is_trackback()){ return false; }
if(function_exists('is_robots') && is_robots()){ return false; }
if(function_exists('is_preview') && is_preview()){ return false; }
if(function_exists('is_customize_preview') && is_customize_preview()){ return false; }
if(function_exists('is_embed') && is_embed()){ return false; }
if(function_exists('is_admin') && is_admin()){ return false; }
if(function_exists('is_blog_admin') && is_blog_admin()){ return false; }
if(function_exists('is_network_admin') && is_network_admin()){ return false; }
# don't minify specific WooCommerce areas
if(function_exists('is_checkout') && is_checkout()){ return false; }
if(function_exists('is_account_page') && is_account_page()){ return false; }
if(function_exists('is_ajax') && is_ajax()){ return false; }
if(function_exists('is_wc_endpoint_url') && is_wc_endpoint_url()){ return false; }
# get requested hostname
$host = fvm_get_domain();
# only for hosts matching the site_url
if(isset($fvm_urls['wp_domain']) && !empty($fvm_urls['wp_domain'])) {
if($host != $fvm_urls['wp_domain']) {
return false;
}
}
# if there is an url, skip common static files
if(isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
# parse url (path, query)
$ruri = fvm_get_uripath();
# no cache by extension as well, such as robots.txt and other situations
$noext = array('.txt', '.xml', '.xsl', '.map', '.css', '.js', '.png', '.jpeg', '.jpg', '.gif', '.webp', '.ico', '.php', '.htaccess', '.json', '.pdf', '.mp4', '.webm');
foreach ($noext as $ext) {
if(substr($ruri, -strlen($ext)) == $ext) {
return false;
}
}
}
# default
return true;
}
# check if the user is logged in, and if the user role allows optimization
function fvm_user_role_processing_allowed($group) {
if(function_exists('is_user_logged_in') && function_exists('wp_get_current_user')) {
if(is_user_logged_in()) {
# get user roles
global $fvm_settings;
$user = wp_get_current_user();
$roles = (array) $user->roles;
foreach($roles as $role) {
if(isset($fvm_settings['minify'][$role]) && $fvm_settings['minify'][$role] == true) {
return true;
}
}
# disable for other logged in users by default
return false;
}
}
# allow by default
return true;
}
# check if we can process the page, minimum filters
function fvm_can_process_query_string($loc) {
# host and uri path
$host = fvm_get_domain();
$request_uri = fvm_get_uripath(true);
$scheme = fvm_get_scheme();
$url = $scheme.'://'.$host.$request_uri;
$parse = parse_url($url);
# parse query string to array, check if should be ignored
if(isset($parse["query"]) && !empty($parse["query"])) {
# check
$qsarr = array(); parse_str($parse["query"], $qsarr);
# allowed queries by default
if(isset($qsarr['s'])) { unset($qsarr['s']); } # search
if(isset($qsarr['lang'])) { unset($qsarr['lang']); } # wpml
# if there are other queries left, bypass cache
if(count($qsarr) > 0) {
return false;
}
}
# allow by default
return true;
}
# check if page is amp
function fvm_is_amp_page() {
# don't minify amp pages by the amp plugin
if(function_exists('is_amp_endpoint') && is_amp_endpoint()){ return true; }
if(function_exists('ampforwp_is_amp_endpoint') && ampforwp_is_amp_endpoint()){ return true; }
# query string or /amp/
if(isset($_GET['amp'])) { return true; }
if(substr(fvm_get_uripath(), -5) == '/amp/') { return true; }
# not amp
return false;
}
# validate and minify css
function fvm_maybe_minify_css_file($css, $url, $min) {
# process css only if it's not php or html
if(fvm_not_php_html($css)) {
global $fvm_settings, $fvm_urls;
# do not minify files in the ignore list
if(isset($fvm_settings['css']['css_ignore_min']) && !empty($fvm_settings['css']['css_ignore_min'])) {
$arr = fvm_string_toarray($fvm_settings['css']['css_ignore_min']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $e) {
if(stripos($url, $e) !== false) {
$min = false;
break;
}
}
}
}
# filtering
$css = fvm_ensure_utf8($css);
$css = str_ireplace('@charset "UTF-8";', '', $css);
# remove query strings from fonts
$css = preg_replace('/(.eot|.woff2|.woff|.ttf)+[?+](.+?)(\)|\'|\")/ui', "$1"."$3", $css);
# remove sourceMappingURL
$css = preg_replace('/(\/\/\s*[#]\s*sourceMappingURL\s*[=]\s*)([a-zA-Z0-9-_\.\/]+)(\.map)/ui', '', $css);
$css = preg_replace('/(\/[*]\s*[#]\s*sourceMappingURL\s*[=]\s*)([a-zA-Z0-9-_\.\/]+)(\.map)\s*[*]\s*[\/]/ui', '', $css);
# fix url paths
if(!empty($url)) {
$matches = array(); preg_match_all("/url\(\s*['\"]?(?!data:)(?!http)(?![\/'\"])(.+?)['\"]?\s*\)/ui", $css, $matches);
foreach($matches[1] as $a) { $b = trim($a); if($b != $a) { $css = str_replace($a, $b, $css); } }
$css = preg_replace("/url\(\s*['\"]?(?!data:)(?!http)(?![\/'\"#])(.+?)['\"]?\s*\)/ui", "url(".dirname($url)."/$1)", $css);
}
# minify string with relative urls
if($min === true) {
$css = fvm_minify_css_string($css, $url);
}
# add font-display block for all font faces
# https://developers.google.com/web/updates/2016/02/font-display
$css = preg_replace_callback('/(?:@font-face)\s*{(?<value>[^}]+)}/i',
function ($matches) {
if ( preg_match('/font-display:\s*(?<swap_value>\w*);?/i', $matches['value'], $attribute)) {
return 'swap' === strtolower($attribute['swap_value']) ? $matches[0] : str_replace($attribute['swap_value'], 'swap', $matches[0]);
} else {
$swap = "font-display:swap;{$matches['value']}";
}
return str_replace( $matches['value'], $swap, $matches[0] );
},
$css
);
# make relative urls when possible
# get root url, preserve subdirectories
if(isset($fvm_urls['wp_site_url']) && !empty($fvm_urls['wp_site_url'])) {
# parse url and extract domain without uri path
$use_url = $fvm_urls['wp_site_url'];
$parse = parse_url($use_url);
if(isset($parse['path']) && !empty($parse['path']) && $parse['path'] != '/') {
$use_url = str_replace(str_replace($use_url, $parse['path'], $use_url), '', $use_url);
}
# adjust paths
$bgimgs = array();
preg_match_all ('/url\s*\(\s*[\'\"]*([^;\'\"]*)[\'\"]*\)/Uui', $css, $bgimgs);
if(isset($bgimgs[1]) && is_array($bgimgs[1])) {
foreach($bgimgs[1] as $img) {
if(stripos($img, 'http') !== false || stripos($img, '//') !== false) {
# normalize
$newimg = fvm_normalize_url($img);
if($newimg != $img) { $css = str_replace($img, $newimg, $css); $img = $newimg; }
# process
if(substr($img, 0, strlen($use_url)) == $use_url) {
$pos = strpos($img, $use_url);
if ($pos !== false) {
# relative path image
$relimg = '/' . ltrim(substr_replace($img, '', $pos, strlen($use_url)), '/');
# replace url
$css = str_replace($img, $relimg, $css);
}
}
}
}
}
# remove empty url()
$css = preg_replace('/url\s*\(\s*[\'"]?\s*[\'"]?\)/Uui', 'none', $css);
# relative paths
$css = str_replace('https://'.$fvm_urls['wp_domain'], '', $css);
$css = str_replace('http://'.$fvm_urls['wp_domain'], '', $css);
$css = str_replace('//'.$fvm_urls['wp_domain'], '', $css);
# fixes
$css = str_replace('/./', '/', $css);
}
# simplify font face
$arr = fvm_simplify_fontface($css);
if($arr !== false && is_array($arr)) {
$css = str_replace($arr['before'], $arr['after'], $css);
}
# return css
return trim($css);
}
return false;
}
# validate and minify js
function fvm_maybe_minify_js($js, $url, $enable_js_minification) {
# ensure it's utf8
$js = fvm_ensure_utf8($js);
# return early if empty
if(empty($js) || $js == false) { return false; }
# process js only if it's not php or html
if(fvm_not_php_html($js)) {
# globals
global $fvm_settings;
# filtering
$js = fvm_ensure_utf8($js);
# remove sourceMappingURL
$js = preg_replace('/(\/\/\s*[#]\s*sourceMappingURL\s*[=]\s*)([a-zA-Z0-9-_\.\/]+)(\.map)/ui', '', $js);
$js = preg_replace('/(\/[*]\s*[#]\s*sourceMappingURL\s*[=]\s*)([a-zA-Z0-9-_\.\/]+)(\.map)\s*[*]\s*[\/]/ui', '', $js);
# minify?
if($enable_js_minification == true) {
# PHP Minify from https://github.com/matthiasmullie/minify
$minifier = new FVM\MatthiasMullie\Minify\JS($js);
$min = $minifier->minify();
# return if not empty
if($min !== false && strlen(trim($min)) > 0) {
return $min;
}
}
# return js
return trim($js);
}
return false;
}
# minify css string with PHP Minify
function fvm_minify_css_string($css) {
# return early if empty
if(empty($css) || $css == false) { return $css; }
# minify
$minifier = new FVM\MatthiasMullie\Minify\CSS($css);
$minifier->setMaxImportSize(10); # embed assets up to 10 Kb (default 5Kb) - processes gif, png, jpg, jpeg, svg & woff
$min = $minifier->minify();
# return
if($min != false) {
return $min;
}
# fallback
return $css;
}
# escape html tags for document.write
function fvm_escape_url_js($str) {
$str = trim(preg_replace('/[\t\n\r\s]+/iu', ' ', $str));
return str_replace(array('\\\\\"', '\\\\"', '\\\"', '\\"'), '\"', json_encode($str));
}
# try catch wrapper for merged javascript
function fvm_try_catch_wrap($js, $href=null) {
$loc = ''; if(isset($href)) { $loc = '[ File: '. $href . ' ] '; }
return 'try{'. PHP_EOL . $js . PHP_EOL . '}catch(e){console.error("An error has occurred. '.$loc.'[ "+e.stack+" ]");}';
}
# Disable the emoji's on the frontend
function fvm_disable_emojis() {
global $fvm_settings;
if(isset($fvm_settings['html']['disable_emojis']) && $fvm_settings['html']['disable_emojis'] == true) {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
}
}
# stop slow ajax requests for bots
function fvm_ajax_optimizer() {
if(isset($_SERVER['HTTP_USER_AGENT']) && (defined('DOING_AJAX') && DOING_AJAX) || (function_exists('is_ajax') && is_ajax()) || (function_exists('wp_doing_ajax') && wp_doing_ajax())){
if (preg_match('/'.implode('|', array('x11.*ox\/54', 'id\s4.*us.*ome\/62', 'oobo', 'ight', 'tmet', 'eadl', 'ngdo', 'PTST')).'/i', $_SERVER['HTTP_USER_AGENT'])){ echo '0'; exit(); }
}
}
# rewrite assets to cdn
function fvm_rewrite_assets_cdn($html) {
# settings
global $fvm_settings, $fvm_urls;
if(isset($fvm_urls['wp_domain']) && !empty($fvm_urls['wp_domain']) &&
isset($fvm_settings['cdn']['enable']) && $fvm_settings['cdn']['enable'] == true &&
isset($fvm_settings['cdn']['domain']) && !empty($fvm_settings['cdn']['domain']) &&
isset($fvm_settings['cdn']['integration']) && !empty($fvm_settings['cdn']['integration'])) {
$arr = fvm_string_toarray($fvm_settings['cdn']['integration']);
if(is_array($arr) && count($arr) > 0) {
foreach($html->find(implode(', ', $arr) ) as $elem) {
# preserve some attributes but replace others
if (is_object($elem) && isset($elem->attr)) {
# get all attributes
foreach ($elem->attr as $key=>$val) {
# skip href attribute for links
if($key == 'href' && stripos($elem->outertext, '<a ') !== false) { continue; }
# skip certain attributes
if(in_array($key, array('id', 'class', 'action'))) { continue; }
# replace other attributes
$elem->{$key} = str_replace('//'.$fvm_urls['wp_domain'], '//'.$fvm_settings['cdn']['domain'], $elem->{$key});
$elem->{$key} = str_replace('\/\/'.$fvm_urls['wp_domain'], '\/\/'.$fvm_settings['cdn']['domain'], $elem->{$key});
}
}
}
}
}
return $html;
}
# try to open the file from the disk, before downloading
function fvm_maybe_download($url) {
# must have
if(is_null($url) || empty($url)) { return false; }
# get domain
global $fvm_urls;
# check if we can open the file locally first
if (stripos($url, $fvm_urls['wp_domain']) !== false && defined('ABSPATH') && !empty('ABSPATH')) {
# file path + windows compatibility
$f = strtok(str_replace('/', DIRECTORY_SEPARATOR, str_replace(rtrim($fvm_urls['wp_site_url'], '/'), rtrim(ABSPATH, '/'), $url)), '?');
# did it work?
if (file_exists($f) && is_file($f)) {
return array('content'=>file_get_contents($f), 'src'=>'Disk');
}
}
# fallback to downloading
# this useragent is needed for google fonts (woff files only + hinted fonts)
$uagent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
# fetch via wordpress functions
$response = wp_remote_get($url, array('user-agent'=>$uagent, 'timeout' => 7, 'httpversion' => '1.1', 'sslverify'=>false));
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
return array('error'=>"Something went wrong: $error_message");
} else {
return array('content'=>wp_remote_retrieve_body($response), 'src'=>'Web');
}
}
# add our function in the header
function fvm_add_header_function($html) {
# create function
$lst = array('x11.*ox\/54', 'id\s4.*us.*ome\/62', 'oobo', 'ight', 'tmet', 'eadl', 'ngdo', 'PTST');
$fvmf = '<script data-cfasync="false">function fvmuag(){var e=navigator.userAgent;if(e.match(/'.implode('|', $lst).'/i))return!1;if(e.match(/x11.*me\/86\.0/i)){var r=screen.width;if("number"==typeof r&&1367==r)return!1}return!0}</script>';
# remove duplicates
if(stripos($html, $fvmf) !== false) {
$html = str_ireplace($fvmf, '', $html);
}
# add function
$html = str_replace('<!-- h_header_function -->', $fvmf, $html);
return $html;
}
# add lazy load library
function fvm_add_delay_scripts_logic($html) {
# based on v2.0.0: https://github.com/shinsenter/defer.js
# delay to interaction
$scripts = <<<'EOF'
<script type='text/javascript' id='fvm-delayjs' data-cfasync='false'>
!function(k,e,x){function r(d,a,g,b){return b=(a?e.getElementById(a):t)||e.createElement(d||"SCRIPT"),a&&(b.id=a),g&&(b.onload=g),b}function u(d){f(function(a){a=[].slice.call(e.querySelectorAll(d));(function v(b,c){if(b=a.shift()){b.parentNode.removeChild(b);var l=b,m,n=void 0;var p=r(l.nodeName);var q=0;for(m=l.attributes;q<m.length;q++)"type"!=(n=m[q]).name&&p.setAttribute(n.name,n.value);(c=(p.text=l.text,p)).src&&!c.hasAttribute("async")?(c.onload=c.onerror=v,e.head.appendChild(c)):(e.head.appendChild(c),
v())}})()})}var f,t,h=[],w=/p/.test(e.readyState);Function();(f=function(d,a){w?x(d,a):h.push(d,a)}).all=u;f.js=function(d,a,g,b){f(function(c){(c=r(t,a,b)).src=d;e.head.appendChild(c)},g)};k.addEventListener("onpageshow"in k?"pageshow":"load",function(){for(w=!u();h[0];)f(h.shift(),h.shift())});k.Defer=f}(this,document,setTimeout);
const userInteractionEvents=["mouseover","keydown","touchstart","touchmove","wheel"];userInteractionEvents.forEach(function(event){window.addEventListener(event,triggerScriptLoader,{passive:!0})});function triggerScriptLoader(){fvmloadscripts();userInteractionEvents.forEach(function(event){window.removeEventListener(event,triggerScriptLoader,{passive:!0})})}function fvmloadscripts(){Defer.all('script[type="fvm-script-delay"]')};
</script>
EOF;
# add code
return str_replace('<!-- h_footer_fvm_scripts -->', '<!-- h_footer_fvm_scripts -->' . $scripts, $html);
}
# get the domain name
function fvm_get_scheme() {
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') { return 'https'; }
if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) { return 'https'; }
if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { return 'https'; }
return 'http';
}
# get the domain name
function fvm_get_domain() {
if (function_exists('site_url')) {
$parse = parse_url(site_url());
return $parse['host'];
} elseif(isset($_SERVER['SERVER_NAME']) && !empty($_SERVER['SERVER_NAME'])) {
return $_SERVER['SERVER_NAME'];
} elseif (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) {
return $_SERVER['HTTP_HOST'];
} else {
return false;
}
}
# get the settings file path, current domain name, and uri path without query strings
function fvm_get_uripath($full=null) {
if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
# full or no query string
if(!is_null($full)) {
$current_uri = trim($_SERVER['REQUEST_URI']);
} else {
$current_uri = strtok($_SERVER['REQUEST_URI'], '?');
}
# filter
$current_uri = str_replace('//', '/', str_replace('..', '', preg_replace( '/[ <>\'\"\r\n\t\(\)]/', '', $current_uri)));
return $current_uri;
} else {
return false;
}
}
\ No newline at end of file
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# functions needed only for frontend ###########
# must have for large strings processing during minification
@ini_set('pcre.backtrack_limit', 5000000);
@ini_set('pcre.recursion_limit', 5000000);
# our own minification libraries
include_once($fvm_var_inc_lib . DIRECTORY_SEPARATOR . 'raisermin' . DIRECTORY_SEPARATOR . 'minify.php');
# php simple html
# https://sourceforge.net/projects/simplehtmldom/
include_once($fvm_var_inc_lib . DIRECTORY_SEPARATOR . 'simplehtmldom' . DIRECTORY_SEPARATOR . 'simple_html_dom.php');
# PHP Minify [1.3.60] for CSS minification only
# https://github.com/matthiasmullie/minify
$fvm_var_inc_lib_mm = $fvm_var_inc_lib . DIRECTORY_SEPARATOR . 'matthiasmullie' . DIRECTORY_SEPARATOR;
include_once($fvm_var_inc_lib_mm . 'minify' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Minify.php');
include_once($fvm_var_inc_lib_mm . 'minify' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'CSS.php');
include_once $fvm_var_inc_lib_mm . 'minify'. DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR .'JS.php';
include_once $fvm_var_inc_lib_mm . 'minify'. DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR .'Exception.php';
include_once $fvm_var_inc_lib_mm . 'minify'. DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR .'Exceptions'. DIRECTORY_SEPARATOR .'BasicException.php';
include_once $fvm_var_inc_lib_mm . 'minify'. DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR .'Exceptions'. DIRECTORY_SEPARATOR .'FileImportException.php';
include_once $fvm_var_inc_lib_mm . 'minify'. DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR .'Exceptions'. DIRECTORY_SEPARATOR .'IOException.php';
include_once($fvm_var_inc_lib_mm . 'path-converter' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'ConverterInterface.php');
include_once($fvm_var_inc_lib_mm . 'path-converter' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Converter.php');
################################################
# start buffering before template
function fvm_start_buffer() {
if(fvm_can_minify_css() || fvm_can_minify_js() || fvm_can_process_html()) {
ob_start('fvm_process_page', 0, PHP_OUTPUT_HANDLER_REMOVABLE);
}
}
# process html from fvm_end_buffer
function fvm_process_page($html) {
# get globals
global $fvm_settings, $fvm_cache_paths, $fvm_urls;
# get html into an object
# https://simplehtmldom.sourceforge.io/manual.htm
$html_object = str_get_html($html, false, true, 'UTF-8', false, PHP_EOL, ' ');
# return early if html is not an object, or overwrite html into an object for processing
if (!is_object($html_object)) {
return $html . '<!-- simplehtmldom failed to process the html -->';
} else {
$html = $html_object;
}
# get globals
global $fvm_settings, $fvm_urls;
# defaults
$tvers = get_option('fvm_last_cache_update', '0');
$htmlpreloads = array();
$htmlcssheader = array();
$htmljsheader = array();
$htmljsdefer = array();
# collect all link preload headers, skip amp
if(fvm_is_amp_page() !== true) {
# skip on web stories
if(count($html->find('script[src*=cdn.ampproject.org]')) > 0) {
return $html . '<!-- FVM does not support AMP -->';
}
# add other preloads
foreach($html->find('link[rel=preload]') as $tag) {
$htmlpreloads[] = $tag->outertext;
$tag->outertext = '';
}
}
# START CSS PROCESSING
if(fvm_can_minify_css()) {
# defaults
$fvm_styles = array();
$allcss = array();
$css_lowpriority_code = '';
# start log
$log = array();
$css_total = 0;
# start log
$log[]= 'PAGE - '. fvm_get_uripath(true) . PHP_EOL . '---' . PHP_EOL;
# exclude styles and link tags inside scripts, no scripts or html comments
$excl = array();
foreach($html->find('script link[rel=stylesheet], script style, noscript style, noscript link[rel=stylesheet], comment') as $element) {
$excl[] = $element->outertext;
}
# collect all styles, but filter out if excluded
foreach($html->find('link[rel=stylesheet], style') as $element) {
if(!in_array($element->outertext, $excl)) {
$allcss[] = $element;
}
}
# START CSS LOOP
foreach($allcss as $k=>$tag) {
# mediatypes
if(isset($tag->media)) {
# Normalize mediatypes
if($tag->media == 'screen' || $tag->media == 'screen, print' || strlen($tag->media) == 0) {
$tag->media = 'all';
}
# Remove print styles
if(isset($fvm_settings['css']['noprint']) && $fvm_settings['css']['noprint'] == true && $tag->media == 'print'){
$tag->outertext = '';
unset($allcss[$k]);
continue;
}
} else {
# must have
$tag->media = 'all';
}
# START CSS FILES
if($tag->tag == 'link' && isset($tag->href)) {
# filter url
$href = fvm_normalize_url($tag->href);
# Ignore css files
$ignore_css_merging = false;
if(isset($fvm_settings['css']['ignore']) && !empty($fvm_settings['css']['ignore'])) {
$arr = fvm_string_toarray($fvm_settings['css']['ignore']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $e) {
if(stripos($href, $e) !== false) {
unset($allcss[$k]);
continue 2;
}
}
}
}
# Remove CSS files
if(isset($fvm_settings['css']['remove']) && !empty($fvm_settings['css']['remove'])) {
$arr = fvm_string_toarray($fvm_settings['css']['remove']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $e) {
if(stripos($href, $e) !== false) {
$tag->outertext = '';
unset($allcss[$k]);
continue 2;
}
}
}
}
# css merging functionality
if(isset($fvm_settings['css']['combine']) && $fvm_settings['css']['combine'] == true) {
# download or fetch from transient, minified
$css = fvm_get_css_from_file($tag);
if($css !== false && is_array($css)) {
# error
if(isset($css['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$css['error'].' */'. PHP_EOL . $tag->outertext;
unset($allcss[$k]);
continue;
}
# extract fonts and icons
if(isset($fvm_settings['css']['fonts']) && $fvm_settings['css']['fonts'] == true) {
$extract_fonts_arr = fvm_extract_fonts($css['code']);
$css_lowpriority_code.= '/* '.$href.' */'. PHP_EOL . $extract_fonts_arr['fonts'];
$css_code = $extract_fonts_arr['code'];
} else {
$css_code = $css['code'];
}
# async from the list only
if(isset($fvm_settings['css']['async']) && $fvm_settings['css']['async'] == true) {
if(isset($fvm_settings['css']['async']) && !empty($fvm_settings['css']['async'])) {
$arr = fvm_string_toarray($fvm_settings['css']['async']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($href, $aa) !== false) {
# save css for merging
$fvm_styles[$tag->media]['async'][] = $css_code;
# log
$size = strlen($css['code']);
$css_total = $css_total + $size;
$log[] = '[CSS Async: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $css['url']). PHP_EOL;
# finish early
$tag->outertext = '';
unset($allcss[$k]);
continue 2;
}
}
}
}
}
# else render block
# save css for merging as fallback
$fvm_styles[$tag->media]['block'][] = $css_code;
# log
$size = strlen($css['code']);
$css_total = $css_total + $size;
$log[] = '[CSS Block: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $css['url']). PHP_EOL;
# finish early
$tag->outertext = '';
unset($allcss[$k]);
continue;
}
}
# minify individually, if enabled
if(!isset($fvm_settings['css']['min_disable']) || (isset($fvm_settings['css']['min_disable'])&& $fvm_settings['css']['min_disable'] != true)) {
# download or fetch from transient, minified
$css = fvm_get_css_from_file($tag);
if($css !== false && is_array($css)) {
# error
if(isset($css['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$css['error'].' */'. PHP_EOL . $tag->outertext;
unset($allcss[$k]);
continue;
}
# extract fonts and icons
if(isset($fvm_settings['css']['fonts']) && $fvm_settings['css']['fonts'] == true) {
$extract_fonts_arr = fvm_extract_fonts($css['code']);
$css_lowpriority_code.= '/* '.$href.' */'. PHP_EOL . $extract_fonts_arr['fonts'];
$css_code = $extract_fonts_arr['code'];
} else {
$css_code = $css['code'];
}
# empty files
if(empty(trim($css_code))) {
$tag->outertext = '';
unset($allcss[$k]);
continue;
} else {
$css_code = '/* '.$href.' */'. PHP_EOL . $css_code;
}
# generate url
$ind_css_url = fvm_generate_min_url($href, $css['tkey'], 'css', $css_code);
# cdn
if(isset($fvm_settings['cdn']['cssok']) && $fvm_settings['cdn']['cssok'] == true) {
$ind_css_url = fvm_rewrite_cdn_url($ind_css_url);
}
# async from the list only
if(isset($fvm_settings['css']['async']) && !empty($fvm_settings['css']['async'])) {
$arr = fvm_string_toarray($fvm_settings['css']['async']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($href, $aa) !== false) {
# async attributes
$tag->rel = 'preload';
$tag->as = 'style';
$tag->onload = "this.rel='stylesheet';this.onload=null";
# log
$size = strlen($css['code']);
$css_total = $css_total + $size;
$log[] = '[CSS Async: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $css['url']). PHP_EOL;
# finish early
$tag->href = $ind_css_url;
unset($allcss[$k]);
continue 2;
}
}
}
}
# force render blocking for other files
# http and html preload for render blocking css
if(!isset($fvm_settings['css']['nopreload']) || (isset($fvm_settings['css']['nopreload']) && $fvm_settings['css']['nopreload'] != true)) {
$htmlpreloads[] = '<link rel="preload" href="'.$ind_css_url.'" as="style" media="'.$tag->media.'" />';
}
# log
$size = strlen($css['code']);
$css_total = $css_total + $size;
$log[] = '[CSS Block: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $css['url']). PHP_EOL;
# finish early
$tag->href = $ind_css_url;
unset($allcss[$k]);
}
}
}
# END CSS FILES
# START STYLE TAGS
if($tag->tag == 'style' && !isset($tag->href)) {
# remove if empty
if(strlen(trim($tag->innertext)) == 0) {
$tag->outertext = '';
unset($allcss[$k]);
continue;
}
# default
$css = $tag->innertext;
# minify?
if(!isset($fvm_settings['css']['min_disable_styles']) || (isset($fvm_settings['css']['min_disable_styles'])&& $fvm_settings['css']['min_disable_styles'] != true)) {
$css = fvm_minify_css_string($css);
}
# handle import rules
$css = fvm_replace_css_imports($css);
# simplify font face
$arr = fvm_simplify_fontface($css);
if($arr !== false && is_array($arr)) {
$css = str_replace($arr['before'], $arr['after'], $css);
}
# extract fonts and icons
if(isset($fvm_settings['css']['fonts']) && $fvm_settings['css']['fonts'] == true) {
$extract_fonts_arr = fvm_extract_fonts($css);
$css_lowpriority_code.= $extract_fonts_arr['fonts'];
$css = $extract_fonts_arr['code'];
}
# add filtered css code
if(!empty($css)) {
$tag->innertext = $css;
unset($allcss[$k]);
continue;
}
}
# END STYLE TAGS
}
# END CSS LOOP
# START CSS LOG
if(count($log) > 1) {
$log[] = str_pad('-', 22, '-',STR_PAD_LEFT) . PHP_EOL;
$log[] = '[CSS Total: '.str_pad(fvm_format_filesize($css_total), 9,' ',STR_PAD_LEFT).']' . PHP_EOL;
$log[] = str_pad('-', 22, '-',STR_PAD_LEFT);
fvm_save_log(array('type'=>'min','msg'=>implode('', $log)));
}
# END CSS LOG
# START OPTIMIZED FONT DELIVERY
if(!empty($css_lowpriority_code)) {
# minify?
if(!isset($fvm_settings['css']['min_disable']) || (isset($fvm_settings['css']['min_disable'])&& $fvm_settings['css']['min_disable'] != true)) {
$css_lowpriority_code = fvm_minify_css_string($css_lowpriority_code);
}
# save transient, if not yet saved
$tkey = fvm_generate_hash_with_prefix(hash('sha256', $css_lowpriority_code), 'css');
# generate url
$css_fonts_url = fvm_generate_min_url('fonts', $tkey, 'css', $css_lowpriority_code);
# cdn
if(isset($fvm_settings['cdn']['cssok']) && $fvm_settings['cdn']['cssok'] == true) {
$css_fonts_url = fvm_rewrite_cdn_url($css_fonts_url);
}
# preload
$htmlcssheader[0] = '<link id="fvm-fonts" rel="stylesheet" href="'.$css_fonts_url.'" media="fonts" onload="if(fvmuag()){this.media=\'all\'}" />';
}
# END OPTIMIZED FONT DELIVERY
# START COMBINING CSS
if(is_array($fvm_styles) && count($fvm_styles) > 0) {
# process mediatypes
foreach ($fvm_styles as $mediatype=>$css_arr) {
# process types, block or async
foreach ($css_arr as $css_method=>$css_arr2) {
# merge and hash
$merged_css = implode(PHP_EOL, $css_arr2);
$tkey = fvm_generate_hash_with_prefix(hash('sha256', $merged_css), 'css');
# inline if small
if(strlen($merged_css) < 15000 && $css_method == 'block') {
$htmlcssheader[] = '<style type="text/css" media="'.$mediatype.'">'.$merged_css.'</style>';
continue;
}
# url, preload, add
$merged_css_url = fvm_generate_min_url('combined', $tkey, 'css', $merged_css);
# cdn
if(isset($fvm_settings['cdn']['cssok']) && $fvm_settings['cdn']['cssok'] == true) {
$merged_css_url = fvm_rewrite_cdn_url($merged_css_url);
}
# http, html preload + header
if($css_method == 'block') {
# add to header
$htmlcssheader[] = '<link rel="stylesheet" href="'.$merged_css_url.'" media="'.$mediatype.'" />';
# http and html preload for render blocking css
if(!isset($fvm_settings['css']['nopreload']) || (isset($fvm_settings['css']['nopreload']) && $fvm_settings['css']['nopreload'] != true)) {
$htmlpreloads[] = '<link rel="preload" href="'.$merged_css_url.'" as="style" media="'.$mediatype.'" />';
}
} else {
# async
$htmlcssheader[] = '<link rel="preload" as="style" href="'.$merged_css_url.'" media="'.$mediatype.'" onload="this.rel=\'stylesheet\'" />';
}
}
}
}
# END COMBINING CSS
}
# END CSS PROCESSING
# START JS PROCESSING
if(fvm_can_minify_js()) {
# defaults
$scripts_duplicate_check = array();
$fvm_scripts_header = array();
$fvm_scripts_defer = array();
# start log
$log = array();
$js_total = 0;
# start log
$log[]= 'PAGE - '. fvm_get_uripath(true) . PHP_EOL . '---' . PHP_EOL;
# get all scripts
$allscripts = array();
foreach($html->find('script') as $element) {
$allscripts[] = $element;
}
# START JS LOOP
if (is_array($allscripts) && count($allscripts) > 0) {
foreach($allscripts as $k=>$tag) {
# handle application/ld+json or application/json before anything else
if(isset($tag->type) && ($tag->type == 'application/ld+json' || $tag->type == 'application/json')) {
# minify
if(isset($fvm_settings['js']['js_enable_min_inline']) && $fvm_settings['js']['js_enable_min_inline'] == true) { $tag->innertext = fvm_minify_microdata($tag->innertext); }
# remove
unset($allscripts[$k]);
continue;
}
# skip unknown script types
if(isset($tag->type) && $tag->type != 'text/javascript') {
unset($allscripts[$k]);
continue;
}
# remove default script type
if(isset($tag->type) && $tag->type == 'text/javascript') { unset($tag->type); }
# START JS FILES
if(isset($tag->src)) {
# filter url
$href = fvm_normalize_url($tag->src);
# ignore js files
if(isset($fvm_settings['js']['ignore']) && !empty($fvm_settings['js']['ignore'])) {
$arr = fvm_string_toarray($fvm_settings['js']['ignore']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $a) {
if(stripos($tag->src, $a) !== false) {
unset($allscripts[$k]);
continue 2;
}
}
}
}
# remove js files
if(isset($fvm_settings['js']['remove']) && !empty($fvm_settings['js']['remove'])) {
$arr = fvm_string_toarray($fvm_settings['js']['remove']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $a) {
if(stripos($tag->src, $a) !== false) {
$tag->outertext = '';
unset($allscripts[$k]);
continue 2;
}
}
}
}
# JS files to delay until user interaction (unmergeable)
if(isset($fvm_settings['js']['thirdparty']) && !empty($fvm_settings['js']['thirdparty'])) {
$arr = fvm_string_toarray($fvm_settings['js']['thirdparty']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $ac) {
if(stripos($tag->src, $ac) !== false) {
# unique identifier
$uid = fvm_generate_hash_with_prefix(hash('sha256', $tag->outertext), 'js');
# remove exact duplicates, or replace transformed tag
if(isset($scripts_duplicate_check[$uid])) {
$tag->outertext = '';
} else {
$tag->type = 'fvm-script-delay';
$scripts_duplicate_check[$uid] = $uid;
}
# mark as processed, unset and break inner loop
unset($allscripts[$k]);
continue 2;
}
}
}
}
# START MERGING JS
if(isset($fvm_settings['js']['combine']) && $fvm_settings['js']['combine'] == true) {
# force render blocking
if(isset($fvm_settings['js']['merge_header']) && !empty($fvm_settings['js']['merge_header'])) {
$arr = fvm_string_toarray($fvm_settings['js']['merge_header']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($tag->src, $aa) !== false) {
# download or fetch from transient, minified
$js = fvm_get_js_from_file($tag);
if($js !== false && is_array($js)) {
# error
if(isset($js['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$js['error'].' */'. PHP_EOL . $tag->outertext;
unset($allscripts[$k]);
continue 2;
}
# save js for merging
$fvm_scripts_header[] = $js['code'];
# log
$size = strlen($js['code']);
$js_total = $js_total + $size;
$log[] = '[JS Block: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $js['url']). PHP_EOL;
# remove from html
$tag->outertext = '';
unset($allscripts[$k]);
continue 2;
}
}
}
}
}
# force defer
if(isset($fvm_settings['js']['merge_defer']) && !empty($fvm_settings['js']['merge_defer'])) {
$arr = fvm_string_toarray($fvm_settings['js']['merge_defer']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($tag->src, $aa) !== false) {
# download or fetch from transient, minified
$js = fvm_get_js_from_file($tag);
if($js !== false && is_array($js)) {
# error
if(isset($js['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$js['error'].' */'. PHP_EOL . $tag->outertext;
unset($allscripts[$k]);
continue 2;
}
# save js for merging
$fvm_scripts_defer[] = $js['code'];
# log
$size = strlen($js['code']);
$js_total = $js_total + $size;
$log[] = '[JS Defer: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $js['url']). PHP_EOL;
# remove from html
$tag->outertext = '';
unset($allscripts[$k]);
continue 2;
}
}
}
}
}
# jquery needs to load earlier, if not being merged (while merging is active)
if(stripos($tag->src, '/jquery.js') !== false || stripos($tag->src, '/jquery.min.js') !== false || stripos($tag->src, '/jquery-migrate') !== false) {
# http and html preload for render blocking js
if(!isset($fvm_settings['js']['nopreload']) || (isset($fvm_settings['js']['nopreload']) && $fvm_settings['js']['nopreload'] != true)) {
$htmlpreloads[] = '<link rel="preload" href="'.$href.'" as="script" />';
}
# header
if(stripos($tag->src, '/jquery-migrate') !== false) {
$htmljsheader[1] = "<script data-cfasync='false' src='".$href."'></script>"; # jquery migrate
} else {
$htmljsheader[0] = "<script data-cfasync='false' src='".$href."'></script>"; # jquery
}
# content
$tag->outertext = '';
unset($allscripts[$k]);
continue;
}
}
# END MERGING JS
# START INDIVIDUAL JS MINIFICATION
# minify individually, if enabled
if(!isset($fvm_settings['js']['min_disable']) || (isset($fvm_settings['js']['min_disable'])&& $fvm_settings['js']['min_disable'] != true)) {
# skip third party scripts, unless allowed
$allowed = array($fvm_urls['wp_domain'], '/ajax.aspnetcdn.com/ajax/', '/ajax.googleapis.com/ajax/libs/', '/cdnjs.cloudflare.com/ajax/libs/');
if(str_replace($allowed, '', $href) == $href) {
unset($allscripts[$k]);
continue;
}
# force render blocking
if(isset($fvm_settings['js']['merge_header']) && !empty($fvm_settings['js']['merge_header'])) {
$arr = fvm_string_toarray($fvm_settings['js']['merge_header']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($tag->src, $aa) !== false) {
# download or fetch from transient, minified
$js = fvm_get_js_from_file($tag);
if($js !== false && is_array($js)) {
# error
if(isset($js['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$js['error'].' */'. PHP_EOL . $tag->outertext;
unset($allscripts[$k]);
continue 2;
}
# generate url
$ind_js_url = fvm_generate_min_url($tag->src, $js['tkey'], 'js', $js['code']);
# cdn
if(isset($fvm_settings['cdn']['jsok']) && $fvm_settings['cdn']['jsok'] == true) {
$ind_js_url = fvm_rewrite_cdn_url($ind_js_url);
}
# render block
if(isset($tag->async)) { unset($tag->async); }
if(isset($tag->defer)) { unset($tag->defer); }
# http and html preload for render blocking scripts
if(!isset($fvm_settings['js']['nopreload']) || (isset($fvm_settings['js']['nopreload']) && $fvm_settings['js']['nopreload'] != true)) {
$htmlpreloads[] = '<link rel="preload" href="'.$ind_js_url.'" as="script" />';
}
# log
$size = strlen($js['code']);
$js_total = $js_total + $size;
$log[] = '[JS Block: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $js['url']). PHP_EOL;
# finish early
$tag->src = $ind_js_url;
unset($allscripts[$k]);
continue 2;
}
}
}
}
}
# force defer
if(isset($fvm_settings['js']['merge_defer']) && !empty($fvm_settings['js']['merge_defer'])) {
$arr = fvm_string_toarray($fvm_settings['js']['merge_defer']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $aa) {
if(stripos($tag->src, $aa) !== false) {
# download or fetch from transient, minified
$js = fvm_get_js_from_file($tag);
if($js !== false && is_array($js)) {
# error
if(isset($js['error'])) {
$tag->outertext = '/* Error on '.$href.' : '.$js['error'].' */'. PHP_EOL . $tag->outertext;
unset($allscripts[$k]);
continue 2;
}
# generate url
$ind_js_url = fvm_generate_min_url($tag->src, $js['tkey'], 'js', $js['code']);
# cdn
if(isset($fvm_settings['cdn']['jsok']) && $fvm_settings['cdn']['jsok'] == true) {
$ind_js_url = fvm_rewrite_cdn_url($ind_js_url);
}
# add defer
if(!isset($tag->defer)) { $tag->defer = 'defer'; }
# log
$size = strlen($js['code']);
$js_total = $js_total + $size;
$log[] = '[JS Defer: '.str_pad(fvm_format_filesize($size), 9,' ',STR_PAD_LEFT).']'."\t".str_replace($fvm_urls['wp_site_url'], '', $js['url']). PHP_EOL;
# finish early
$tag->src = $ind_js_url;
unset($allscripts[$k]);
continue 2;
}
}
}
}
}
# remove unprocessed scripts from loop
unset($allscripts[$k]);
continue;
}
# END INDIVIDUAL JS MINIFICATION
}
# END JS FILES
# START INLINED SCRIPTS
if(!isset($tag->src)) {
# remove if empty
if(strlen(trim($tag->innertext)) == 0) {
$tag->outertext = '';
unset($allcss[$k]);
continue;
}
# default
$js = ''; $js = $tag->innertext;
# minify?
if(!isset($fvm_settings['js']['min_disable_inline']) || (isset($fvm_settings['js']['min_disable_inline'])&& $fvm_settings['js']['min_disable_inline'] != true)) {
$js = PHP_EOL . fvm_maybe_minify_js($js, null, true) . PHP_EOL;
}
# delay inline scripts until user interaction (unmergeable)
if(isset($fvm_settings['js']['thirdparty']) && !empty($fvm_settings['js']['thirdparty'])) {
$arr = fvm_string_toarray($fvm_settings['js']['thirdparty']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $b) {
if(stripos($js, $b) !== false || stripos($js, $b) !== false) {
# delay
$tag->type = 'fvm-script-delay';
# minified
if(!empty($js)) {
$tag->innertext = $js;
}
# unset
unset($allscripts[$k]);
continue 2;
}
}
}
}
# defer inline scripts
if(isset($fvm_settings['js']['defer_dependencies']) && !empty($fvm_settings['js']['defer_dependencies'])) {
$arr = fvm_string_toarray($fvm_settings['js']['defer_dependencies']);
if(is_array($arr) && count($arr) > 0) {
foreach ($arr as $b) {
if((stripos($js, $b) !== false || stripos($js, $b) !== false) && !isset($tag->src)) {
# defer
$tag->type = 'module';
# html comments are not supported inside module scripts
if(!empty($js)) {
$tag->innertext = preg_replace('/<!--(.|\s)*?-->/ui', '', $js);
}
# unset
unset($allscripts[$k]);
continue 2;
}
}
}
}
}
# END INLINED SCRIPTS
}
}
# END JS LOOP
# START JS LOG
if(count($log) > 1) {
$log[] = str_pad('-', 21, '-',STR_PAD_LEFT) . PHP_EOL;
$log[] = '[JS Total: '.str_pad(fvm_format_filesize($js_total), 9,' ',STR_PAD_LEFT).']' . PHP_EOL;
$log[] = str_pad('-', 21, '-',STR_PAD_LEFT);
fvm_save_log(array('type'=>'min','msg'=>implode('', $log)));
}
# END JS LOG
# START COMBINING JS
# header scripts
if(is_array($fvm_scripts_header) && count($fvm_scripts_header) > 0) {
# merge code, hash
$merged_js = implode(PHP_EOL, $fvm_scripts_header);
$tkey = fvm_generate_hash_with_prefix(hash('sha256', $merged_js), 'js');
# generate url
$merged_js_url = fvm_generate_min_url('combined', $tkey, 'js', $merged_js);
# cdn
if(isset($fvm_settings['cdn']['jsok']) && $fvm_settings['cdn']['jsok'] == true) {
$merged_js_url = fvm_rewrite_cdn_url($merged_js_url);
}
# http and html preload for render blocking scripts
if(!isset($fvm_settings['js']['nopreload']) || (isset($fvm_settings['js']['nopreload']) && $fvm_settings['js']['nopreload'] != true)) {
$htmlpreloads[] = '<link rel="preload" href="'.$merged_js_url.'" as="script" />';
}
# add to header
$htmljsheader[] = "<script data-cfasync='false' src='".$merged_js_url."'></script>";
}
# deferred scripts
if(is_array($fvm_scripts_defer) && count($fvm_scripts_defer) > 0) {
# merge code, hash
$merged_js = implode(PHP_EOL, $fvm_scripts_defer);
$tkey = fvm_generate_hash_with_prefix(hash('sha256', $merged_js), 'js');
# generate url
$merged_js_url = fvm_generate_min_url('combined', $tkey, 'js', $merged_js);
# cdn
if(isset($fvm_settings['cdn']['jsok']) && $fvm_settings['cdn']['jsok'] == true) {
$merged_js_url = fvm_rewrite_cdn_url($merged_js_url);
}
# header, no preload for deferred files
$htmljsheader[] = "<script defer='defer' src='".$merged_js_url."'></script>";
}
}
# END JS PROCESSING
# process HTML minification, if not disabled ###############################
if(fvm_can_process_html()) {
# Remove HTML comments and IE conditionals
if(isset($fvm_settings['html']['nocomments']) && $fvm_settings['html']['nocomments'] == true) {
foreach($html->find('comment') as $element) {
$element->outertext = '';
}
}
# Remove generator tags
if(isset($fvm_settings['html']['cleanup_header']) && $fvm_settings['html']['cleanup_header'] == true) {
# remove
foreach($html->find('head meta[name=generator], head link[rel=shortlink], head link[rel=dns-prefetch], head link[rel=preconnect], head link[rel=prefetch], head link[rel=prerender], head meta[name*=msapplication], head link[rel=apple-touch-icon], head link[rel=EditURI], head link[rel=preconnect], head link[rel=wlwmanifest], head link[rel=https://api.w.org/], head link[href*=/wp-json/], head link[rel=pingback], head link[type=application/json+oembed], head link[type=text/xml+oembed]') as $element) {
$element->outertext = '';
}
# allow only the last link[rel=icon]
$ic = array(); $ic = $html->find('head link[rel=icon]');
$i = 1; $len = count($ic);
if($len > 1) {
foreach($ic as $element) {
if ($i != $len) { $element->outertext = ''; } $i++; # delete except if last
}
}
}
}
# build extra head and footer ###############################
# header and footer markers
$hm = '<!-- h_preheader --><!-- h_header_function -->';
$hm_late = '<!-- h_cssheader --><!-- h_jsheader -->';
$fm = '<!-- h_footer_fvm_scripts -->';
# add our function to head
if(fvm_can_minify_css() || fvm_can_minify_js()) {
$hm = fvm_add_header_function($hm);
}
# remove charset meta tag and collect it to first position
if(!is_null($html->find('meta[charset]', 0))) {
$hm = str_replace('<!-- h_preheader -->', $html->find('meta[charset]', 0)->outertext.'<!-- h_preheader -->', $hm);
foreach($html->find('meta[charset]') as $element) { $element->outertext = ''; }
}
# remove other meta tag and collect them between preload and css/js files
foreach($html->find('head meta, head title, head link[rel=canonical], head link[rel=alternate], head link[rel=pingback], head script[type=application/ld+json]') as $element) {
$hm_late = str_replace('<!-- h_cssheader -->', $element->outertext.'<!-- h_cssheader -->', $hm_late);
$element->outertext = '';
}
# preload headers, by importance
if(is_array($htmlpreloads)) {
# deduplicate
$htmlpreloads = array_unique($htmlpreloads);
# get values
$pre_html = array_values($htmlpreloads);
# add preload html header
if(count($pre_html) > 0) {
$hm = str_replace('<!-- h_preheader -->', implode(PHP_EOL, $pre_html).'<!-- h_preheader -->', $hm);
}
}
# add stylesheets
if(isset($htmlcssheader)) {
if(is_array($htmlcssheader) && count($htmlcssheader) > 0) {
ksort($htmlcssheader); # priority
$hm_late = str_replace('<!-- h_cssheader -->', implode(PHP_EOL, $htmlcssheader).'<!-- h_cssheader -->', $hm_late);
}
}
# add header scripts
if(isset($htmljsheader)) {
if(is_array($htmljsheader) && count($htmljsheader) > 0) {
ksort($htmljsheader); # priority
$hm_late = str_replace('<!-- h_jsheader -->', implode(PHP_EOL, $htmljsheader).'<!-- h_jsheader -->', $hm_late);
}
}
# add defer scripts
if(isset($htmljscodedefer)) {
if(is_array($htmljscodedefer) && count($htmljscodedefer) > 0) {
ksort($htmljscodedefer); # priority
$hm_late = str_replace('<!-- h_jsheader -->', implode(PHP_EOL, $htmljscodedefer), $hm_late);
}
}
# add fvm_footer scripts, if enabled
if(fvm_can_minify_js()) {
$fm = fvm_add_delay_scripts_logic($fm);
}
# cleanup leftover markers
$hm = str_replace(array('<!-- h_preheader -->', '<!-- h_header_function -->'), '', $hm);
$hm_late = str_replace(array('<!-- h_cssheader -->', '<!-- h_jsheader -->'), '', $hm_late);
$fm = str_replace('<!-- h_footer_fvm_scripts -->', '', $fm);
# append header and footer
if(!is_null($html->find('head', 0)) && !is_null($html->find('body', -1))) {
if(!is_null($html->find('head', 0)->first_child()) && !is_null($html->find('body', -1)->last_child())) {
$html->find('head', 0)->first_child()->outertext = $hm . $html->find('head', 0)->first_child()->outertext . $hm_late;
$html->find('body', -1)->last_child()->outertext = $html->find('body', -1)->last_child ()->outertext . $fm;
}
}
# convert html object to string, save all objects to string
$html = trim($html->save());
# process cdn optimization
if(fvm_can_process_cdn()) {
$html = fvm_process_cdn($html);
}
# minify remaining HTML at the end, if enabled
if(fvm_can_process_html()) {
if(!isset($fvm_settings['html']['min_disable']) || (isset($fvm_settings['html']['min_disable']) && $fvm_settings['html']['min_disable'] != true)) {
$html = fvm_raisermin_html($html);
}
}
# filter final html if needed
if(function_exists('fvm_filter_final_html')) {
$html = fvm_filter_final_html($html);
}
# return html
return $html;
}
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
### Get General Information
function fvm_get_generalinfo() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
echo __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
echo'+++'. PHP_EOL;
echo'SERVER INFO:'. PHP_EOL;
echo'OS: '. PHP_OS . PHP_EOL;
echo'Server: '. $_SERVER["SERVER_SOFTWARE"] . PHP_EOL;
echo'PHP: '. PHP_VERSION . PHP_EOL;
echo'MySQL: '. fvm_get_mysql_version() . PHP_EOL;
echo'CPU Cores: '. fvm_get_servercpu() . PHP_EOL;
echo'Server Load: '. fvm_get_serverload() . PHP_EOL;
echo'---'. PHP_EOL;
echo'SITE INFO:'. PHP_EOL;
echo'Site Path: '. ABSPATH . PHP_EOL;
echo'Hostname: '. $_SERVER['SERVER_NAME'] . PHP_EOL;
echo'DB Data Size: '. fvm_format_php_size(fvm_get_mysql_data_usage()) . PHP_EOL;
echo'DB Index Size: '. fvm_format_php_size(fvm_get_mysql_index_usage()) . PHP_EOL;
echo'---'. PHP_EOL;
echo'LIMITS:'. PHP_EOL;
echo'PHP Max Exec Time: '. fvm_get_php_max_execution(). PHP_EOL;
echo'PHP Memory Limit: '. fvm_format_php_size(fvm_get_php_memory_limit()) . PHP_EOL;
echo'PHP Max Upload Size: '. fvm_format_php_size(fvm_get_php_upload_max()) . PHP_EOL;
echo'PHP Max Post Size: '. fvm_format_php_size(fvm_get_php_post_max()) . PHP_EOL;
echo'MySQL Max Packet Size: '. fvm_format_php_size(fvm_get_mysql_max_allowed_packet()) . PHP_EOL;
echo'MySQL Max Connections: '. fvm_get_mysql_max_allowed_connections() . PHP_EOL;
echo'+++';
}
### Convert PHP Size Format to an int, then readable format
function fvm_format_php_size($size) {
if (!is_numeric($size)) {
if (strpos($size, 'M') !== false) {
$size = intval($size)*1024*1024;
} elseif (strpos($size, 'K') !== false) {
$size = intval($size)*1024;
} elseif (strpos($size, 'G') !== false) {
$size = intval($size)*1024*1024*1024;
}
}
$size = is_numeric($size) ? fvm_format_filesize($size, 0) : $size;
return str_pad($size, 8, " ", STR_PAD_LEFT);
}
### Function: Get PHP Max Upload Size
if(!function_exists('fvm_get_php_upload_max')) {
function fvm_get_php_upload_max() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
if(ini_get('upload_max_filesize')) {
$upload_max = ini_get('upload_max_filesize');
} else {
$upload_max = strval('N/A');
}
return $upload_max;
}
}
### Function: Get PHP Max Post Size
if(!function_exists('fvm_get_php_post_max')) {
function fvm_get_php_post_max() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
if(ini_get('post_max_size')) {
$post_max = ini_get('post_max_size');
} else {
$post_max = strval('N/A');
}
return $post_max;
}
}
### Function: PHP Maximum Execution Time
if(!function_exists('fvm_get_php_max_execution')) {
function fvm_get_php_max_execution() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
if(ini_get('max_execution_time')) {
$max_execute = intval(ini_get('max_execution_time'));
} else {
$max_execute = strval('N/A');
}
return str_pad($max_execute, 5, " ", STR_PAD_LEFT);
}
}
### Function: PHP Memory Limit
if(!function_exists('fvm_get_php_memory_limit')) {
function fvm_get_php_memory_limit() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
if(ini_get('memory_limit')) {
$memory_limit = ini_get('memory_limit');
} else {
$memory_limit = strval('N/A');
}
return $memory_limit;
}
}
### Function: Get MYSQL Version
if(!function_exists('fvm_get_mysql_version')) {
function fvm_get_mysql_version() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
global $wpdb;
return $wpdb->get_var("SELECT VERSION() AS version");
}
}
### Function: Get MYSQL Data Usage
if(!function_exists('fvm_get_mysql_data_usage')) {
function fvm_get_mysql_data_usage() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
global $wpdb;
$data_usage = 0;
$tablesstatus = $wpdb->get_results("SHOW TABLE STATUS");
foreach($tablesstatus as $tablestatus) {
if(is_numeric($tablestatus->Data_length)) { $data_usage += $tablestatus->Data_length; } else { $data_usage += 0; }
}
if (!$data_usage) {
$data_usage = strval('N/A');
}
return $data_usage;
}
}
### Function: Get MYSQL Index Usage
if(!function_exists('fvm_get_mysql_index_usage')) {
function fvm_get_mysql_index_usage() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
global $wpdb;
$index_usage = 0;
$tablesstatus = $wpdb->get_results("SHOW TABLE STATUS");
foreach($tablesstatus as $tablestatus) {
if(is_numeric($tablestatus->Index_length)) { $index_usage += $tablestatus->Index_length; } else { $index_usage += 0; }
}
if (!$index_usage){
$index_usage = strval('N/A');
}
return $index_usage;
}
}
### Function: Get MYSQL Max Allowed Packet
if(!function_exists('fvm_get_mysql_max_allowed_packet')) {
function fvm_get_mysql_max_allowed_packet() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
global $wpdb;
$packet_max_query = $wpdb->get_row("SHOW VARIABLES LIKE 'max_allowed_packet'");
$packet_max = $packet_max_query->Value;
if(!$packet_max) {
$packet_max = strval('N/A');
}
return $packet_max;
}
}
### Function:Get MYSQL Max Allowed Connections
if(!function_exists('fvm_get_mysql_max_allowed_connections')) {
function fvm_get_mysql_max_allowed_connections() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
global $wpdb;
$connection_max_query = $wpdb->get_row("SHOW VARIABLES LIKE 'max_connections'");
$connection_max = $connection_max_query->Value;
if(!$connection_max) {
$connection_max = strval('N/A');
}
return str_pad($connection_max, 5, " ", STR_PAD_LEFT);
}
}
### Function: Get The Server Load
if(!function_exists('fvm_get_serverload')) {
function fvm_get_serverload() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
$server_load = 0;
$numCpus = 'N/A';
if(PHP_OS != 'WINNT' && PHP_OS != 'WIN32') {
clearstatcache();
if(@file_exists('/proc/loadavg') ) {
if ($fh = @fopen( '/proc/loadavg', 'r' )) {
$data = @fread( $fh, 6 );
@fclose( $fh );
$load_avg = explode( " ", $data );
$server_load = trim($load_avg[0]);
}
} else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)) && function_exists('popen') && fvm_function_available('popen')) {
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process && null !== $process) {
fgets($process);
$numCpus = intval(fgets($process));
pclose($process);
}
} else if (function_exists('system') && fvm_function_available('system')){
$data = @system('uptime');
preg_match('/(.*):{1}(.*)/', $data, $matches);
if(isset($matches[2])) {
$load_arr = explode(',', $matches[2]);
$server_load = trim($load_arr[0]);
} else {
$server_load = strval('N/A');
}
} else {
$server_load = strval('N/A');
}
}
if(empty($server_load)) {
$server_load = strval('N/A');
}
return $server_load;
}
}
### Function: Get The Server CPU's
if(!function_exists('fvm_get_servercpu')) {
function fvm_get_servercpu() {
# check if user has admin rights
if(!current_user_can('manage_options')) {
return __( 'You are not allowed to execute this function!', 'fast-velocity-minify' );
}
$numCpus = 0;
if(PHP_OS != 'WINNT' && PHP_OS != 'WIN32') {
clearstatcache();
if (@is_file('/proc/cpuinfo')) {
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$numCpus = count($matches[0]);
} else if (function_exists('popen') && fvm_function_available('popen')) {
$process = @popen('sysctl -a', 'rb');
if (false !== $process && null !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) { $numCpus = intval($matches[1][0]); }
pclose($process);
}
} else {
$numCpus = strval('N/A');
}
}
if(empty($numCpus)) {
$numCpus = strval('N/A');
}
return $numCpus;
}
}
\ No newline at end of file
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# update routines for new fields and replacements
function fvm_update_changes() {
# current version
global $fvm_var_plugin_version;
# Version 3.0 routines start
# delete old FVM files
global $fvm_var_dir_path, $fvm_var_inc_lib, $fvm_var_inc_dir;
# prevent deleting if the paths are empty
# can happen when a user runs wp-cli on a child directory
if(isset($fvm_var_dir_path) && isset($fvm_var_inc_lib) && isset($fvm_var_inc_dir) && !empty($fvm_var_dir_path) && !empty($fvm_var_inc_lib) && !empty($fvm_var_inc_dir)) {
# must be inside a fast-velocity-minify directory
if (stripos($fvm_var_dir_path, 'fast-velocity-minify') !== false) {
# delete
if(file_exists($fvm_var_inc_dir.'functions-cache.php')) { @unlink($fvm_var_inc_dir.'functions-cache.php'); }
if(file_exists($fvm_var_inc_dir.'functions-cli.php')) { @unlink($fvm_var_inc_dir.'functions-cli.php'); }
if(file_exists($fvm_var_inc_dir.'functions-serverinfo.php')) { @unlink($fvm_var_inc_dir.'functions-serverinfo.php'); }
if(file_exists($fvm_var_inc_dir.'functions-upgrade.php')) { @unlink($fvm_var_inc_dir.'functions-upgrade.php'); }
if(file_exists($fvm_var_inc_dir.'functions.php')) { @unlink($fvm_var_inc_dir.'functions.php'); }
if(file_exists($fvm_var_dir_path.'fvm.css')) { @unlink($fvm_var_dir_path.'fvm.css'); }
if(file_exists($fvm_var_dir_path.'fvm.js')) { @unlink($fvm_var_dir_path.'fvm.js'); }
if(file_exists($fvm_var_inc_lib.'mrclay' . DIRECTORY_SEPARATOR . 'HTML.php')) {
@unlink($fvm_var_inc_lib.'mrclay' . DIRECTORY_SEPARATOR . 'HTML.php');
@unlink($fvm_var_inc_lib.'mrclay' . DIRECTORY_SEPARATOR . 'index.html');
@rmdir($fvm_var_inc_lib.'mrclay');
}
}
}
# Version 3.2 routines start
if (get_option("fastvelocity_plugin_version") !== false) {
if (version_compare($fvm_var_plugin_version, '3.2.0', '>=') && get_option("fastvelocity_min_ignore") !== false) {
# cleanup
delete_option('fastvelocity_min_change_cache_path');
delete_option('fastvelocity_min_change_cache_base_url');
delete_option('fastvelocity_min_fvm_cdn_url');
delete_option('fastvelocity_plugin_version');
delete_option('fvm-last-cache-update');
delete_option('fastvelocity_min_ignore');
delete_option('fastvelocity_min_blacklist');
delete_option('fastvelocity_min_ignorelist');
delete_option('fastvelocity_min_excludecsslist');
delete_option('fastvelocity_min_excludejslist');
delete_option('fastvelocity_min_enable_purgemenu');
delete_option('fastvelocity_min_default_protocol');
delete_option('fastvelocity_min_disable_js_merge');
delete_option('fastvelocity_min_disable_css_merge');
delete_option('fastvelocity_min_disable_js_minification');
delete_option('fastvelocity_min_disable_css_minification');
delete_option('fastvelocity_min_remove_print_mediatypes');
delete_option('fastvelocity_min_skip_html_minification');
delete_option('fastvelocity_min_strip_htmlcomments');
delete_option('fastvelocity_min_skip_cssorder');
delete_option('fastvelocity_min_skip_google_fonts');
delete_option('fastvelocity_min_skip_emoji_removal');
delete_option('fastvelocity_fvm_clean_header_one');
delete_option('fastvelocity_min_enable_defer_js');
delete_option('fastvelocity_min_exclude_defer_jquery');
delete_option('fastvelocity_min_force_inline_css');
delete_option('fastvelocity_min_force_inline_css_footer');
delete_option('fastvelocity_min_remove_googlefonts');
delete_option('fastvelocity_min_defer_for_pagespeed');
delete_option('fastvelocity_min_defer_for_pagespeed_optimize');
delete_option('fastvelocity_min_exclude_defer_login');
delete_option('fastvelocity_min_skip_defer_lists');
delete_option('fastvelocity_min_fvm_fix_editor');
delete_option('fastvelocity_min_loadcss');
delete_option('fastvelocity_min_fvm_removecss');
delete_option('fastvelocity_enabled_css_preload');
delete_option('fastvelocity_enabled_js_preload');
delete_option('fastvelocity_fontawesome_method');
delete_option('fastvelocity_gfonts_method');
}
}
# Version 3.2 routines end
}
<?php
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
###################################################
# extend wp-cli to purge cache, usage: wp fvm purge
###################################################
# only for wp-cli
if ( defined( 'WP_CLI' ) && WP_CLI ) {
class fastvelocity_WPCLI {
# purge files + cache
public function purge() {
WP_CLI::success( __( 'FVM and other caches were purged.', 'fast-velocity-minify' ) );
fvm_purge_static_files();
fvm_purge_others();
# purge everything
$cache = fvm_purge_static_files();
$others = fvm_purge_others();
# notices
WP_CLI::success( __( 'FVM: All Caches are now cleared.', 'fast-velocity-minify' ) .' ('.date("D, d M Y @ H:i:s e").')');
if(is_string($cache)) { WP_CLI::warning($cache); }
if(is_string($others)) { WP_CLI::success($others); }
}
# get cache size
public function stats() {
WP_CLI::error( __( 'This feature is currently under development.', 'fast-velocity-minify' ) );
}
}
# add commands
WP_CLI::add_command( 'fvm', 'fastvelocity_WPCLI' );
}
<?php if( $active_tab == 'help' ) { ?>
<div class="fvm-wrapper">
<h2 class="title">FVM 3 Release Notes</h2>
<div class="accordion">
<h3>Important JS and JavaScript changes</h3>
<div>
<p><strong>Notes:</strong></p>
<p>JavaScript merging functionality went through a significant change on FVM 3 and it now requires manual configuration to work.</p>
<p>If you are upgrading from FVM 2 please refer to the help section below for more information on the settings.</p>
<p>If you just installed the plugin, please note that JS is not being optimized yet. You have to choose which files to be render blocking and which ones to be deferred, plus it's inline script dependencies (if any). </p>
<p>Previously, FVM merged everything and relied on having options to ignore scripts. This option frequently created issues with other plugin updates, when they changed something JavaScript related.</p>
<p>Please understand that this plugin is and it has always been aimed at being a tool for advanced users and developers, so it's not meant just be plug and play, without manual settings in place.</p>
<p>There is a new method to optimize third party scripts and load them on user interaction or automatically, after 5 seconds. This is a more recommended method to optimize scripts, as compared to FVM 2 which used document.write and other deprecated methods.</p>
<p>Please refer to the JavaScript help section further down on this page to understand how you can optimize your scripts.</p>
</div>
<h3>Relevant CSS and Fonts changes</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You can now ignore or completely remove CSS files by URI Path or domain name (such as google fonts or other unwanted CSS files).</p>
<p>Known fonts, icon, animation and some other CSS files now have an option to be merged separately and loaded Async.</p>
<p>FVM now preloads the external CSS files on the header, before render blocking them later on the page.</p>
</div>
<h3>Relevant Cache changes</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Purging cache on FVM, renames the file name in order to bypass CDN and browser cache, however, expired CSS and JS cache files are only deleted 24 hours (by default) after your last cache purge request.</p>
<p>This is needed because some hosting services can cache your HTML regardless of your cache purge request. If we were to delete the FVM cached files right away, it would break your layout for anonymous users, as the files would no longer exist but your page would still be referencing them.</p>
</div>
<h3>Other changes</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Preconnect and Preload Headers have been removed (please use your own PHP code and conditional tags for that).</p>
<p>Critical Path CSS option has been removed (add your own code with code and <code>&lt;style id=&quot;critical-path&quot;&gt;</code> your code &lt;/style&gt; ).</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">Global Settings</h2>
<div class="accordion">
<h3>Purge Minified CSS/JS files instantly</h3>
<div>
<p><strong>Notes:</strong></p>
<p>When you purge CSS/JS files instantly, all CSS and JS cache files are deleted immediately when you clear everything on FVM. While this is great during development, it may cause issues when your hosting is doing page caching that cannot be purged by FVM. For example, if you were to delete the CSS and JS files instantly without purging the full page cache, that page cache would now be pointing to deleted files.</p>
<p>If you deselect this option, whenever you clear everything on FVM, it will only try to delete files that are older than 24h (and hopefully this should be enough for your hosting to expire the page cache automatically). That way, even if your hosting is still showing your page cache to anonymous users, the referred CSS and JS files will still be available.</p>
<p>If you are not sure about page caching on your server or hosting provider, you should keep this option disabled.</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">HTML Settings</h2>
<div class="accordion">
<h3>Enable HTML Processing</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You need to enable this option, for any other options in the HTML section to work.</p>
</div>
<h3>Strip HTML Comments</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Some plugins may need to use comments for certain functionality to work, however this is quite rare. The benefit of removing comments is usually very small, so if needed you can disable this setting.</p>
</div>
<h3>Cleanup Header</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This options removes resource hints, generator tags, shortlinks, manifest link, etc from the header.</p>
<p>The header should be kept as lean as possible for the best TTFB response times and LCP metrics, but if you later find that you need some of the stuff that is removed by this option, you can disable this setting.</p>
</div>
<h3>Remove Emoji</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This will remove the default emoji scripts from wordpress, thus reducing the amount of code during page loading. If you use WordPress emoji when posting content, you should keep this option disabled.</p>
</div>
<h3>Disable HTML Minification</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Although rare, it's possible for the HTML minification to strip too much code thus breaking something. You can use this option to test if that is the case and keep this option disabled if that is the case.</p>
<p>HTML minification is no longer a recommendation by gtmetrix or pagespeed insights, so you can keep this option disabled if there is any incompatibility issue.</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">CSS Settings</h2>
<div class="accordion">
<h3>Enable CSS Processing</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You need to enable this option, for any other options in the CSS section to work.</p>
</div>
<h3>Merge Fonts and Icons Separately</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This will try to collect and simplify all your CSS font face rules into a separate CSS file and load it async. It may be useful for de-duplication of fonts, or to evaluate how many fonts are in use. </p>
</div>
<h3>Remove "Print" stylesheets</h3>
<div>
<p><strong>Notes:</strong></p>
<p>As a generic rule this it's safe to remove it for the vast majority of sites, unless your users often need to print pages from your site and you have customized styles for when they do so.</p>
</div>
<h3>Combine CSS Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Merging CSS is no longer recommended if your server supports HTTP/2. The feature also usually causes conflicts when merging multiple CSS files into one, due to the lack of specificity or other errors in the code. It's still available for legacy support on old installations or outdated servers that do not support HTTP/2 delivery.</p>
</div>
<h3>Disable CSS Files Minification</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Although rare, it's possible that CSS files minification may strip too much code and break some style rules that are not supported by the minification library. You can always try to disable this and check if this fixes anything, then use the ignore list to exclude the file that is causing issues.</p>
</div>
<h3>Disable CSS Styles Minification</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Although rare, it's possible that CSS Styles minification may strip too much code and break some style rules that are not supported by the minification library. You can always try to disable this and check if this fixes anything.</p>
</div>
<h3>Disable CSS Link Preload</h3>
<div>
<p><strong>Notes:</strong></p>
<p>CSS Link Preloading is useful when you are merging CSS files or when you defined certain paths as Async CSS. By default, FVM will send an HTTP preload request as well as adding the html preload tag on the header, which will prioritize downloading the critical styles earlier than the other resources.</p>
<p>If you select this option, these headers will be removed and your default preload resources will load earlier than the CSS files. You need to test and see what works best for you.</p>
</div>
<h3>Ignore CSS files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>If there is a conflict when merging CSS files or during individual minification of a specific CSS file, you can add the path on this section and FVM will ignore the file, thus leaving it alone.</p>
</div>
<h3>Remove CSS Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>If your plugins enqueue multiple duplicate libraries with different url paths, you can add the path on this section and FVM will remove the file from the frontend, thus reducing your total CSS size.</p>
</div>
<h3>Async CSS Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>CSS files from plugins that are not rendered above the fold, should ideally be loaded async. For example, if a plugin has CSS files but you only use the element on the footer, you could add the /plugins/plugin-name/ here to async it. But you should not async CSS files that are needed for content that is visible on the critical path.</p>
<p>Also note that by loading certain CSS files async, you are changing the order of styles. This means, some styles may or may not work as intended, because now they load on a different position.</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">JS Settings</h2>
<div class="accordion">
<h3>Enable JS Processing</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You need to enable this option, for any other options in the JS section to work.</p>
</div>
<h3>Combine JS Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Merging JS is no longer recommended if your server supports HTTP/2. The feature also usually causes conflicts when merging multiple JS files into one, due to a different order of loading or other errors in the code. It's still available for legacy support on old installations or outdated servers that do not support HTTP/2 delivery.</p>
</div>
<h3>Disable JS Files Minification</h3>
<div>
<p><strong>Notes:</strong></p>
<p>JS files minification may strip too much code and break some code that is not supported by the minification library. You can always try to disable this and check if this fixes anything, then use the ignore list to exclude the file that is causing issues.</p>
</div>
<h3>Disable JS Inline Minification</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Inline JS Styles minification may strip too much code and break some code that is not supported by the minification library. You can always try to disable this and check if this fixes anything.</p>
</div>
<h3>Disable JS Link Preload</h3>
<div>
<p><strong>Notes:</strong></p>
<p>JS Link Preloading is useful when you are merging JS files or when you defined certain paths as Defer JS. By default, FVM will send an HTTP preload request as well as adding the html preload tag on the header, which will prioritize downloading the render blocking scripts earlier than the other resources.</p>
<p>If you select this option, these headers will be removed and your default preload resources will load earlier than the JS files. You need to test and see what works best for you.</p>
</div>
<h3>Ignore Script Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>When you are merging JS files, the order of scripts change positions and dependencies may break. Other times, a specific script is not supported by the minification and breaks as well. If you encounter issues while merging or minifying JS files, you can exclude them here and those files will be left alone.</p>
</div>
<h3>Render Blocking JS files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>In most WordPress themes and for a significant amount of plugins, you usually need to render block jQuery and jQuery Migrate for compatibility reasons.</p>
<p>Some plugins may not work at all if they are not render blocking, so you should look out for browser console log errors in incognito mode.</p>
<p><strong>Recommended Default Settings:</strong></p>
<p class="fvm-code-full">
/jquery-migrate<br>
/jquery.js<br>
/jquery.min.js<br>
</p>
</div>
<h3>Defer JS Files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Deferring every single script is not always the best solution, especially if those are needed to generate content above the fold. You must check your browser console log in incognito mode for possible errors after enabling this feature, and either move them to the render blocking section or check if there is any inline script that also needs to be deferred (so the order of loading is preserved).</p>
<p>Note that this is an advanced feature, hence it requires manual configuration for it to work.</p>
<p><strong>Recommended Default Settings:</strong></p>
<p class="fvm-code-full">
/ajax.aspnetcdn.com/ajax/<br>
/ajax.googleapis.com/ajax/libs/<br>
/cdnjs.cloudflare.com/ajax/libs/<br>
/stackpath.bootstrapcdn.com/bootstrap/<br>
/wp-admin/<br>
/wp-content/<br>
/wp-includes/
</p>
</div>
<h3>Defer Inline JavaScript</h3>
<div>
<p><strong>Notes:</strong></p>
<p>When you merge JS files and defer them, you are effectively changing the order in which they load, however for certain scripts, the order of loading matters. If you are deferring a certain JS file and you see an "undefined" error triggered on some inline code, you can try this option to also defer the inline code and preserve the order of execution.</p>
<p>Note however, not all scripts can work with defer so you need to test if everything is working without errors.</p>
<p>This is empty by default, unless you determine that it's needed.</p>
<p><strong>Recommended Default Settings:</strong></p>
<p class="fvm-code-full">
wp.i18n<br>
wp.apiFetch.use<br>
window.lodash<br>
wp.hooks<br>
wp.url
</p>
</div>
<h3>Delay third party scripts until user interaction</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Scripts like analytics, ads, tracking codes, etc, consume important CPU and network resources needed for the initial page view. You can force certain plugins to wait for user interaction (mouseover, keydown, touchstart, touchmove and wheel) and the scripts will only run on these events.</p>
<p>Delaying these scripts will improve your speed because most third party scripts are not needed for showing any content (if they are, then they are on the critical path and you should not delay them). In addition, note that some codes make use of document.write and other methods, which do not support delaying (delaying will work as usual, but the script will not do anything or stop working).</p>
<p>If you have render blocking third party scripts, ask your provider if they can provide you with an async or defer implementation (else remove them, because render blocking scripts are not recommended for speed).</p>
<p><strong>Example Settings:</strong></p>
<p class="fvm-code-full">
function(w,d,s,l,i)<br>
function(f,b,e,v,n,t,s)<br>
function(h,o,t,j,a,r)<br>
www.googletagmanager.com/gtm.js<br>
gtag(<br>
fbq(<br>
</p>
</div>
<h3>Remove JavaScript Scripts</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This can be used when you want to remove a duplicate JS file from the frontend source. However, if this is for a third party script you added to the header or footer (either code or via some plugin), it's better if you delete it at the source.</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">CDN Settings</h2>
<div class="accordion">
<h3>Enable CDN Processing</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You need to enable this option, for any other options in the CDN section to work.</p>
</div>
<h3>Enable CDN for merged CSS files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>When selecting this option, FVM will replace your domain name with the CDN domain, for the generated CSS cache file.</p>
<p>Under certain situations, you may not want to serve the CSS file from the CDN, such as when your server compression level is significantly higher than the CDN (smaller file than the one delivered by the CDN).</p>
<p>Also bare in mind, that if the CSS file is served from the CDN, any static assets inside the CSS file that make use of relative paths, will also be cached and served from the CDN, which may also be undesirable in certain situations.</p>
</div>
<h3>Enable CDN for merged JS files</h3>
<div>
<p><strong>Notes:</strong></p>
<p>When selecting this option, FVM will replace your domain name with the CDN domain, for the generated JS cache file.</p>
<p>Under certain situations, you may not want to serve the JS file from the CDN, such as when your server compression level is significantly higher than the CDN (smaller file than the one delivered by the CDN).</p>
<p>Also bare in mind, that if the JS file is served from the CDN, any static assets inside the JS file that make use of relative paths, will also be cached and served from the CDN, which may also be undesirable in certain situations.</p>
</div>
<h3>CDN URL</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This is not required for providers such as Cloudflare.com as well as any reverse proxy CDN service that doesn't change your domain name (the whole site goes through their service).</p>
<p>For other types of CDN, you are usually provided with an alternative domain name from where your static files can be served and in those cases, you would introduce your new domain name here.</p>
</div>
<h3>CDN Integration</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Uses syntax from <a target="_blank" href="https://simplehtmldom.sourceforge.io/manual.htm">https://simplehtmldom.sourceforge.io/manual.htm</a> for modifying the HTML.</p>
<p>The plugin will replace your site domain url with the CDN domain for the matching HTML tags.</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">User Settings</h2>
<div class="accordion">
<h3>User Options</h3>
<div>
<p><strong>Notes:</strong></p>
<p>This will allow you to force CSS, HTML and JS processing for specific user roles.</p>
<p>By default, only anonymous users should be optimized, to ensure that there is nothing broken for logged in users (unless you know what you are doing).</p>
</div>
</div>
<div style="height: 20px;"></div>
<h2 class="title">Other FAQ's</h2>
<div class="accordion">
<h3>Is the plugin GDPR compatible?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>FVM does not collect any information from you, your site or your users. It also doesn't require cookies to work, therefore it's fully GDPR compatible.</p>
</div>
<h3>How do I know if the plugin is working?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>For compatibility reasons, the plugin only optimizes anonymous users by default. That means, you need to open another browser window, or use incognito mode to test and see what it's doing. Logged in users will not see the optimizations, unless you manually enable certain user roles (not recommended for complex websites, unless you know what you are doing).</p>
</div>
<h3>How do I purge the cache?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Please note that FVM is not a page cache plugin and it doesn't cache your content. The only time you should need to purge it's cache, is when you edit a css or js file.</p>
<p>If your HTML page is being cached somewhere else, you must purge your cache either, unless FVM supports it natively.</p>
</div>
<h3>Why am I getting 404 error not found for the generated CSS or JS files?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You deleted the FVM cache but forgot to purge the HTML page cache, or you are lacking writing permissions on the cache directory and files are not being created. </p>
<p>You must purge your page cache either on some other cache plugin or at your server/hosting level for your page to update and find the latest merged file paths.</p>
<p>Note that some hosts rate limit the amount of times you can purge caches to once every few minutes, so you may be purging and it doesn't work, because you are being rate limited by your hosting cache system.</p>
<p>Avoid doing development on live sites and use a staging server without cache for testing. Production servers are for deploying once and leave it until the next deployment cycle.</p>
</div>
<h3>Why is my site layout broke after an update, a configuration change, or some other change?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You must check your browser console log in incognito mode, for possible errors after enabling certain features, deferring scripts or using some other optimization plugins, which may be conflicting with FVM optimization.</p>
<p>If there are no errors, disable each option one by one on FVM (html processing, css processing, js processing, etc) until you find the feature breaking it. After that, adjust and tweak those settings accordingly, or hire a developer to help you.</p>
</div>
<h3>How can I download an older version of FVM for testing purposes?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>It's not recommended you do that, but if you want to test something, you can do so from the <a target="_blank" href="https://plugins.svn.wordpress.org/fast-velocity-minify/tags/">SVN repository</a> on WordPress.</p>
</div>
<h3>How do I undo all optimizations done by FVM?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>Simply disable the plugin, and make sure to purge all page caches (Cache Plugins, Hosting, OPCache, etc).</p>
<p>Note that some hosts rate limit the amount of times you can purge caches to once every few minutes, so you may be purging and it doesn't work, because you are being rate limited by your hosting cache system. If that happens, just wait and try again later or ask your hosting to manually purge all caches on the server.</p>
<p>You can also delete any database entries on the wp_options table starting with fastvelocity to completely purge it.</p>
<p>FVM does not modify your site. It runs after your template loads and filters the final HTML to present it to your users, in a more optimized way.</p>
</div>
<h3>I have disabled FVM but somehow the cache files are still being generated?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>If you already purged all caches available, please ensure you have deleted the plugin and that it's no longer visible via wp-admin. If you still see references to FVM in incognito mode via google chrome, that means your server still has full page cache in memory that needs to be cleared.</p>
<p>A few hosting providers will put your files on a remote storage and cache your disk and files in memory to speed things up, which may cause code to be cached even if you have completely deleted it from the remote storage. This means, it may take a few minutes, or several hours for the actual code to update. In that case, restart the server or ask your hosting to purge all disk and page caching memory.</p>
</div>
<h3>Where can I get support or ask questions about the plugin?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>You can ask for help on <a href="https://wordpress.org/support/plugin/fast-velocity-minify/">https://wordpress.org/support/plugin/fast-velocity-minify/</a> but please note we cannot guide you on which files to merge or how to solve JavaScript conflicts. You need to try different settings (trial and error) and open a separate window in incognito mode, to look for console log errors on your browser, and adjust settings as needed.</p>
</div>
<h3>How is it possible that some scan is showing malware on the plugin?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>I guarantee that the plugin is 100% clean of malware, provided you have downloaded the plugin from the official WordPress source AND that your other plugins, theme or core is not compromised.</p>
<p>Malware can infect any plugin (even security plugins) regardless of the point of entry. Sometimes it propagates from different areas (including other sites you may have on the same server) or through a vulnerability on another theme or plugin (even disabled plugins or themes sometimes). </p>
<p>For that reason, if there is already malware on any JS files or CSS being merged by FVM, they would still be merged as they are, as FVM also reads them as they are. </p>
<p>If you are seeing malware on any cache file related to FVM, simply purge all caches and delete the FVM plugin. Then hire someone to manually audit the site (plugins or automated malware checks are not 100% accurate). You can then reinstall the FVM plugin from the official source on wordpress.org or via wp-admin if you like.</p>
</div>
<h3>How do I report a security issue or file a bug report?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>If you are sure it's a bug and not a misconfiguration specific to your site, thank you for taking the time to report it.</p>
<p>You can contact me on <a href="https://fastvelocity.com/">https://fastvelocity.com/</a> using the contact form.</p>
<p>You are also welcome to submit patches and fixes via <a href="https://github.com/peixotorms/fast-velocity-minify">https://github.com/peixotorms/fast-velocity-minify</a> if you are a developer.</p>
</div>
<h3>I'm not a developer, can I hire you for a more complete speed optimization?</h3>
<div>
<p>You can contact me on <a href="https://fastvelocity.com/">https://fastvelocity.com/</a> using the contact form, providing me your site URL and what issues you are trying to fix, for a more exact quote.</p>
<p>My speed optimization starts from $500 for small sites and from $850 for woocommerce and membership sites.</p>
<p>I do not use the free FVM for my professional work, but I guarantee as best performance as possible for your site content.</p>
</div>
<h3>How can I donate to the plugin author?</h3>
<div>
<p><strong>Notes:</strong></p>
<p>While not required, if you are happy with my work and would like to buy me a <del>beer</del> green tea, you can do it via PayPal at <a target="_blank" href="https://goo.gl/vpLrSV">https://goo.gl/vpLrSV</a> and thank you in advance :)</p>
</div>
</div>
</div>
<?php
}
<?php if( $active_tab == 'settings' ) { ?>
<div class="fvm-wrapper">
<form method="post" id="fvm-save-changes">
<?php
# nounce
wp_nonce_field('fvm_settings_nonce', 'fvm_settings_nonce');
?>
<h2 class="title"><?php _e( 'Global Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'Settings that affect the plugin and are not specific to speed optimization.', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'Global Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Handle with Care', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_cache_min_instant_purge">
<input name="fvm_settings[cache][min_instant_purge]" type="checkbox" id="fvm_settings_cache_min_instant_purge" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'cache', 'min_instant_purge')); ?>>
<?php _e( 'Purge Minified CSS/JS files instantly', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Cache files are only deleted if older than 24h by default, for compatibility with certain hosting providers.', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
</tbody>
</table>
<h2 class="title"><?php _e( 'HTML Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'Optimize your HTML and remove some clutter from the HTML page.', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'HTML Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Recommended Settings', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_html_enable">
<input name="fvm_settings[html][enable]" type="checkbox" id="fvm_settings_html_enable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'html', 'enable')); ?>>
<?php _e( 'Enable HTML Processing', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will enable processing for the settings below', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_html_nocomments">
<input name="fvm_settings[html][nocomments]" type="checkbox" id="fvm_settings_html_nocomments" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'html', 'nocomments')); ?>>
<?php _e( 'Strip HTML Comments', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will strip HTML comments from your HTML page', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_html_cleanup_header">
<input name="fvm_settings[html][cleanup_header]" type="checkbox" id="fvm_settings_html_cleanup_header" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'html', 'cleanup_header')); ?>>
<?php _e( 'Cleanup Header', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Removes resource hints, generator tag, shortlinks, manifest link, etc', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_html_disable_emojis">
<input name="fvm_settings[html][disable_emojis]" type="checkbox" id="fvm_settings_html_disable_emojis" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'html', 'disable_emojis')); ?>>
<?php _e( 'Remove Emoji', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Removes the default emoji scripts and styles that come with WordPress', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Advanced HTML Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Handle with Care', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_html_min_disable">
<input name="fvm_settings[html][min_disable]" type="checkbox" id="fvm_settings_html_min_disable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'html', 'min_disable')); ?>>
<?php _e( 'Disable HTML Minification', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will disable HTML minification for compatibility purposes', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
</tbody>
</table>
<div style="height: 60px;"></div>
<h2 class="title"><?php _e( 'CSS Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'Optimize your CSS and Styles settings.', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'CSS Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Recommended Settings', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_css_enable">
<input name="fvm_settings[css][enable]" type="checkbox" id="fvm_settings_css_enable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'enable')); ?>>
<?php _e( 'Enable CSS Processing', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will enable processing for the settings below', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_css_fonts">
<input name="fvm_settings[css][fonts]" type="checkbox" id="fvm_settings_css_fonts" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'fonts')); ?>>
<?php _e( 'Merge Fonts and Icons separately', 'fast-velocity-minify' ); ?><span class="note-info">[ <?php _e( 'Will merge fonts and icons into a separate CSS file', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_css_noprint">
<input name="fvm_settings[css][noprint]" type="checkbox" id="fvm_settings_css_noprint" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'noprint')); ?>>
<?php _e( 'Remove "Print" CSS files', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will remove CSS files of mediatype "print" from the frontend', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Advanced CSS Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Handle with Care', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_css_combine">
<input name="fvm_settings[css][combine]" type="checkbox" id="fvm_settings_css_combine" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'combine')); ?>>
<?php _e( 'Combine CSS Files', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Deprecated: Will combine all CSS files by mediatype groups in the header (no longer recommended for HTTP/2 servers)', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_css_min_disable">
<input name="fvm_settings[css][min_disable]" type="checkbox" id="fvm_settings_css_min_disable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'min_disable')); ?>>
<?php _e( 'Disable CSS Files Minification', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will disable CSS Files minification for compatibility purposes', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_css_min_disable_styles">
<input name="fvm_settings[css][min_disable_styles]" type="checkbox" id="fvm_settings_css_min_disable_styles" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'min_disable_styles')); ?>>
<?php _e( 'Disable CSS Styles Minification', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will disable CSS Styles minification for compatibility purposes', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_css_nopreload">
<input name="fvm_settings[css][nopreload]" type="checkbox" id="fvm_settings_css_nopreload" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'css', 'nopreload')); ?>>
<?php _e( 'Disable CSS Link Preload', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will remove the Render Blocking CSS files Link Preload from the header', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Ignore CSS files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_css_ignore"><span class="fvm-bold-green fvm-rowintro"><?php _e( "Ignore the following CSS URL's", 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[css][ignore]" rows="7" cols="50" id="fvm_settings_css_ignore" class="large-text code" placeholder="ex: /plugins/something/assets/problem.css"><?php echo fvm_get_settings_value($fvm_settings, 'css', 'ignore'); ?></textarea></p>
<p class="description">[ <?php _e( 'CSS files are merged and grouped automatically by mediatype, hence you have an option to exclude files.', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the <code>href attribute</code> on the <code>link tag</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Remove CSS Files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_css_remove"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Remove the following CSS files', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[css][remove]" rows="7" cols="50" id="fvm_settings_css_remove" class="large-text code" placeholder="ex: fonts.googleapis.com"><?php echo fvm_get_settings_value($fvm_settings, 'css', 'remove'); ?></textarea></p>
<p class="description">[ <?php _e( 'This will allow you to remove unwanted CSS files by URL path from the frontend', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the <code>href attribute</code> on the <code>link tag</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Async CSS Files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_css_async"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Async the following CSS files', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[css][async]" rows="7" cols="50" id="fvm_settings_css_async" class="large-text code" placeholder="ex: /plugins/something/assets/low-priority.css"><?php echo fvm_get_settings_value($fvm_settings, 'css', 'async'); ?></textarea></p>
<p class="description">[ <?php _e( 'This will allow you to remove unwanted CSS files by URL path from the frontend', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the <code>href attribute</code> on the <code>link tag</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
</tbody>
</table>
<div style="height: 60px;"></div>
<h2 class="title"><?php _e( 'JS Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'In this section, you can optimize your JS files and inline scripts manually (by default all scripts are ignored for compatibility reasons).', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'JS Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Recommended Settings', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_js_enable">
<input name="fvm_settings[js][enable]" type="checkbox" id="fvm_settings_js_enable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'js', 'enable')); ?>>
<?php _e( 'Enable JS Processing', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will enable processing for the settings below', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Advanced JS Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Handle with Care', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_js_combine">
<input name="fvm_settings[js][combine]" type="checkbox" id="fvm_settings_js_combine" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'js', 'combine')); ?>>
<?php _e( 'Combine JS Files', 'fast-velocity-minify' ); ?> <span class="note-info">[<?php _e( 'Deprecated: Will combine all JS files by render blocking type (no longer recommended for HTTP/2 servers)', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_js_min_disable">
<input name="fvm_settings[js][min_disable]" type="checkbox" id="fvm_settings_js_min_disable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'js', 'min_disable')); ?>>
<?php _e( 'Disable JS Files Minification', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will disable JS Files minification for testing purposes', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_js_min_disable_inline">
<input name="fvm_settings[js][min_disable_inline]" type="checkbox" id="fvm_settings_js_min_disable_inline" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'js', 'min_disable_inline')); ?>>
<?php _e( 'Disable JS Inline Minification', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will disable JS Inline minification for testing purposes', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_js_inline-all">
<input name="fvm_settings[js][nopreload]" type="checkbox" id="fvm_settings_js_nopreload" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'js', 'nopreload')); ?>>
<?php _e( 'Disable JS link Preload', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will remove the Render Blocking JS files Link Preload from the header', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Ignore Script Files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_js_ignore"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Will prevent merging or minification for all JS files matching the paths below', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][ignore]" rows="7" cols="50" id="fvm_settings_js_ignore" class="large-text code" placeholder="<?php _e( '--- ex: /plugins/something/assets/problem.js ---', 'fast-velocity-minify' ); ?>"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'ignore'); ?></textarea></p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the script <code>src</code> attribute', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'It is highly recommended to try to leave this empty and later be more specific on what to merge', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Render Blocking JS files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_merge_header"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'This will render block all JS files matching the paths below', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][merge_header]" rows="7" cols="50" id="fvm_settings_js_merge_header" class="large-text code" placeholder="<?php _e( '--- example ---', 'fast-velocity-minify' ); ?>
/jquery-migrate.js
/jquery.js
/jquery.min.js"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'merge_header'); ?></textarea></p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the script <code>src attribute</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Defer JS Files', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_merge_defer"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'This will defer all JS files matching the paths below', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][merge_defer]" rows="7" cols="50" id="fvm_settings_js_merge_defer" class="large-text code" placeholder="<?php _e( '--- example ---', 'fast-velocity-minify' ); ?>
/wp-admin/
/wp-includes/
/wp-content/"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'merge_defer'); ?></textarea></p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the script <code>src attribute', 'fast-velocity-minify' ); ?></code> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Defer Inline JavaScript', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_defer_dependencies"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Preserve the order of scripts execution when deferring JS files dependencies', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][defer_dependencies]" rows="7" cols="50" id="fvm_settings_js_defer_dependencies" class="large-text code" placeholder="<?php _e( '--- example ---', 'fast-velocity-minify' ); ?>
wp.i18n
wp.apiFetch.use
window.lodash
wp.hooks
wp.url"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'defer_dependencies'); ?></textarea></p>
<p class="description">[ <?php _e( 'Inline JavaScript matching these rules, will be deferred with script type module', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the script <code>innerHTML</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Delay third party scripts until user interaction', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_js_thirdparty"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Delay JS files or inline scripts until user interaction', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][thirdparty]" rows="7" cols="50" id="fvm_settings_js_thirdparty" class="large-text code" placeholder="<?php _e( '--- example ---', 'fast-velocity-minify' ); ?>
function(w,d,s,l,i)
function(f,b,e,v,n,t,s)
function(h,o,t,j,a,r)
www.googletagmanager.com/gtm.js"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'thirdparty'); ?></textarea></p>
<p class="description">[ <?php _e( 'Used interaction events: mouseover, keydown, touchstart, touchmove and wheel', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the inline script <code>innerHTML</code> or <code>src</code> attribute for JS files', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Remove JavaScript Scripts', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_js_remove"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Remove the following JS files or Inline Scripts', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[js][remove]" rows="7" cols="50" id="fvm_settings_js_remove" class="large-text code" placeholder="<?php _e( '--- example ---', 'fast-velocity-minify' ); ?>
/some/duplicate/file.js"><?php echo fvm_get_settings_value($fvm_settings, 'js', 'remove'); ?></textarea></p>
<p class="description">[ <?php _e( 'This will allow you to remove unwanted script tags from the frontend', 'fast-velocity-minify' ); ?> ]</p>
<p class="description">[ <?php _e( 'Will match using <code>PHP stripos</code> against the script <code>outerHTML</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
</tbody>
</table>
<div style="height: 60px;"></div>
<h2 class="title"><?php _e( 'CDN Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'If your CDN provider gives you a different URL for your assets, you can use it here', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'CDN Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Select your options below', 'fast-velocity-minify' ); ?></p>
<fieldset>
<label for="fvm_settings_cdn_enable">
<input name="fvm_settings[cdn][enable]" type="checkbox" id="fvm_settings_cdn_enable" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'cdn', 'enable')); ?>>
<?php _e( 'Enable CDN Processing', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will enable processing for the settings below', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_cdn_cssok">
<input name="fvm_settings[cdn][cssok]" type="checkbox" id="fvm_settings_cdn_cssok" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'cdn', 'cssok')); ?>>
<?php _e( 'Enable CDN for merged CSS files', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will serve the FVM generated CSS files from the CDN', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
<label for="fvm_settings_cdn_jsok">
<input name="fvm_settings[cdn][jsok]" type="checkbox" id="fvm_settings_cdn_jsok" value="1" <?php echo fvm_get_settings_checkbox(fvm_get_settings_value($fvm_settings, 'cdn', 'jsok')); ?>>
<?php _e( 'Enable CDN for merged JS files', 'fast-velocity-minify' ); ?> <span class="note-info">[ <?php _e( 'Will serve the FVM generated JS files from the CDN', 'fast-velocity-minify' ); ?> ]</span></label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><span class="fvm-label-special"><?php _e( 'CDN URL', 'fast-velocity-minify' ); ?></span></th>
<td><fieldset>
<label for="fvm_settings_cdn_domain">
<p><input type="text" name="fvm_settings[cdn][domain]" id="fvm_settings_cdn_domain" value="<?php echo fvm_get_settings_value($fvm_settings, 'cdn', 'domain'); ?>" size="80" /></p>
<p class="description">[ <?php _e( 'You can ignore this if your CDN url matches your domain name (ie: Cloudflare)', 'fast-velocity-minify' ); ?> ]</p>
</label>
<br />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'CDN Integration', 'fast-velocity-minify' ); ?></th>
<td><fieldset>
<label for="fvm_settings_cdn_integration"><span class="fvm-bold-green fvm-rowintro"><?php _e( 'Missing HTML elements to replace', 'fast-velocity-minify' ); ?></span></label>
<p><textarea name="fvm_settings[cdn][integration]" rows="7" cols="50" id="fvm_settings_cdn_integration" class="large-text code" placeholder="--- check the help section for suggestions ---"><?php echo fvm_get_settings_value($fvm_settings, 'cdn', 'integration'); ?></textarea></p>
<p class="description">[ <?php _e( 'Additional replacement rules with syntax from <code>https://simplehtmldom.sourceforge.io/manual.htm</code>', 'fast-velocity-minify' ); ?> ]</p>
</fieldset></td>
</tr>
</tbody></table>
<div style="height: 60px;"></div>
<h2 class="title"><?php _e( 'User Settings', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'For compatibility reasons, only anonymous users should be optimized by default.', 'fast-velocity-minify' ); ?></h3>
<table class="form-table fvm-settings">
<tbody>
<tr>
<th scope="row"><?php _e( 'User Options', 'fast-velocity-minify' ); ?></th>
<td>
<p class="fvm-bold-green fvm-rowintro"><?php _e( 'Force optimization for the following user roles', 'fast-velocity-minify' ); ?></p>
<fieldset>
<?php
# output user roles checkboxes
echo fvm_get_user_roles_checkboxes();
?>
</fieldset></td>
</tbody></table>
<input type="hidden" name="fvm_action" value="save_settings" />
<p class="submit"><input type="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'fast-velocity-minify' ); ?>"></p>
</form>
</div>
<?php
}
<?php
# server info
if( $active_tab == 'status' ) {
?>
<div class="fvm-wrapper">
<div id="status">
<div style="height: 40px;"></div>
<h2 class="title"><?php _e( 'Latest Logs', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'In this section, you can check the latest logs for CSS and JS files', 'fast-velocity-minify' ); ?></h3>
<div class="row-log log-stats wpraiser-textarea"><textarea rows="10" cols="50" class="large-text code row-log log-css" disabled></textarea></div>
<div style="height: 40px;"></div>
<h2 class="title"><?php _e( 'Server Info', 'fast-velocity-minify' ); ?></h2>
<h3 class="fvm-bold-green"><?php _e( 'In this section, you can check some server stats and information', 'fast-velocity-minify' ); ?></h3>
<textarea rows="10" cols="50" class="large-text code row-log" disabled><?php fvm_get_generalinfo(); ?></textarea>
<script>fvm_get_logs();</script>
</div>
</div>
<?php
}
\ No newline at end of file
<?php if( $active_tab == 'upgrade' ) { ?>
<div class="fvm-wrapper">
<h2 class="title">Upgrade Your Speed</h2>
<h3 class="fvm-bold-green">Would you like to improve your speed and google scores further?</h3>
</div>
<?php
}
<div class="wrap">
<h1>Fast Velocity Minify</h1>
<div style="height: 20px;"></div>
<?php
# get active tab, set default
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'settings';
?>
<h2 class="nav-tab-wrapper wp-clearfix">
<a href="?page=fvm" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Settings', 'fast-velocity-minify' ); ?></a>
<a href="?page=fvm&tab=status" class="nav-tab <?php echo $active_tab == 'status' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Status', 'fast-velocity-minify' ); ?></a>
<?php /*<a href="?page=fvm&tab=upgrade" class="nav-tab <?php echo $active_tab == 'upgrade' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Upgrade', 'fast-velocity-minify' ); ?></a>*/ ?>
<a href="?page=fvm&tab=help" class="nav-tab <?php echo $active_tab == 'help' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Help', 'fast-velocity-minify' ); ?></a>
</h2>
<div id="fvm">
<?php
# settings
include_once($fvm_var_dir_path . 'layout' . DIRECTORY_SEPARATOR . 'admin-layout-settings.php');
# include other tabs
include_once($fvm_var_dir_path . 'layout' . DIRECTORY_SEPARATOR . 'admin-layout-status.php');
#include_once($fvm_var_dir_path . 'layout' . DIRECTORY_SEPARATOR . 'admin-layout-upgrade.php');
include_once($fvm_var_dir_path . 'layout' . DIRECTORY_SEPARATOR . 'admin-layout-help.php');
?>
</div>
\ No newline at end of file
# replace
namespace MatthiasMullie > namespace FVM\MatthiasMullie
use MatthiasMullie > use FVM\MatthiasMullie
\ No newline at end of file
#!/usr/bin/env php
<?php
use MatthiasMullie\Minify;
// command line utility to minify CSS
if (file_exists(__DIR__ . '/../../../autoload.php')) {
// if composer install
require_once __DIR__ . '/../../../autoload.php';
} else {
require_once __DIR__ . '/../src/Minify.php';
require_once __DIR__ . '/../src/CSS.php';
require_once __DIR__ . '/../src/Exception.php';
}
error_reporting(E_ALL);
// check PHP setup for cli arguments
if (!isset($_SERVER['argv']) && !isset($argv)) {
fwrite(STDERR, 'Please enable the "register_argc_argv" directive in your php.ini' . PHP_EOL);
exit(1);
} elseif (!isset($argv)) {
$argv = $_SERVER['argv'];
}
// check if path to file given
if (!isset($argv[1])) {
fwrite(STDERR, 'Argument expected: path to file' . PHP_EOL);
exit(1);
}
// check if script run in cli environment
if ('cli' !== php_sapi_name()) {
fwrite(STDERR, $argv[1] . ' must be run in the command line' . PHP_EOL);
exit(1);
}
// check if source file exists
if (!file_exists($argv[1])) {
fwrite(STDERR, 'Source file "' . $argv[1] . '" not found' . PHP_EOL);
exit(1);
}
try {
$minifier = new Minify\CSS($argv[1]);
echo $minifier->minify();
} catch (Exception $e) {
fwrite(STDERR, $e->getMessage(), PHP_EOL);
exit(1);
}
#!/usr/bin/env php
<?php
use MatthiasMullie\Minify;
// command line utility to minify JS
if (file_exists(__DIR__ . '/../../../autoload.php')) {
// if composer install
require_once __DIR__ . '/../../../autoload.php';
} else {
require_once __DIR__ . '/../src/Minify.php';
require_once __DIR__ . '/../src/JS.php';
require_once __DIR__ . '/../src/Exception.php';
}
error_reporting(E_ALL);
// check PHP setup for cli arguments
if (!isset($_SERVER['argv']) && !isset($argv)) {
fwrite(STDERR, 'Please enable the "register_argc_argv" directive in your php.ini' . PHP_EOL);
exit(1);
} elseif (!isset($argv)) {
$argv = $_SERVER['argv'];
}
// check if path to file given
if (!isset($argv[1])) {
fwrite(STDERR, 'Argument expected: path to file' . PHP_EOL);
exit(1);
}
// check if script run in cli environment
if ('cli' !== php_sapi_name()) {
fwrite(STDERR, $argv[1] . ' must be run in the command line' . PHP_EOL);
exit(1);
}
// check if source file exists
if (!file_exists($argv[1])) {
fwrite(STDERR, 'Source file "' . $argv[1] . '" not found' . PHP_EOL);
exit(1);
}
try {
$minifier = new Minify\JS($argv[1]);
echo $minifier->minify();
} catch (Exception $e) {
fwrite(STDERR, $e->getMessage(), PHP_EOL);
exit(1);
}
in
public
extends
private
protected
implements
instanceof
\ No newline at end of file
do
in
let
new
var
case
else
enum
void
with
class
const
yield
delete
export
import
public
static
typeof
extends
package
private
function
protected
implements
instanceof
\ No newline at end of file
do
if
in
for
let
new
try
var
case
else
enum
eval
null
this
true
void
with
break
catch
class
const
false
super
throw
while
yield
delete
export
import
public
return
static
switch
typeof
default
extends
finally
package
private
continue
debugger
function
arguments
interface
protected
implements
instanceof
abstract
boolean
byte
char
double
final
float
goto
int
long
native
short
synchronized
throws
transient
volatile
\ No newline at end of file
+
-
*
/
%
=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
&
|
^
~
<<
>>
>>>
==
===
!=
!==
>
<
>=
<=
&&
||
!
.
[
]
?
:
,
;
(
)
{
}
\ No newline at end of file
+
-
*
/
%
=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
&
|
^
<<
>>
>>>
==
===
!=
!==
>
<
>=
<=
&&
||
.
[
]
?
:
,
;
(
)
}
\ No newline at end of file
+
-
*
/
%
=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
&
|
^
~
<<
>>
>>>
==
===
!=
!==
>
<
>=
<=
&&
||
!
.
[
?
:
,
;
(
{
<?php
/**
* CSS Minifier
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify;
use FVM\MatthiasMullie\Minify\Exceptions\FileImportException;
use FVM\MatthiasMullie\PathConverter\ConverterInterface;
use FVM\MatthiasMullie\PathConverter\Converter;
/**
* CSS minifier
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @package Minify
* @author Matthias Mullie <minify@mullie.eu>
* @author Tijs Verkoyen <minify@verkoyen.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
class CSS extends Minify
{
/**
* @var int maximum inport size in kB
*/
protected $maxImportSize = 5;
/**
* @var string[] valid import extensions
*/
protected $importExtensions = array(
'gif' => 'data:image/gif',
'png' => 'data:image/png',
'jpe' => 'data:image/jpeg',
'jpg' => 'data:image/jpeg',
'jpeg' => 'data:image/jpeg',
'svg' => 'data:image/svg+xml',
'woff' => 'data:application/x-font-woff',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'xbm' => 'image/x-xbitmap',
);
/**
* Set the maximum size if files to be imported.
*
* Files larger than this size (in kB) will not be imported into the CSS.
* Importing files into the CSS as data-uri will save you some connections,
* but we should only import relatively small decorative images so that our
* CSS file doesn't get too bulky.
*
* @param int $size Size in kB
*/
public function setMaxImportSize($size)
{
$this->maxImportSize = $size;
}
/**
* Set the type of extensions to be imported into the CSS (to save network
* connections).
* Keys of the array should be the file extensions & respective values
* should be the data type.
*
* @param string[] $extensions Array of file extensions
*/
public function setImportExtensions(array $extensions)
{
$this->importExtensions = $extensions;
}
/**
* Move any import statements to the top.
*
* @param string $content Nearly finished CSS content
*
* @return string
*/
protected function moveImportsToTop($content)
{
if (preg_match_all('/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)));?/', $content, $matches)) {
// remove from content
foreach ($matches[0] as $import) {
$content = str_replace($import, '', $content);
}
// add to top
$content = implode(';', $matches[2]).';'.trim($content, ';');
}
return $content;
}
/**
* Combine CSS from import statements.
*
* @import's will be loaded and their content merged into the original file,
* to save HTTP requests.
*
* @param string $source The file to combine imports for
* @param string $content The CSS content to combine imports for
* @param string[] $parents Parent paths, for circular reference checks
*
* @return string
*
* @throws FileImportException
*/
protected function combineImports($source, $content, $parents)
{
$importRegexes = array(
// @import url(xxx)
'/
# import statement
@import
# whitespace
\s+
# open url()
url\(
# (optional) open path enclosure
(?P<quotes>["\']?)
# fetch path
(?P<path>.+?)
# (optional) close path enclosure
(?P=quotes)
# close url()
\)
# (optional) trailing whitespace
\s*
# (optional) media statement(s)
(?P<media>[^;]*)
# (optional) trailing whitespace
\s*
# (optional) closing semi-colon
;?
/ix',
// @import 'xxx'
'/
# import statement
@import
# whitespace
\s+
# open path enclosure
(?P<quotes>["\'])
# fetch path
(?P<path>.+?)
# close path enclosure
(?P=quotes)
# (optional) trailing whitespace
\s*
# (optional) media statement(s)
(?P<media>[^;]*)
# (optional) trailing whitespace
\s*
# (optional) closing semi-colon
;?
/ix',
);
// find all relative imports in css
$matches = array();
foreach ($importRegexes as $importRegex) {
if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
$matches = array_merge($matches, $regexMatches);
}
}
$search = array();
$replace = array();
// loop the matches
foreach ($matches as $match) {
// get the path for the file that will be imported
$importPath = dirname($source).'/'.$match['path'];
// only replace the import with the content if we can grab the
// content of the file
if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
continue;
}
// check if current file was not imported previously in the same
// import chain.
if (in_array($importPath, $parents)) {
throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
}
// grab referenced file & minify it (which may include importing
// yet other @import statements recursively)
$minifier = new static($importPath);
$minifier->setMaxImportSize($this->maxImportSize);
$minifier->setImportExtensions($this->importExtensions);
$importContent = $minifier->execute($source, $parents);
// check if this is only valid for certain media
if (!empty($match['media'])) {
$importContent = '@media '.$match['media'].'{'.$importContent.'}';
}
// add to replacement array
$search[] = $match[0];
$replace[] = $importContent;
}
// replace the import statements
return str_replace($search, $replace, $content);
}
/**
* Import files into the CSS, base64-ized.
*
* @url(image.jpg) images will be loaded and their content merged into the
* original file, to save HTTP requests.
*
* @param string $source The file to import files for
* @param string $content The CSS content to import files for
*
* @return string
*/
protected function importFiles($source, $content)
{
$regex = '/url\((["\']?)(.+?)\\1\)/i';
if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
$search = array();
$replace = array();
// loop the matches
foreach ($matches as $match) {
$extension = substr(strrchr($match[2], '.'), 1);
if ($extension && !array_key_exists($extension, $this->importExtensions)) {
continue;
}
// get the path for the file that will be imported
$path = $match[2];
$path = dirname($source).'/'.$path;
// only replace the import with the content if we're able to get
// the content of the file, and it's relatively small
if ($this->canImportFile($path) && $this->canImportBySize($path)) {
// grab content && base64-ize
$importContent = $this->load($path);
$importContent = base64_encode($importContent);
// build replacement
$search[] = $match[0];
$replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
}
}
// replace the import statements
$content = str_replace($search, $replace, $content);
}
return $content;
}
/**
* Minify the data.
* Perform CSS optimizations.
*
* @param string[optional] $path Path to write the data to
* @param string[] $parents Parent paths, for circular reference checks
*
* @return string The minified data
*/
public function execute($path = null, $parents = array())
{
$content = '';
// loop CSS data (raw data and files)
foreach ($this->data as $source => $css) {
/*
* Let's first take out strings & comments, since we can't just
* remove whitespace anywhere. If whitespace occurs inside a string,
* we should leave it alone. E.g.:
* p { content: "a test" }
*/
$this->extractStrings();
$this->stripComments();
$this->extractCalcs();
$css = $this->replace($css);
$css = $this->stripWhitespace($css);
$css = $this->shortenColors($css);
$css = $this->shortenZeroes($css);
$css = $this->shortenFontWeights($css);
$css = $this->stripEmptyTags($css);
// restore the string we've extracted earlier
$css = $this->restoreExtractedData($css);
$source = is_int($source) ? '' : $source;
$parents = $source ? array_merge($parents, array($source)) : $parents;
$css = $this->combineImports($source, $css, $parents);
$css = $this->importFiles($source, $css);
/*
* If we'll save to a new path, we'll have to fix the relative paths
* to be relative no longer to the source file, but to the new path.
* If we don't write to a file, fall back to same path so no
* conversion happens (because we still want it to go through most
* of the move code, which also addresses url() & @import syntax...)
*/
$converter = $this->getPathConverter($source, $path ?: $source);
$css = $this->move($converter, $css);
// combine css
$content .= $css;
}
$content = $this->moveImportsToTop($content);
return $content;
}
/**
* Moving a css file should update all relative urls.
* Relative references (e.g. ../images/image.gif) in a certain css file,
* will have to be updated when a file is being saved at another location
* (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
*
* @param ConverterInterface $converter Relative path converter
* @param string $content The CSS content to update relative urls for
*
* @return string
*/
protected function move(ConverterInterface $converter, $content)
{
/*
* Relative path references will usually be enclosed by url(). @import
* is an exception, where url() is not necessary around the path (but is
* allowed).
* This *could* be 1 regular expression, where both regular expressions
* in this array are on different sides of a |. But we're using named
* patterns in both regexes, the same name on both regexes. This is only
* possible with a (?J) modifier, but that only works after a fairly
* recent PCRE version. That's why I'm doing 2 separate regular
* expressions & combining the matches after executing of both.
*/
$relativeRegexes = array(
// url(xxx)
'/
# open url()
url\(
\s*
# open path enclosure
(?P<quotes>["\'])?
# fetch path
(?P<path>.+?)
# close path enclosure
(?(quotes)(?P=quotes))
\s*
# close url()
\)
/ix',
// @import "xxx"
'/
# import statement
@import
# whitespace
\s+
# we don\'t have to check for @import url(), because the
# condition above will already catch these
# open path enclosure
(?P<quotes>["\'])
# fetch path
(?P<path>.+?)
# close path enclosure
(?P=quotes)
/ix',
);
// find all relative urls in css
$matches = array();
foreach ($relativeRegexes as $relativeRegex) {
if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
$matches = array_merge($matches, $regexMatches);
}
}
$search = array();
$replace = array();
// loop all urls
foreach ($matches as $match) {
// determine if it's a url() or an @import match
$type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
$url = $match['path'];
if ($this->canImportByPath($url)) {
// attempting to interpret GET-params makes no sense, so let's discard them for awhile
$params = strrchr($url, '?');
$url = $params ? substr($url, 0, -strlen($params)) : $url;
// fix relative url
$url = $converter->convert($url);
// now that the path has been converted, re-apply GET-params
$url .= $params;
}
/*
* Urls with control characters above 0x7e should be quoted.
* According to Mozilla's parser, whitespace is only allowed at the
* end of unquoted urls.
* Urls with `)` (as could happen with data: uris) should also be
* quoted to avoid being confused for the url() closing parentheses.
* And urls with a # have also been reported to cause issues.
* Urls with quotes inside should also remain escaped.
*
* @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
* @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
* @see https://github.com/matthiasmullie/minify/issues/193
*/
$url = trim($url);
if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
$url = $match['quotes'] . $url . $match['quotes'];
}
// build replacement
$search[] = $match[0];
if ($type === 'url') {
$replace[] = 'url('.$url.')';
} elseif ($type === 'import') {
$replace[] = '@import "'.$url.'"';
}
}
// replace urls
return str_replace($search, $replace, $content);
}
/**
* Shorthand hex color codes.
* #FF0000 -> #F00.
*
* @param string $content The CSS content to shorten the hex color codes for
*
* @return string
*/
protected function shortenColors($content)
{
$content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?:([0-9a-z])\\4)?(?=[; }])/i', '#$1$2$3$4', $content);
// remove alpha channel if it's pointless...
$content = preg_replace('/(?<=[: ])#([0-9a-z]{6})ff?(?=[; }])/i', '#$1', $content);
$content = preg_replace('/(?<=[: ])#([0-9a-z]{3})f?(?=[; }])/i', '#$1', $content);
$colors = array(
// we can shorten some even more by replacing them with their color name
'#F0FFFF' => 'azure',
'#F5F5DC' => 'beige',
'#A52A2A' => 'brown',
'#FF7F50' => 'coral',
'#FFD700' => 'gold',
'#808080' => 'gray',
'#008000' => 'green',
'#4B0082' => 'indigo',
'#FFFFF0' => 'ivory',
'#F0E68C' => 'khaki',
'#FAF0E6' => 'linen',
'#800000' => 'maroon',
'#000080' => 'navy',
'#808000' => 'olive',
'#CD853F' => 'peru',
'#FFC0CB' => 'pink',
'#DDA0DD' => 'plum',
'#800080' => 'purple',
'#F00' => 'red',
'#FA8072' => 'salmon',
'#A0522D' => 'sienna',
'#C0C0C0' => 'silver',
'#FFFAFA' => 'snow',
'#D2B48C' => 'tan',
'#FF6347' => 'tomato',
'#EE82EE' => 'violet',
'#F5DEB3' => 'wheat',
// or the other way around
'WHITE' => '#fff',
'BLACK' => '#000',
);
return preg_replace_callback(
'/(?<=[: ])('.implode('|', array_keys($colors)).')(?=[; }])/i',
function ($match) use ($colors) {
return $colors[strtoupper($match[0])];
},
$content
);
}
/**
* Shorten CSS font weights.
*
* @param string $content The CSS content to shorten the font weights for
*
* @return string
*/
protected function shortenFontWeights($content)
{
$weights = array(
'normal' => 400,
'bold' => 700,
);
$callback = function ($match) use ($weights) {
return $match[1].$weights[$match[2]];
};
return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
}
/**
* Shorthand 0 values to plain 0, instead of e.g. -0em.
*
* @param string $content The CSS content to shorten the zero values for
*
* @return string
*/
protected function shortenZeroes($content)
{
// we don't want to strip units in `calc()` expressions:
// `5px - 0px` is valid, but `5px - 0` is not
// `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
// `10 * 0` is invalid
// we've extracted calcs earlier, so we don't need to worry about this
// reusable bits of code throughout these regexes:
// before & after are used to make sure we don't match lose unintended
// 0-like values (e.g. in #000, or in http://url/1.0)
// units can be stripped from 0 values, or used to recognize non 0
// values (where wa may be able to strip a .0 suffix)
$before = '(?<=[:(, ])';
$after = '(?=[ ,);}])';
$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
// strip units after zeroes (0px -> 0)
// NOTE: it should be safe to remove all units for a 0 value, but in
// practice, Webkit (especially Safari) seems to stumble over at least
// 0%, potentially other units as well. Only stripping 'px' for now.
// @see https://github.com/matthiasmullie/minify/issues/60
$content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
// strip 0-digits (.0 -> 0)
$content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
// strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
$content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
// strip trailing 0: 50.00 -> 50, 50.00px -> 50px
$content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
// strip leading 0: 0.1 -> .1, 01.1 -> 1.1
$content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
// strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
$content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
// IE doesn't seem to understand a unitless flex-basis value (correct -
// it goes against the spec), so let's add it in again (make it `%`,
// which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
// @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
$content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
$content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
return $content;
}
/**
* Strip empty tags from source code.
*
* @param string $content
*
* @return string
*/
protected function stripEmptyTags($content)
{
$content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
$content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
return $content;
}
/**
* Strip comments from source code.
*/
protected function stripComments()
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$callback = function ($match) use ($minifier) {
$count = count($minifier->extracted);
$placeholder = '/*'.$count.'*/';
$minifier->extracted[$placeholder] = $match[0];
return $placeholder;
};
$this->registerPattern('/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s', $callback);
$this->registerPattern('/\/\*.*?\*\//s', '');
}
/**
* Strip whitespace.
*
* @param string $content The CSS content to strip the whitespace for
*
* @return string
*/
protected function stripWhitespace($content)
{
// remove leading & trailing whitespace
$content = preg_replace('/^\s*/m', '', $content);
$content = preg_replace('/\s*$/m', '', $content);
// replace newlines with a single space
$content = preg_replace('/\s+/', ' ', $content);
// remove whitespace around meta characters
// inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
$content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
$content = preg_replace('/([\[(:>\+])\s+/', '$1', $content);
$content = preg_replace('/\s+([\]\)>\+])/', '$1', $content);
$content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
// whitespace around + and - can only be stripped inside some pseudo-
// classes, like `:nth-child(3+2n)`
// not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
// selectors like `div.weird- p`
$pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
$content = preg_replace('/:('.implode('|', $pseudos).')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
// remove semicolon/whitespace followed by closing bracket
$content = str_replace(';}', '}', $content);
return trim($content);
}
/**
* Replace all `calc()` occurrences.
*/
protected function extractCalcs()
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$callback = function ($match) use ($minifier) {
$length = strlen($match[1]);
$expr = '';
$opened = 0;
for ($i = 0; $i < $length; $i++) {
$char = $match[1][$i];
$expr .= $char;
if ($char === '(') {
$opened++;
} elseif ($char === ')' && --$opened === 0) {
break;
}
}
$rest = str_replace($expr, '', $match[1]);
$expr = trim(substr($expr, 1, -1));
$count = count($minifier->extracted);
$placeholder = 'calc('.$count.')';
$minifier->extracted[$placeholder] = 'calc('.$expr.')';
return $placeholder.$rest;
};
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/', $callback);
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/m', $callback);
}
/**
* Check if file is small enough to be imported.
*
* @param string $path The path to the file
*
* @return bool
*/
protected function canImportBySize($path)
{
return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
}
/**
* Check if file a file can be imported, going by the path.
*
* @param string $path
*
* @return bool
*/
protected function canImportByPath($path)
{
return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
}
/**
* Return a converter to update relative paths to be relative to the new
* destination.
*
* @param string $source
* @param string $target
*
* @return ConverterInterface
*/
protected function getPathConverter($source, $target)
{
return new Converter($source, $target);
}
}
<?php
/**
* Base Exception
*
* @deprecated Use Exceptions\BasicException instead
*
* @author Matthias Mullie <minify@mullie.eu>
*/
namespace FVM\MatthiasMullie\Minify;
/**
* Base Exception Class
* @deprecated Use Exceptions\BasicException instead
*
* @package Minify
* @author Matthias Mullie <minify@mullie.eu>
*/
abstract class Exception extends \Exception
{
}
<?php
/**
* Basic exception
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify\Exceptions;
use FVM\MatthiasMullie\Minify\Exception;
/**
* Basic Exception Class
*
* @package Minify\Exception
* @author Matthias Mullie <minify@mullie.eu>
*/
abstract class BasicException extends Exception
{
}
<?php
/**
* File Import Exception
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify\Exceptions;
/**
* File Import Exception Class
*
* @package Minify\Exception
* @author Matthias Mullie <minify@mullie.eu>
*/
class FileImportException extends BasicException
{
}
<?php
/**
* IO Exception
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify\Exceptions;
/**
* IO Exception Class
*
* @package Minify\Exception
* @author Matthias Mullie <minify@mullie.eu>
*/
class IOException extends BasicException
{
}
<?php
/**
* JavaScript minifier
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify;
/**
* JavaScript Minifier Class
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @package Minify
* @author Matthias Mullie <minify@mullie.eu>
* @author Tijs Verkoyen <minify@verkoyen.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
class JS extends Minify
{
/**
* Var-matching regex based on http://stackoverflow.com/a/9337047/802993.
*
* Note that regular expressions using that bit must have the PCRE_UTF8
* pattern modifier (/u) set.
*
* @var string
*/
const REGEX_VARIABLE = '\b[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\x{02c1}\x{02c6}-\x{02d1}\x{02e0}-\x{02e4}\x{02ec}\x{02ee}\x{0370}-\x{0374}\x{0376}\x{0377}\x{037a}-\x{037d}\x{0386}\x{0388}-\x{038a}\x{038c}\x{038e}-\x{03a1}\x{03a3}-\x{03f5}\x{03f7}-\x{0481}\x{048a}-\x{0527}\x{0531}-\x{0556}\x{0559}\x{0561}-\x{0587}\x{05d0}-\x{05ea}\x{05f0}-\x{05f2}\x{0620}-\x{064a}\x{066e}\x{066f}\x{0671}-\x{06d3}\x{06d5}\x{06e5}\x{06e6}\x{06ee}\x{06ef}\x{06fa}-\x{06fc}\x{06ff}\x{0710}\x{0712}-\x{072f}\x{074d}-\x{07a5}\x{07b1}\x{07ca}-\x{07ea}\x{07f4}\x{07f5}\x{07fa}\x{0800}-\x{0815}\x{081a}\x{0824}\x{0828}\x{0840}-\x{0858}\x{08a0}\x{08a2}-\x{08ac}\x{0904}-\x{0939}\x{093d}\x{0950}\x{0958}-\x{0961}\x{0971}-\x{0977}\x{0979}-\x{097f}\x{0985}-\x{098c}\x{098f}\x{0990}\x{0993}-\x{09a8}\x{09aa}-\x{09b0}\x{09b2}\x{09b6}-\x{09b9}\x{09bd}\x{09ce}\x{09dc}\x{09dd}\x{09df}-\x{09e1}\x{09f0}\x{09f1}\x{0a05}-\x{0a0a}\x{0a0f}\x{0a10}\x{0a13}-\x{0a28}\x{0a2a}-\x{0a30}\x{0a32}\x{0a33}\x{0a35}\x{0a36}\x{0a38}\x{0a39}\x{0a59}-\x{0a5c}\x{0a5e}\x{0a72}-\x{0a74}\x{0a85}-\x{0a8d}\x{0a8f}-\x{0a91}\x{0a93}-\x{0aa8}\x{0aaa}-\x{0ab0}\x{0ab2}\x{0ab3}\x{0ab5}-\x{0ab9}\x{0abd}\x{0ad0}\x{0ae0}\x{0ae1}\x{0b05}-\x{0b0c}\x{0b0f}\x{0b10}\x{0b13}-\x{0b28}\x{0b2a}-\x{0b30}\x{0b32}\x{0b33}\x{0b35}-\x{0b39}\x{0b3d}\x{0b5c}\x{0b5d}\x{0b5f}-\x{0b61}\x{0b71}\x{0b83}\x{0b85}-\x{0b8a}\x{0b8e}-\x{0b90}\x{0b92}-\x{0b95}\x{0b99}\x{0b9a}\x{0b9c}\x{0b9e}\x{0b9f}\x{0ba3}\x{0ba4}\x{0ba8}-\x{0baa}\x{0bae}-\x{0bb9}\x{0bd0}\x{0c05}-\x{0c0c}\x{0c0e}-\x{0c10}\x{0c12}-\x{0c28}\x{0c2a}-\x{0c33}\x{0c35}-\x{0c39}\x{0c3d}\x{0c58}\x{0c59}\x{0c60}\x{0c61}\x{0c85}-\x{0c8c}\x{0c8e}-\x{0c90}\x{0c92}-\x{0ca8}\x{0caa}-\x{0cb3}\x{0cb5}-\x{0cb9}\x{0cbd}\x{0cde}\x{0ce0}\x{0ce1}\x{0cf1}\x{0cf2}\x{0d05}-\x{0d0c}\x{0d0e}-\x{0d10}\x{0d12}-\x{0d3a}\x{0d3d}\x{0d4e}\x{0d60}\x{0d61}\x{0d7a}-\x{0d7f}\x{0d85}-\x{0d96}\x{0d9a}-\x{0db1}\x{0db3}-\x{0dbb}\x{0dbd}\x{0dc0}-\x{0dc6}\x{0e01}-\x{0e30}\x{0e32}\x{0e33}\x{0e40}-\x{0e46}\x{0e81}\x{0e82}\x{0e84}\x{0e87}\x{0e88}\x{0e8a}\x{0e8d}\x{0e94}-\x{0e97}\x{0e99}-\x{0e9f}\x{0ea1}-\x{0ea3}\x{0ea5}\x{0ea7}\x{0eaa}\x{0eab}\x{0ead}-\x{0eb0}\x{0eb2}\x{0eb3}\x{0ebd}\x{0ec0}-\x{0ec4}\x{0ec6}\x{0edc}-\x{0edf}\x{0f00}\x{0f40}-\x{0f47}\x{0f49}-\x{0f6c}\x{0f88}-\x{0f8c}\x{1000}-\x{102a}\x{103f}\x{1050}-\x{1055}\x{105a}-\x{105d}\x{1061}\x{1065}\x{1066}\x{106e}-\x{1070}\x{1075}-\x{1081}\x{108e}\x{10a0}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{10fa}\x{10fc}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1380}-\x{138f}\x{13a0}-\x{13f4}\x{1401}-\x{166c}\x{166f}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16ea}\x{16ee}-\x{16f0}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17d7}\x{17dc}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191c}\x{1950}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19c1}-\x{19c7}\x{1a00}-\x{1a16}\x{1a20}-\x{1a54}\x{1aa7}\x{1b05}-\x{1b33}\x{1b45}-\x{1b4b}\x{1b83}-\x{1ba0}\x{1bae}\x{1baf}\x{1bba}-\x{1be5}\x{1c00}-\x{1c23}\x{1c4d}-\x{1c4f}\x{1c5a}-\x{1c7d}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf1}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{2160}-\x{2188}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{2e2f}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{31a0}-\x{31ba}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}\x{4e00}-\x{9fcc}\x{a000}-\x{a48c}\x{a4d0}-\x{a4fd}\x{a500}-\x{a60c}\x{a610}-\x{a61f}\x{a62a}\x{a62b}\x{a640}-\x{a66e}\x{a67f}-\x{a697}\x{a6a0}-\x{a6ef}\x{a717}-\x{a71f}\x{a722}-\x{a788}\x{a78b}-\x{a78e}\x{a790}-\x{a793}\x{a7a0}-\x{a7aa}\x{a7f8}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a822}\x{a840}-\x{a873}\x{a882}-\x{a8b3}\x{a8f2}-\x{a8f7}\x{a8fb}\x{a90a}-\x{a925}\x{a930}-\x{a946}\x{a960}-\x{a97c}\x{a984}-\x{a9b2}\x{a9cf}\x{aa00}-\x{aa28}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa60}-\x{aa76}\x{aa7a}\x{aa80}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aadd}\x{aae0}-\x{aaea}\x{aaf2}-\x{aaf4}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{abc0}-\x{abe2}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{f900}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb36}\x{fb38}-\x{fb3c}\x{fb3e}\x{fb40}\x{fb41}\x{fb43}\x{fb44}\x{fb46}-\x{fbb1}\x{fbd3}-\x{fd3d}\x{fd50}-\x{fd8f}\x{fd92}-\x{fdc7}\x{fdf0}-\x{fdfb}\x{fe70}-\x{fe74}\x{fe76}-\x{fefc}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\x{02c1}\x{02c6}-\x{02d1}\x{02e0}-\x{02e4}\x{02ec}\x{02ee}\x{0370}-\x{0374}\x{0376}\x{0377}\x{037a}-\x{037d}\x{0386}\x{0388}-\x{038a}\x{038c}\x{038e}-\x{03a1}\x{03a3}-\x{03f5}\x{03f7}-\x{0481}\x{048a}-\x{0527}\x{0531}-\x{0556}\x{0559}\x{0561}-\x{0587}\x{05d0}-\x{05ea}\x{05f0}-\x{05f2}\x{0620}-\x{064a}\x{066e}\x{066f}\x{0671}-\x{06d3}\x{06d5}\x{06e5}\x{06e6}\x{06ee}\x{06ef}\x{06fa}-\x{06fc}\x{06ff}\x{0710}\x{0712}-\x{072f}\x{074d}-\x{07a5}\x{07b1}\x{07ca}-\x{07ea}\x{07f4}\x{07f5}\x{07fa}\x{0800}-\x{0815}\x{081a}\x{0824}\x{0828}\x{0840}-\x{0858}\x{08a0}\x{08a2}-\x{08ac}\x{0904}-\x{0939}\x{093d}\x{0950}\x{0958}-\x{0961}\x{0971}-\x{0977}\x{0979}-\x{097f}\x{0985}-\x{098c}\x{098f}\x{0990}\x{0993}-\x{09a8}\x{09aa}-\x{09b0}\x{09b2}\x{09b6}-\x{09b9}\x{09bd}\x{09ce}\x{09dc}\x{09dd}\x{09df}-\x{09e1}\x{09f0}\x{09f1}\x{0a05}-\x{0a0a}\x{0a0f}\x{0a10}\x{0a13}-\x{0a28}\x{0a2a}-\x{0a30}\x{0a32}\x{0a33}\x{0a35}\x{0a36}\x{0a38}\x{0a39}\x{0a59}-\x{0a5c}\x{0a5e}\x{0a72}-\x{0a74}\x{0a85}-\x{0a8d}\x{0a8f}-\x{0a91}\x{0a93}-\x{0aa8}\x{0aaa}-\x{0ab0}\x{0ab2}\x{0ab3}\x{0ab5}-\x{0ab9}\x{0abd}\x{0ad0}\x{0ae0}\x{0ae1}\x{0b05}-\x{0b0c}\x{0b0f}\x{0b10}\x{0b13}-\x{0b28}\x{0b2a}-\x{0b30}\x{0b32}\x{0b33}\x{0b35}-\x{0b39}\x{0b3d}\x{0b5c}\x{0b5d}\x{0b5f}-\x{0b61}\x{0b71}\x{0b83}\x{0b85}-\x{0b8a}\x{0b8e}-\x{0b90}\x{0b92}-\x{0b95}\x{0b99}\x{0b9a}\x{0b9c}\x{0b9e}\x{0b9f}\x{0ba3}\x{0ba4}\x{0ba8}-\x{0baa}\x{0bae}-\x{0bb9}\x{0bd0}\x{0c05}-\x{0c0c}\x{0c0e}-\x{0c10}\x{0c12}-\x{0c28}\x{0c2a}-\x{0c33}\x{0c35}-\x{0c39}\x{0c3d}\x{0c58}\x{0c59}\x{0c60}\x{0c61}\x{0c85}-\x{0c8c}\x{0c8e}-\x{0c90}\x{0c92}-\x{0ca8}\x{0caa}-\x{0cb3}\x{0cb5}-\x{0cb9}\x{0cbd}\x{0cde}\x{0ce0}\x{0ce1}\x{0cf1}\x{0cf2}\x{0d05}-\x{0d0c}\x{0d0e}-\x{0d10}\x{0d12}-\x{0d3a}\x{0d3d}\x{0d4e}\x{0d60}\x{0d61}\x{0d7a}-\x{0d7f}\x{0d85}-\x{0d96}\x{0d9a}-\x{0db1}\x{0db3}-\x{0dbb}\x{0dbd}\x{0dc0}-\x{0dc6}\x{0e01}-\x{0e30}\x{0e32}\x{0e33}\x{0e40}-\x{0e46}\x{0e81}\x{0e82}\x{0e84}\x{0e87}\x{0e88}\x{0e8a}\x{0e8d}\x{0e94}-\x{0e97}\x{0e99}-\x{0e9f}\x{0ea1}-\x{0ea3}\x{0ea5}\x{0ea7}\x{0eaa}\x{0eab}\x{0ead}-\x{0eb0}\x{0eb2}\x{0eb3}\x{0ebd}\x{0ec0}-\x{0ec4}\x{0ec6}\x{0edc}-\x{0edf}\x{0f00}\x{0f40}-\x{0f47}\x{0f49}-\x{0f6c}\x{0f88}-\x{0f8c}\x{1000}-\x{102a}\x{103f}\x{1050}-\x{1055}\x{105a}-\x{105d}\x{1061}\x{1065}\x{1066}\x{106e}-\x{1070}\x{1075}-\x{1081}\x{108e}\x{10a0}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{10fa}\x{10fc}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1380}-\x{138f}\x{13a0}-\x{13f4}\x{1401}-\x{166c}\x{166f}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16ea}\x{16ee}-\x{16f0}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17d7}\x{17dc}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191c}\x{1950}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19c1}-\x{19c7}\x{1a00}-\x{1a16}\x{1a20}-\x{1a54}\x{1aa7}\x{1b05}-\x{1b33}\x{1b45}-\x{1b4b}\x{1b83}-\x{1ba0}\x{1bae}\x{1baf}\x{1bba}-\x{1be5}\x{1c00}-\x{1c23}\x{1c4d}-\x{1c4f}\x{1c5a}-\x{1c7d}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf1}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{2160}-\x{2188}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{2e2f}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{31a0}-\x{31ba}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}\x{4e00}-\x{9fcc}\x{a000}-\x{a48c}\x{a4d0}-\x{a4fd}\x{a500}-\x{a60c}\x{a610}-\x{a61f}\x{a62a}\x{a62b}\x{a640}-\x{a66e}\x{a67f}-\x{a697}\x{a6a0}-\x{a6ef}\x{a717}-\x{a71f}\x{a722}-\x{a788}\x{a78b}-\x{a78e}\x{a790}-\x{a793}\x{a7a0}-\x{a7aa}\x{a7f8}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a822}\x{a840}-\x{a873}\x{a882}-\x{a8b3}\x{a8f2}-\x{a8f7}\x{a8fb}\x{a90a}-\x{a925}\x{a930}-\x{a946}\x{a960}-\x{a97c}\x{a984}-\x{a9b2}\x{a9cf}\x{aa00}-\x{aa28}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa60}-\x{aa76}\x{aa7a}\x{aa80}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aadd}\x{aae0}-\x{aaea}\x{aaf2}-\x{aaf4}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{abc0}-\x{abe2}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{f900}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb36}\x{fb38}-\x{fb3c}\x{fb3e}\x{fb40}\x{fb41}\x{fb43}\x{fb44}\x{fb46}-\x{fbb1}\x{fbd3}-\x{fd3d}\x{fd50}-\x{fd8f}\x{fd92}-\x{fdc7}\x{fdf0}-\x{fdfb}\x{fe70}-\x{fe74}\x{fe76}-\x{fefc}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}0-9\x{0300}-\x{036f}\x{0483}-\x{0487}\x{0591}-\x{05bd}\x{05bf}\x{05c1}\x{05c2}\x{05c4}\x{05c5}\x{05c7}\x{0610}-\x{061a}\x{064b}-\x{0669}\x{0670}\x{06d6}-\x{06dc}\x{06df}-\x{06e4}\x{06e7}\x{06e8}\x{06ea}-\x{06ed}\x{06f0}-\x{06f9}\x{0711}\x{0730}-\x{074a}\x{07a6}-\x{07b0}\x{07c0}-\x{07c9}\x{07eb}-\x{07f3}\x{0816}-\x{0819}\x{081b}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082d}\x{0859}-\x{085b}\x{08e4}-\x{08fe}\x{0900}-\x{0903}\x{093a}-\x{093c}\x{093e}-\x{094f}\x{0951}-\x{0957}\x{0962}\x{0963}\x{0966}-\x{096f}\x{0981}-\x{0983}\x{09bc}\x{09be}-\x{09c4}\x{09c7}\x{09c8}\x{09cb}-\x{09cd}\x{09d7}\x{09e2}\x{09e3}\x{09e6}-\x{09ef}\x{0a01}-\x{0a03}\x{0a3c}\x{0a3e}-\x{0a42}\x{0a47}\x{0a48}\x{0a4b}-\x{0a4d}\x{0a51}\x{0a66}-\x{0a71}\x{0a75}\x{0a81}-\x{0a83}\x{0abc}\x{0abe}-\x{0ac5}\x{0ac7}-\x{0ac9}\x{0acb}-\x{0acd}\x{0ae2}\x{0ae3}\x{0ae6}-\x{0aef}\x{0b01}-\x{0b03}\x{0b3c}\x{0b3e}-\x{0b44}\x{0b47}\x{0b48}\x{0b4b}-\x{0b4d}\x{0b56}\x{0b57}\x{0b62}\x{0b63}\x{0b66}-\x{0b6f}\x{0b82}\x{0bbe}-\x{0bc2}\x{0bc6}-\x{0bc8}\x{0bca}-\x{0bcd}\x{0bd7}\x{0be6}-\x{0bef}\x{0c01}-\x{0c03}\x{0c3e}-\x{0c44}\x{0c46}-\x{0c48}\x{0c4a}-\x{0c4d}\x{0c55}\x{0c56}\x{0c62}\x{0c63}\x{0c66}-\x{0c6f}\x{0c82}\x{0c83}\x{0cbc}\x{0cbe}-\x{0cc4}\x{0cc6}-\x{0cc8}\x{0cca}-\x{0ccd}\x{0cd5}\x{0cd6}\x{0ce2}\x{0ce3}\x{0ce6}-\x{0cef}\x{0d02}\x{0d03}\x{0d3e}-\x{0d44}\x{0d46}-\x{0d48}\x{0d4a}-\x{0d4d}\x{0d57}\x{0d62}\x{0d63}\x{0d66}-\x{0d6f}\x{0d82}\x{0d83}\x{0dca}\x{0dcf}-\x{0dd4}\x{0dd6}\x{0dd8}-\x{0ddf}\x{0df2}\x{0df3}\x{0e31}\x{0e34}-\x{0e3a}\x{0e47}-\x{0e4e}\x{0e50}-\x{0e59}\x{0eb1}\x{0eb4}-\x{0eb9}\x{0ebb}\x{0ebc}\x{0ec8}-\x{0ecd}\x{0ed0}-\x{0ed9}\x{0f18}\x{0f19}\x{0f20}-\x{0f29}\x{0f35}\x{0f37}\x{0f39}\x{0f3e}\x{0f3f}\x{0f71}-\x{0f84}\x{0f86}\x{0f87}\x{0f8d}-\x{0f97}\x{0f99}-\x{0fbc}\x{0fc6}\x{102b}-\x{103e}\x{1040}-\x{1049}\x{1056}-\x{1059}\x{105e}-\x{1060}\x{1062}-\x{1064}\x{1067}-\x{106d}\x{1071}-\x{1074}\x{1082}-\x{108d}\x{108f}-\x{109d}\x{135d}-\x{135f}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17d3}\x{17dd}\x{17e0}-\x{17e9}\x{180b}-\x{180d}\x{1810}-\x{1819}\x{18a9}\x{1920}-\x{192b}\x{1930}-\x{193b}\x{1946}-\x{194f}\x{19b0}-\x{19c0}\x{19c8}\x{19c9}\x{19d0}-\x{19d9}\x{1a17}-\x{1a1b}\x{1a55}-\x{1a5e}\x{1a60}-\x{1a7c}\x{1a7f}-\x{1a89}\x{1a90}-\x{1a99}\x{1b00}-\x{1b04}\x{1b34}-\x{1b44}\x{1b50}-\x{1b59}\x{1b6b}-\x{1b73}\x{1b80}-\x{1b82}\x{1ba1}-\x{1bad}\x{1bb0}-\x{1bb9}\x{1be6}-\x{1bf3}\x{1c24}-\x{1c37}\x{1c40}-\x{1c49}\x{1c50}-\x{1c59}\x{1cd0}-\x{1cd2}\x{1cd4}-\x{1ce8}\x{1ced}\x{1cf2}-\x{1cf4}\x{1dc0}-\x{1de6}\x{1dfc}-\x{1dff}\x{200c}\x{200d}\x{203f}\x{2040}\x{2054}\x{20d0}-\x{20dc}\x{20e1}\x{20e5}-\x{20f0}\x{2cef}-\x{2cf1}\x{2d7f}\x{2de0}-\x{2dff}\x{302a}-\x{302f}\x{3099}\x{309a}\x{a620}-\x{a629}\x{a66f}\x{a674}-\x{a67d}\x{a69f}\x{a6f0}\x{a6f1}\x{a802}\x{a806}\x{a80b}\x{a823}-\x{a827}\x{a880}\x{a881}\x{a8b4}-\x{a8c4}\x{a8d0}-\x{a8d9}\x{a8e0}-\x{a8f1}\x{a900}-\x{a909}\x{a926}-\x{a92d}\x{a947}-\x{a953}\x{a980}-\x{a983}\x{a9b3}-\x{a9c0}\x{a9d0}-\x{a9d9}\x{aa29}-\x{aa36}\x{aa43}\x{aa4c}\x{aa4d}\x{aa50}-\x{aa59}\x{aa7b}\x{aab0}\x{aab2}-\x{aab4}\x{aab7}\x{aab8}\x{aabe}\x{aabf}\x{aac1}\x{aaeb}-\x{aaef}\x{aaf5}\x{aaf6}\x{abe3}-\x{abea}\x{abec}\x{abed}\x{abf0}-\x{abf9}\x{fb1e}\x{fe00}-\x{fe0f}\x{fe20}-\x{fe26}\x{fe33}\x{fe34}\x{fe4d}-\x{fe4f}\x{ff10}-\x{ff19}\x{ff3f}]*\b';
/**
* Full list of JavaScript reserved words.
* Will be loaded from /data/js/keywords_reserved.txt.
*
* @see https://mathiasbynens.be/notes/reserved-keywords
*
* @var string[]
*/
protected $keywordsReserved = array();
/**
* List of JavaScript reserved words that accept a <variable, value, ...>
* after them. Some end of lines are not the end of a statement, like with
* these keywords.
*
* E.g.: we shouldn't insert a ; after this else
* else
* console.log('this is quite fine')
*
* Will be loaded from /data/js/keywords_before.txt
*
* @var string[]
*/
protected $keywordsBefore = array();
/**
* List of JavaScript reserved words that accept a <variable, value, ...>
* before them. Some end of lines are not the end of a statement, like when
* continued by one of these keywords on the newline.
*
* E.g.: we shouldn't insert a ; before this instanceof
* variable
* instanceof String
*
* Will be loaded from /data/js/keywords_after.txt
*
* @var string[]
*/
protected $keywordsAfter = array();
/**
* List of all JavaScript operators.
*
* Will be loaded from /data/js/operators.txt
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
*
* @var string[]
*/
protected $operators = array();
/**
* List of JavaScript operators that accept a <variable, value, ...> after
* them. Some end of lines are not the end of a statement, like with these
* operators.
*
* Note: Most operators are fine, we've only removed ++ and --.
* ++ & -- have to be joined with the value they're in-/decrementing.
*
* Will be loaded from /data/js/operators_before.txt
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
*
* @var string[]
*/
protected $operatorsBefore = array();
/**
* List of JavaScript operators that accept a <variable, value, ...> before
* them. Some end of lines are not the end of a statement, like when
* continued by one of these operators on the newline.
*
* Note: Most operators are fine, we've only removed ), ], ++, --, ! and ~.
* There can't be a newline separating ! or ~ and whatever it is negating.
* ++ & -- have to be joined with the value they're in-/decrementing.
* ) & ] are "special" in that they have lots or usecases. () for example
* is used for function calls, for grouping, in if () and for (), ...
*
* Will be loaded from /data/js/operators_after.txt
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
*
* @var string[]
*/
protected $operatorsAfter = array();
/**
* {@inheritdoc}
*/
public function __construct()
{
call_user_func_array(array('parent', '__construct'), func_get_args());
$dataDir = __DIR__.'/../data/js/';
$options = FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES;
$this->keywordsReserved = file($dataDir.'keywords_reserved.txt', $options);
$this->keywordsBefore = file($dataDir.'keywords_before.txt', $options);
$this->keywordsAfter = file($dataDir.'keywords_after.txt', $options);
$this->operators = file($dataDir.'operators.txt', $options);
$this->operatorsBefore = file($dataDir.'operators_before.txt', $options);
$this->operatorsAfter = file($dataDir.'operators_after.txt', $options);
}
/**
* Minify the data.
* Perform JS optimizations.
*
* @param string[optional] $path Path to write the data to
*
* @return string The minified data
*/
public function execute($path = null)
{
$content = '';
/*
* Let's first take out strings, comments and regular expressions.
* All of these can contain JS code-like characters, and we should make
* sure any further magic ignores anything inside of these.
*
* Consider this example, where we should not strip any whitespace:
* var str = "a test";
*
* Comments will be removed altogether, strings and regular expressions
* will be replaced by placeholder text, which we'll restore later.
*/
$this->extractStrings('\'"`');
$this->stripComments();
$this->extractRegex();
// loop files
foreach ($this->data as $source => $js) {
// take out strings, comments & regex (for which we've registered
// the regexes just a few lines earlier)
$js = $this->replace($js);
$js = $this->propertyNotation($js);
$js = $this->shortenBools($js);
$js = $this->stripWhitespace($js);
// combine js: separating the scripts by a ;
$content .= $js.";";
}
// clean up leftover `;`s from the combination of multiple scripts
$content = ltrim($content, ';');
$content = (string) substr($content, 0, -1);
/*
* Earlier, we extracted strings & regular expressions and replaced them
* with placeholder text. This will restore them.
*/
$content = $this->restoreExtractedData($content);
return $content;
}
/**
* Strip comments from source code.
*/
protected function stripComments()
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$callback = function ($match) use ($minifier) {
$count = count($minifier->extracted);
$placeholder = '/*'.$count.'*/';
$minifier->extracted[$placeholder] = $match[0];
return $placeholder;
};
// multi-line comments
$this->registerPattern('/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s', $callback);
$this->registerPattern('/\/\*.*?\*\//s', '');
// single-line comments
$this->registerPattern('/\/\/.*$/m', '');
}
/**
* JS can have /-delimited regular expressions, like: /ab+c/.match(string).
*
* The content inside the regex can contain characters that may be confused
* for JS code: e.g. it could contain whitespace it needs to match & we
* don't want to strip whitespace in there.
*
* The regex can be pretty simple: we don't have to care about comments,
* (which also use slashes) because stripComments() will have stripped those
* already.
*
* This method will replace all string content with simple REGEX#
* placeholder text, so we've rid all regular expressions from characters
* that may be misinterpreted. Original regex content will be saved in
* $this->extracted and after doing all other minifying, we can restore the
* original content via restoreRegex()
*/
protected function extractRegex()
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$callback = function ($match) use ($minifier) {
$count = count($minifier->extracted);
$placeholder = '"'.$count.'"';
$minifier->extracted[$placeholder] = $match[0];
return $placeholder;
};
// match all chars except `/` and `\`
// `\` is allowed though, along with whatever char follows (which is the
// one being escaped)
// this should allow all chars, except for an unescaped `/` (= the one
// closing the regex)
// then also ignore bare `/` inside `[]`, where they don't need to be
// escaped: anything inside `[]` can be ignored safely
$pattern = '\\/(?!\*)(?:[^\\[\\/\\\\\n\r]++|(?:\\\\.)++|(?:\\[(?:[^\\]\\\\\n\r]++|(?:\\\\.)++)++\\])++)++\\/[gimuy]*';
// a regular expression can only be followed by a few operators or some
// of the RegExp methods (a `\` followed by a variable or value is
// likely part of a division, not a regex)
$keywords = array('do', 'in', 'new', 'else', 'throw', 'yield', 'delete', 'return', 'typeof');
$before = '([=:,;\+\-\*\/\}\(\{\[&\|!]|^|'.implode('|', $keywords).')\s*';
$propertiesAndMethods = array(
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Properties_2
'constructor',
'flags',
'global',
'ignoreCase',
'multiline',
'source',
'sticky',
'unicode',
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Methods_2
'compile(',
'exec(',
'test(',
'toSource(',
'toString(',
);
$delimiters = array_fill(0, count($propertiesAndMethods), '/');
$propertiesAndMethods = array_map('preg_quote', $propertiesAndMethods, $delimiters);
$after = '(?=\s*([\.,;\)\}&\|+]|\/\/|$|\.('.implode('|', $propertiesAndMethods).')))';
$this->registerPattern('/'.$before.'\K'.$pattern.$after.'/', $callback);
// regular expressions following a `)` are rather annoying to detect...
// quite often, `/` after `)` is a division operator & if it happens to
// be followed by another one (or a comment), it is likely to be
// confused for a regular expression
// however, it's perfectly possible for a regex to follow a `)`: after
// a single-line `if()`, `while()`, ... statement, for example
// since, when they occur like that, they're always the start of a
// statement, there's only a limited amount of ways they can be useful:
// by calling the regex methods directly
// if a regex following `)` is not followed by `.<property or method>`,
// it's quite likely not a regex
$before = '\)\s*';
$after = '(?=\s*\.('.implode('|', $propertiesAndMethods).'))';
$this->registerPattern('/'.$before.'\K'.$pattern.$after.'/', $callback);
// 1 more edge case: a regex can be followed by a lot more operators or
// keywords if there's a newline (ASI) in between, where the operator
// actually starts a new statement
// (https://github.com/matthiasmullie/minify/issues/56)
$operators = $this->getOperatorsForRegex($this->operatorsBefore, '/');
$operators += $this->getOperatorsForRegex($this->keywordsReserved, '/');
$after = '(?=\s*\n\s*('.implode('|', $operators).'))';
$this->registerPattern('/'.$pattern.$after.'/', $callback);
}
/**
* Strip whitespace.
*
* We won't strip *all* whitespace, but as much as possible. The thing that
* we'll preserve are newlines we're unsure about.
* JavaScript doesn't require statements to be terminated with a semicolon.
* It will automatically fix missing semicolons with ASI (automatic semi-
* colon insertion) at the end of line causing errors (without semicolon.)
*
* Because it's sometimes hard to tell if a newline is part of a statement
* that should be terminated or not, we'll just leave some of them alone.
*
* @param string $content The content to strip the whitespace for
*
* @return string
*/
protected function stripWhitespace($content)
{
// uniform line endings, make them all line feed
$content = str_replace(array("\r\n", "\r"), "\n", $content);
// collapse all non-line feed whitespace into a single space
$content = preg_replace('/[^\S\n]+/', ' ', $content);
// strip leading & trailing whitespace
$content = str_replace(array(" \n", "\n "), "\n", $content);
// collapse consecutive line feeds into just 1
$content = preg_replace('/\n+/', "\n", $content);
$operatorsBefore = $this->getOperatorsForRegex($this->operatorsBefore, '/');
$operatorsAfter = $this->getOperatorsForRegex($this->operatorsAfter, '/');
$operators = $this->getOperatorsForRegex($this->operators, '/');
$keywordsBefore = $this->getKeywordsForRegex($this->keywordsBefore, '/');
$keywordsAfter = $this->getKeywordsForRegex($this->keywordsAfter, '/');
// strip whitespace that ends in (or next line begin with) an operator
// that allows statements to be broken up over multiple lines
unset($operatorsBefore['+'], $operatorsBefore['-'], $operatorsAfter['+'], $operatorsAfter['-']);
$content = preg_replace(
array(
'/('.implode('|', $operatorsBefore).')\s+/',
'/\s+('.implode('|', $operatorsAfter).')/',
),
'\\1',
$content
);
// make sure + and - can't be mistaken for, or joined into ++ and --
$content = preg_replace(
array(
'/(?<![\+\-])\s*([\+\-])(?![\+\-])/',
'/(?<![\+\-])([\+\-])\s*(?![\+\-])/',
),
'\\1',
$content
);
// collapse whitespace around reserved words into single space
$content = preg_replace('/(^|[;\}\s])\K('.implode('|', $keywordsBefore).')\s+/', '\\2 ', $content);
$content = preg_replace('/\s+('.implode('|', $keywordsAfter).')(?=([;\{\s]|$))/', ' \\1', $content);
/*
* We didn't strip whitespace after a couple of operators because they
* could be used in different contexts and we can't be sure it's ok to
* strip the newlines. However, we can safely strip any non-line feed
* whitespace that follows them.
*/
$operatorsDiffBefore = array_diff($operators, $operatorsBefore);
$operatorsDiffAfter = array_diff($operators, $operatorsAfter);
$content = preg_replace('/('.implode('|', $operatorsDiffBefore).')[^\S\n]+/', '\\1', $content);
$content = preg_replace('/[^\S\n]+('.implode('|', $operatorsDiffAfter).')/', '\\1', $content);
/*
* Whitespace after `return` can be omitted in a few occasions
* (such as when followed by a string or regex)
* Same for whitespace in between `)` and `{`, or between `{` and some
* keywords.
*/
$content = preg_replace('/\breturn\s+(["\'\/\+\-])/', 'return$1', $content);
$content = preg_replace('/\)\s+\{/', '){', $content);
$content = preg_replace('/}\n(else|catch|finally)\b/', '}$1', $content);
/*
* Get rid of double semicolons, except where they can be used like:
* "for(v=1,_=b;;)", "for(v=1;;v++)" or "for(;;ja||(ja=true))".
* I'll safeguard these double semicolons inside for-loops by
* temporarily replacing them with an invalid condition: they won't have
* a double semicolon and will be easy to spot to restore afterwards.
*/
$content = preg_replace('/\bfor\(([^;]*);;([^;]*)\)/', 'for(\\1;-;\\2)', $content);
$content = preg_replace('/;+/', ';', $content);
$content = preg_replace('/\bfor\(([^;]*);-;([^;]*)\)/', 'for(\\1;;\\2)', $content);
/*
* Next, we'll be removing all semicolons where ASI kicks in.
* for-loops however, can have an empty body (ending in only a
* semicolon), like: `for(i=1;i<3;i++);`, of `for(i in list);`
* Here, nothing happens during the loop; it's just used to keep
* increasing `i`. With that ; omitted, the next line would be expected
* to be the for-loop's body... Same goes for while loops.
* I'm going to double that semicolon (if any) so after the next line,
* which strips semicolons here & there, we're still left with this one.
*/
$content = preg_replace('/(for\([^;\{]*;[^;\{]*;[^;\{]*\));(\}|$)/s', '\\1;;\\2', $content);
$content = preg_replace('/(for\([^;\{]+\s+in\s+[^;\{]+\));(\}|$)/s', '\\1;;\\2', $content);
/*
* Below will also keep `;` after a `do{}while();` along with `while();`
* While these could be stripped after do-while, detecting this
* distinction is cumbersome, so I'll play it safe and make sure `;`
* after any kind of `while` is kept.
*/
$content = preg_replace('/(while\([^;\{]+\));(\}|$)/s', '\\1;;\\2', $content);
/*
* We also can't strip empty else-statements. Even though they're
* useless and probably shouldn't be in the code in the first place, we
* shouldn't be stripping the `;` that follows it as it breaks the code.
* We can just remove those useless else-statements completely.
*
* @see https://github.com/matthiasmullie/minify/issues/91
*/
$content = preg_replace('/else;/s', '', $content);
/*
* We also don't really want to terminate statements followed by closing
* curly braces (which we've ignored completely up until now) or end-of-
* script: ASI will kick in here & we're all about minifying.
* Semicolons at beginning of the file don't make any sense either.
*/
$content = preg_replace('/;(\}|$)/s', '\\1', $content);
$content = ltrim($content, ';');
// get rid of remaining whitespace af beginning/end
return trim($content);
}
/**
* We'll strip whitespace around certain operators with regular expressions.
* This will prepare the given array by escaping all characters.
*
* @param string[] $operators
* @param string $delimiter
*
* @return string[]
*/
protected function getOperatorsForRegex(array $operators, $delimiter = '/')
{
// escape operators for use in regex
$delimiters = array_fill(0, count($operators), $delimiter);
$escaped = array_map('preg_quote', $operators, $delimiters);
$operators = array_combine($operators, $escaped);
// ignore + & - for now, they'll get special treatment
unset($operators['+'], $operators['-']);
// dot can not just immediately follow a number; it can be confused for
// decimal point, or calling a method on it, e.g. 42 .toString()
$operators['.'] = '(?<![0-9]\s)\.';
// don't confuse = with other assignment shortcuts (e.g. +=)
$chars = preg_quote('+-*\=<>%&|', $delimiter);
$operators['='] = '(?<!['.$chars.'])\=';
return $operators;
}
/**
* We'll strip whitespace around certain keywords with regular expressions.
* This will prepare the given array by escaping all characters.
*
* @param string[] $keywords
* @param string $delimiter
*
* @return string[]
*/
protected function getKeywordsForRegex(array $keywords, $delimiter = '/')
{
// escape keywords for use in regex
$delimiter = array_fill(0, count($keywords), $delimiter);
$escaped = array_map('preg_quote', $keywords, $delimiter);
// add word boundaries
array_walk($keywords, function ($value) {
return '\b'.$value.'\b';
});
$keywords = array_combine($keywords, $escaped);
return $keywords;
}
/**
* Replaces all occurrences of array['key'] by array.key.
*
* @param string $content
*
* @return string
*/
protected function propertyNotation($content)
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$keywords = $this->keywordsReserved;
$callback = function ($match) use ($minifier, $keywords) {
$property = trim($minifier->extracted[$match[1]], '\'"');
/*
* Check if the property is a reserved keyword. In this context (as
* property of an object literal/array) it shouldn't matter, but IE8
* freaks out with "Expected identifier".
*/
if (in_array($property, $keywords)) {
return $match[0];
}
/*
* See if the property is in a variable-like format (e.g.
* array['key-here'] can't be replaced by array.key-here since '-'
* is not a valid character there.
*/
if (!preg_match('/^'.$minifier::REGEX_VARIABLE.'$/u', $property)) {
return $match[0];
}
return '.'.$property;
};
/*
* Figure out if previous character is a variable name (of the array
* we want to use property notation on) - this is to make sure
* standalone ['value'] arrays aren't confused for keys-of-an-array.
* We can (and only have to) check the last character, because PHP's
* regex implementation doesn't allow unfixed-length look-behind
* assertions.
*/
preg_match('/(\[[^\]]+\])[^\]]*$/', static::REGEX_VARIABLE, $previousChar);
$previousChar = $previousChar[1];
/*
* Make sure word preceding the ['value'] is not a keyword, e.g.
* return['x']. Because -again- PHP's regex implementation doesn't allow
* unfixed-length look-behind assertions, I'm just going to do a lot of
* separate look-behind assertions, one for each keyword.
*/
$keywords = $this->getKeywordsForRegex($keywords);
$keywords = '(?<!'.implode(')(?<!', $keywords).')';
return preg_replace_callback('/(?<='.$previousChar.'|\])'.$keywords.'\[\s*(([\'"])[0-9]+\\2)\s*\]/u', $callback, $content);
}
/**
* Replaces true & false by !0 and !1.
*
* @param string $content
*
* @return string
*/
protected function shortenBools($content)
{
/*
* 'true' or 'false' could be used as property names (which may be
* followed by whitespace) - we must not replace those!
* Since PHP doesn't allow variable-length (to account for the
* whitespace) lookbehind assertions, I need to capture the leading
* character and check if it's a `.`
*/
$callback = function ($match) {
if (trim($match[1]) === '.') {
return $match[0];
}
return $match[1].($match[2] === 'true' ? '!0' : '!1');
};
$content = preg_replace_callback('/(^|.\s*)\b(true|false)\b(?!:)/', $callback, $content);
// for(;;) is exactly the same as while(true), but shorter :)
$content = preg_replace('/\bwhile\(!0\){/', 'for(;;){', $content);
// now make sure we didn't turn any do ... while(true) into do ... for(;;)
preg_match_all('/\bdo\b/', $content, $dos, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
// go backward to make sure positional offsets aren't altered when $content changes
$dos = array_reverse($dos);
foreach ($dos as $do) {
$offsetDo = $do[0][1];
// find all `while` (now `for`) following `do`: one of those must be
// associated with the `do` and be turned back into `while`
preg_match_all('/\bfor\(;;\)/', $content, $whiles, PREG_OFFSET_CAPTURE | PREG_SET_ORDER, $offsetDo);
foreach ($whiles as $while) {
$offsetWhile = $while[0][1];
$open = substr_count($content, '{', $offsetDo, $offsetWhile - $offsetDo);
$close = substr_count($content, '}', $offsetDo, $offsetWhile - $offsetDo);
if ($open === $close) {
// only restore `while` if amount of `{` and `}` are the same;
// otherwise, that `for` isn't associated with this `do`
$content = substr_replace($content, 'while(!0)', $offsetWhile, strlen('for(;;)'));
break;
}
}
}
return $content;
}
}
<?php
/**
* Abstract minifier class
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
namespace FVM\MatthiasMullie\Minify;
use FVM\MatthiasMullie\Minify\Exceptions\IOException;
use Psr\Cache\CacheItemInterface;
/**
* Abstract minifier class.
*
* Please report bugs on https://github.com/matthiasmullie/minify/issues
*
* @package Minify
* @author Matthias Mullie <minify@mullie.eu>
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
* @license MIT License
*/
abstract class Minify
{
/**
* The data to be minified.
*
* @var string[]
*/
protected $data = array();
/**
* Array of patterns to match.
*
* @var string[]
*/
protected $patterns = array();
/**
* This array will hold content of strings and regular expressions that have
* been extracted from the JS source code, so we can reliably match "code",
* without having to worry about potential "code-like" characters inside.
*
* @var string[]
*/
public $extracted = array();
/**
* Init the minify class - optionally, code may be passed along already.
*/
public function __construct(/* $data = null, ... */)
{
// it's possible to add the source through the constructor as well ;)
if (func_num_args()) {
call_user_func_array(array($this, 'add'), func_get_args());
}
}
/**
* Add a file or straight-up code to be minified.
*
* @param string|string[] $data
*
* @return static
*/
public function add($data /* $data = null, ... */)
{
// bogus "usage" of parameter $data: scrutinizer warns this variable is
// not used (we're using func_get_args instead to support overloading),
// but it still needs to be defined because it makes no sense to have
// this function without argument :)
$args = array($data) + func_get_args();
// this method can be overloaded
foreach ($args as $data) {
if (is_array($data)) {
call_user_func_array(array($this, 'add'), $data);
continue;
}
// redefine var
$data = (string) $data;
// load data
$value = $this->load($data);
$key = ($data != $value) ? $data : count($this->data);
// replace CR linefeeds etc.
// @see https://github.com/matthiasmullie/minify/pull/139
$value = str_replace(array("\r\n", "\r"), "\n", $value);
// store data
$this->data[$key] = $value;
}
return $this;
}
/**
* Add a file to be minified.
*
* @param string|string[] $data
*
* @return static
*
* @throws IOException
*/
public function addFile($data /* $data = null, ... */)
{
// bogus "usage" of parameter $data: scrutinizer warns this variable is
// not used (we're using func_get_args instead to support overloading),
// but it still needs to be defined because it makes no sense to have
// this function without argument :)
$args = array($data) + func_get_args();
// this method can be overloaded
foreach ($args as $path) {
if (is_array($path)) {
call_user_func_array(array($this, 'addFile'), $path);
continue;
}
// redefine var
$path = (string) $path;
// check if we can read the file
if (!$this->canImportFile($path)) {
throw new IOException('The file "'.$path.'" could not be opened for reading. Check if PHP has enough permissions.');
}
$this->add($path);
}
return $this;
}
/**
* Minify the data & (optionally) saves it to a file.
*
* @param string[optional] $path Path to write the data to
*
* @return string The minified data
*/
public function minify($path = null)
{
$content = $this->execute($path);
// save to path
if ($path !== null) {
$this->save($content, $path);
}
return $content;
}
/**
* Minify & gzip the data & (optionally) saves it to a file.
*
* @param string[optional] $path Path to write the data to
* @param int[optional] $level Compression level, from 0 to 9
*
* @return string The minified & gzipped data
*/
public function gzip($path = null, $level = 9)
{
$content = $this->execute($path);
$content = gzencode($content, $level, FORCE_GZIP);
// save to path
if ($path !== null) {
$this->save($content, $path);
}
return $content;
}
/**
* Minify the data & write it to a CacheItemInterface object.
*
* @param CacheItemInterface $item Cache item to write the data to
*
* @return CacheItemInterface Cache item with the minifier data
*/
public function cache(CacheItemInterface $item)
{
$content = $this->execute();
$item->set($content);
return $item;
}
/**
* Minify the data.
*
* @param string[optional] $path Path to write the data to
*
* @return string The minified data
*/
abstract public function execute($path = null);
/**
* Load data.
*
* @param string $data Either a path to a file or the content itself
*
* @return string
*/
protected function load($data)
{
// check if the data is a file
if ($this->canImportFile($data)) {
$data = file_get_contents($data);
// strip BOM, if any
if (substr($data, 0, 3) == "\xef\xbb\xbf") {
$data = substr($data, 3);
}
}
return $data;
}
/**
* Save to file.
*
* @param string $content The minified data
* @param string $path The path to save the minified data to
*
* @throws IOException
*/
protected function save($content, $path)
{
$handler = $this->openFileForWriting($path);
$this->writeToFile($handler, $content);
@fclose($handler);
}
/**
* Register a pattern to execute against the source content.
*
* @param string $pattern PCRE pattern
* @param string|callable $replacement Replacement value for matched pattern
*/
protected function registerPattern($pattern, $replacement = '')
{
// study the pattern, we'll execute it more than once
$pattern .= 'S';
$this->patterns[] = array($pattern, $replacement);
}
/**
* We can't "just" run some regular expressions against JavaScript: it's a
* complex language. E.g. having an occurrence of // xyz would be a comment,
* unless it's used within a string. Of you could have something that looks
* like a 'string', but inside a comment.
* The only way to accurately replace these pieces is to traverse the JS one
* character at a time and try to find whatever starts first.
*
* @param string $content The content to replace patterns in
*
* @return string The (manipulated) content
*/
protected function replace($content)
{
$processed = '';
$positions = array_fill(0, count($this->patterns), -1);
$matches = array();
while ($content) {
// find first match for all patterns
foreach ($this->patterns as $i => $pattern) {
list($pattern, $replacement) = $pattern;
// we can safely ignore patterns for positions we've unset earlier,
// because we know these won't show up anymore
if (array_key_exists($i, $positions) == false) {
continue;
}
// no need to re-run matches that are still in the part of the
// content that hasn't been processed
if ($positions[$i] >= 0) {
continue;
}
$match = null;
if (preg_match($pattern, $content, $match, PREG_OFFSET_CAPTURE)) {
$matches[$i] = $match;
// we'll store the match position as well; that way, we
// don't have to redo all preg_matches after changing only
// the first (we'll still know where those others are)
$positions[$i] = $match[0][1];
} else {
// if the pattern couldn't be matched, there's no point in
// executing it again in later runs on this same content;
// ignore this one until we reach end of content
unset($matches[$i], $positions[$i]);
}
}
// no more matches to find: everything's been processed, break out
if (!$matches) {
$processed .= $content;
break;
}
// see which of the patterns actually found the first thing (we'll
// only want to execute that one, since we're unsure if what the
// other found was not inside what the first found)
$discardLength = min($positions);
$firstPattern = array_search($discardLength, $positions);
$match = $matches[$firstPattern][0][0];
// execute the pattern that matches earliest in the content string
list($pattern, $replacement) = $this->patterns[$firstPattern];
$replacement = $this->replacePattern($pattern, $replacement, $content);
// figure out which part of the string was unmatched; that's the
// part we'll execute the patterns on again next
$content = (string) substr($content, $discardLength);
$unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
// move the replaced part to $processed and prepare $content to
// again match batch of patterns against
$processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
$content = $unmatched;
// first match has been replaced & that content is to be left alone,
// the next matches will start after this replacement, so we should
// fix their offsets
foreach ($positions as $i => $position) {
$positions[$i] -= $discardLength + strlen($match);
}
}
return $processed;
}
/**
* This is where a pattern is matched against $content and the matches
* are replaced by their respective value.
* This function will be called plenty of times, where $content will always
* move up 1 character.
*
* @param string $pattern Pattern to match
* @param string|callable $replacement Replacement value
* @param string $content Content to match pattern against
*
* @return string
*/
protected function replacePattern($pattern, $replacement, $content)
{
if (is_callable($replacement)) {
return preg_replace_callback($pattern, $replacement, $content, 1, $count);
} else {
return preg_replace($pattern, $replacement, $content, 1, $count);
}
}
/**
* Strings are a pattern we need to match, in order to ignore potential
* code-like content inside them, but we just want all of the string
* content to remain untouched.
*
* This method will replace all string content with simple STRING#
* placeholder text, so we've rid all strings from characters that may be
* misinterpreted. Original string content will be saved in $this->extracted
* and after doing all other minifying, we can restore the original content
* via restoreStrings().
*
* @param string[optional] $chars
* @param string[optional] $placeholderPrefix
*/
protected function extractStrings($chars = '\'"', $placeholderPrefix = '')
{
// PHP only supports $this inside anonymous functions since 5.4
$minifier = $this;
$callback = function ($match) use ($minifier, $placeholderPrefix) {
// check the second index here, because the first always contains a quote
if ($match[2] === '') {
/*
* Empty strings need no placeholder; they can't be confused for
* anything else anyway.
* But we still needed to match them, for the extraction routine
* to skip over this particular string.
*/
return $match[0];
}
$count = count($minifier->extracted);
$placeholder = $match[1].$placeholderPrefix.$count.$match[1];
$minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
return $placeholder;
};
/*
* The \\ messiness explained:
* * Don't count ' or " as end-of-string if it's escaped (has backslash
* in front of it)
* * Unless... that backslash itself is escaped (another leading slash),
* in which case it's no longer escaping the ' or "
* * So there can be either no backslash, or an even number
* * multiply all of that times 4, to account for the escaping that has
* to be done to pass the backslash into the PHP string without it being
* considered as escape-char (times 2) and to get it in the regex,
* escaped (times 2)
*/
$this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
}
/**
* This method will restore all extracted data (strings, regexes) that were
* replaced with placeholder text in extract*(). The original content was
* saved in $this->extracted.
*
* @param string $content
*
* @return string
*/
protected function restoreExtractedData($content)
{
if (!$this->extracted) {
// nothing was extracted, nothing to restore
return $content;
}
$content = strtr($content, $this->extracted);
$this->extracted = array();
return $content;
}
/**
* Check if the path is a regular file and can be read.
*
* @param string $path
*
* @return bool
*/
protected function canImportFile($path)
{
$parsed = parse_url($path);
if (
// file is elsewhere
isset($parsed['host']) ||
// file responds to queries (may change, or need to bypass cache)
isset($parsed['query'])
) {
return false;
}
return strlen($path) < PHP_MAXPATHLEN && @is_file($path) && is_readable($path);
}
/**
* Attempts to open file specified by $path for writing.
*
* @param string $path The path to the file
*
* @return resource Specifier for the target file
*
* @throws IOException
*/
protected function openFileForWriting($path)
{
if (($handler = @fopen($path, 'w')) === false) {
throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
}
return $handler;
}
/**
* Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
*
* @param resource $handler The resource to write to
* @param string $content The content to write
* @param string $path The path to the file (for exception printing only)
*
* @throws IOException
*/
protected function writeToFile($handler, $content, $path = '')
{
if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) {
throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
}
}
}
<?php
namespace FVM\MatthiasMullie\PathConverter;
/**
* Convert paths relative from 1 file to another.
*
* E.g.
* ../../images/icon.jpg relative to /css/imports/icons.css
* becomes
* ../images/icon.jpg relative to /css/minified.css
*
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
*
* @author Matthias Mullie <pathconverter@mullie.eu>
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
* @license MIT License
*/
class Converter implements ConverterInterface
{
/**
* @var string
*/
protected $from;
/**
* @var string
*/
protected $to;
/**
* @param string $from The original base path (directory, not file!)
* @param string $to The new base path (directory, not file!)
* @param string $root Root directory (defaults to `getcwd`)
*/
public function __construct($from, $to, $root = '')
{
$shared = $this->shared($from, $to);
if ($shared === '') {
// when both paths have nothing in common, one of them is probably
// absolute while the other is relative
$root = $root ?: getcwd();
$from = strpos($from, $root) === 0 ? $from : preg_replace('/\/+/', '/', $root.'/'.$from);
$to = strpos($to, $root) === 0 ? $to : preg_replace('/\/+/', '/', $root.'/'.$to);
// or traveling the tree via `..`
// attempt to resolve path, or assume it's fine if it doesn't exist
$from = @realpath($from) ?: $from;
$to = @realpath($to) ?: $to;
}
$from = $this->dirname($from);
$to = $this->dirname($to);
$from = $this->normalize($from);
$to = $this->normalize($to);
$this->from = $from;
$this->to = $to;
}
/**
* Normalize path.
*
* @param string $path
*
* @return string
*/
protected function normalize($path)
{
// deal with different operating systems' directory structure
$path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '/');
/*
* Example:
* /home/forkcms/frontend/cache/compiled_templates/../../core/layout/css/../images/img.gif
* to
* /home/forkcms/frontend/core/layout/images/img.gif
*/
do {
$path = preg_replace('/[^\/]+(?<!\.\.)\/\.\.\//', '', $path, -1, $count);
} while ($count);
return $path;
}
/**
* Figure out the shared path of 2 locations.
*
* Example:
* /home/forkcms/frontend/core/layout/images/img.gif
* and
* /home/forkcms/frontend/cache/minified_css
* share
* /home/forkcms/frontend
*
* @param string $path1
* @param string $path2
*
* @return string
*/
protected function shared($path1, $path2)
{
// $path could theoretically be empty (e.g. no path is given), in which
// case it shouldn't expand to array(''), which would compare to one's
// root /
$path1 = $path1 ? explode('/', $path1) : array();
$path2 = $path2 ? explode('/', $path2) : array();
$shared = array();
// compare paths & strip identical ancestors
foreach ($path1 as $i => $chunk) {
if (isset($path2[$i]) && $path1[$i] == $path2[$i]) {
$shared[] = $chunk;
} else {
break;
}
}
return implode('/', $shared);
}
/**
* Convert paths relative from 1 file to another.
*
* E.g.
* ../images/img.gif relative to /home/forkcms/frontend/core/layout/css
* should become:
* ../../core/layout/images/img.gif relative to
* /home/forkcms/frontend/cache/minified_css
*
* @param string $path The relative path that needs to be converted
*
* @return string The new relative path
*/
public function convert($path)
{
// quit early if conversion makes no sense
if ($this->from === $this->to) {
return $path;
}
$path = $this->normalize($path);
// if we're not dealing with a relative path, just return absolute
if (strpos($path, '/') === 0) {
return $path;
}
// normalize paths
$path = $this->normalize($this->from.'/'.$path);
// strip shared ancestor paths
$shared = $this->shared($path, $this->to);
$path = mb_substr($path, mb_strlen($shared));
$to = mb_substr($this->to, mb_strlen($shared));
// add .. for every directory that needs to be traversed to new path
$to = str_repeat('../', count(array_filter(explode('/', $to))));
return $to.ltrim($path, '/');
}
/**
* Attempt to get the directory name from a path.
*
* @param string $path
*
* @return string
*/
protected function dirname($path)
{
if (@is_file($path)) {
return dirname($path);
}
if (@is_dir($path)) {
return rtrim($path, '/');
}
// no known file/dir, start making assumptions
// ends in / = dir
if (mb_substr($path, -1) === '/') {
return rtrim($path, '/');
}
// has a dot in the name, likely a file
if (preg_match('/.*\..*$/', basename($path)) !== 0) {
return dirname($path);
}
// you're on your own here!
return $path;
}
}
<?php
namespace FVM\MatthiasMullie\PathConverter;
/**
* Convert file paths.
*
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
*
* @author Matthias Mullie <pathconverter@mullie.eu>
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
* @license MIT License
*/
interface ConverterInterface
{
/**
* Convert file paths.
*
* @param string $path The path to be converted
*
* @return string The new path
*/
public function convert($path);
}
<?php
namespace FVM\MatthiasMullie\PathConverter;
/**
* Don't convert paths.
*
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
*
* @author Matthias Mullie <pathconverter@mullie.eu>
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
* @license MIT License
*/
class NoConverter implements ConverterInterface
{
/**
* {@inheritdoc}
*/
public function convert($path)
{
return $path;
}
}
<?php
/**
*
* Website: https://wpraiser.com/
* Author: Raul Peixoto (https://www.upwork.com/fl/raulpeixoto)
* Licensed under GPLv2 (or later)
* Version 1.0
*
* Usage: fvm_raisermin_js($js);
*
*/
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# minify js, whitespace only
function fvm_raisermin_js($code){
# remove // comments
$code = preg_replace('/(^|\s)\/\/(.*)\n/m', '', $code);
$code = preg_replace('/(\{|\}|\[|\]|\(|\)|\;)\/\/(.*)\n/m', '$1', $code);
# remove /* ... */ comments
$code = preg_replace('/(^|\s)\/\*(.*)\*\//Us', '', $code);
$code = preg_replace('/(\;|\{)\/\*(.*)\*\//Us', '$1', $code);
# remove sourceMappingURL
$code = preg_replace('/(\/\/\s*[#]\s*sourceMappingURL\s*[=]\s*)([a-zA-Z0-9-_\.\/]+)(\.map)/ui', '', $code);
# uniform line endings, make them all line feed
$code = str_replace(array("\r\n", "\r"), "\n", $code);
# collapse all non-line feed whitespace into a single space
$code = preg_replace('/[^\S\n]+/', ' ', $code);
# strip leading & trailing whitespace
$code = str_replace(array(" \n", "\n "), "\n", $code);
# collapse consecutive line feeds into just 1
$code = preg_replace('/\n+/', "\n", $code);
# process horizontal space
$code = preg_replace('/([\[\]\(\)\{\}\;\<\>])(\h+)([\[\]\(\)\{\}\;\<\>])/ui', '$1 $3', $code);
$code = preg_replace('/([\)])(\h?)(\.)/ui', '$1$3', $code);
$code = preg_replace('/([\)\?])(\h?)(\.)/ui', '$1$3', $code);
$code = preg_replace('/(\,)(\h+)/ui', '$1 ', $code);
$code = preg_replace('/(\h+)(\,)/ui', ' $2', $code);
$code = preg_replace('/([if])(\h+)(\()/ui', '$1$3', $code);
# trim whitespace on beginning/end
return trim($code);
}
# remove UTF8 BOM
function fvm_min_remove_utf8_bom($text) {
$bom = pack('H*','EFBBBF');
while (preg_match("/^$bom/", $text)) {
$text = preg_replace("/^$bom/ui", '', $text);
}
return $text;
}
# minify html, don't touch certain tags
function fvm_raisermin_html($html) {
# clone
$content = $html;
# get all scripts
$skp = array();
preg_match_all('/(\<script(.*?)\<(\s*)\/script(\s*)\>|\<noscript(.*?)\<(\s*)\/noscript(\s*)\>|\<code(.*?)\<(\s*)\/code(\s*)\>|\<pre(.*?)\<(\s*)\/pre(\s*)\>)/uis', $html, $skp);
# replace all skippable patterns with comment
if(is_array($skp) && isset($skp[0]) && count($skp[0]) > 0) {
foreach ($skp[0] as $k=>$v) {
$content = str_replace($v, '<!-- SKIP '.$k.' -->', $content);
}
}
# remove line breaks, and colapse two or more white spaces into one
$content = preg_replace('/\s+/u', " ", $content);
# add linebreaks after html and head tags, for readability
$content = str_replace('<head>', PHP_EOL . '<head>' . PHP_EOL, $content);
$content = str_replace('</head>', PHP_EOL . '</head>' . PHP_EOL, $content);
$content = str_replace('<html', PHP_EOL . '<html', $content);
$content = str_replace('</html>', PHP_EOL . '</html>', $content);
# final readability adjustments
$content = str_replace('<meta ', PHP_EOL . '<meta ', $content);
$content = str_replace('<link ', PHP_EOL . '<link ', $content);
$content = str_replace('<style', PHP_EOL . '<style', $content);
$content = str_replace('<noscript', PHP_EOL . '<noscript>', $content);
# replace markers for scripts last
if(is_array($skp) && isset($skp[0]) && count($skp[0]) > 0) {
foreach ($skp[0] as $k=>$v) {
$content = str_replace('<!-- SKIP '.$k.' -->', PHP_EOL . $v . PHP_EOL, $content);
}
}
# no empty lines
$lines = explode(PHP_EOL, $content);
foreach($lines as $k=>$ln) { $ln = ltrim($ln); if(empty($ln)) { unset($lines[$k]); } else { $lines[$k] = $ln; } }
$content = implode(PHP_EOL, $lines);
# save as html, if not empty
if(!empty($content)) {
$html = $content;
}
# return
return $html;
}
<?php
/**
* Website: http://sourceforge.net/projects/simplehtmldom/
* Additional projects: http://sourceforge.net/projects/debugobject/
* Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
*
* Licensed under The MIT License
* See the LICENSE file in the project root for more information.
*
* Authors:
* S.C. Chen
* John Schlick
* Rus Carroll
* logmanoriginal
*
* Contributors:
* Yousuke Kumakura
* Vadim Voituk
* Antcs
*
* Version Rev. 1.9.1 (291) (edited for FVM)
*/
# Exit if accessed directly
if (!defined('ABSPATH')){ exit(); }
# mod
defined('FVM_MAX_FILE_SIZE') || define('FVM_MAX_FILE_SIZE', 2000000); # Process HTML up to 2 Mb
defined('DEFAULT_TARGET_CHARSET') || define('DEFAULT_TARGET_CHARSET', 'UTF-8');
defined('DEFAULT_BR_TEXT') || define('DEFAULT_BR_TEXT', "\r\n");
defined('DEFAULT_SPAN_TEXT') || define('DEFAULT_SPAN_TEXT', ' ');
# other
define('HDOM_TYPE_ELEMENT', 1);
define('HDOM_TYPE_COMMENT', 2);
define('HDOM_TYPE_TEXT', 3);
define('HDOM_TYPE_ENDTAG', 4);
define('HDOM_TYPE_ROOT', 5);
define('HDOM_TYPE_UNKNOWN', 6);
define('HDOM_QUOTE_DOUBLE', 0);
define('HDOM_QUOTE_SINGLE', 1);
define('HDOM_QUOTE_NO', 3);
define('HDOM_INFO_BEGIN', 0);
define('HDOM_INFO_END', 1);
define('HDOM_INFO_QUOTE', 2);
define('HDOM_INFO_SPACE', 3);
define('HDOM_INFO_TEXT', 4);
define('HDOM_INFO_INNER', 5);
define('HDOM_INFO_OUTER', 6);
define('HDOM_INFO_ENDSPACE', 7);
define('HDOM_SMARTY_AS_TEXT', 1);
# functions
function file_get_html(
$url,
$use_include_path = false,
$context = null,
$offset = 0,
$maxLen = -1,
$lowercase = true,
$forceTagsClosed = true,
$target_charset = DEFAULT_TARGET_CHARSET,
$stripRN = true,
$defaultBRText = DEFAULT_BR_TEXT,
$defaultSpanText = DEFAULT_SPAN_TEXT)
{
if($maxLen <= 0) { $maxLen = FVM_MAX_FILE_SIZE; }
$dom = new simple_html_dom(
null,
$lowercase,
$forceTagsClosed,
$target_charset,
$stripRN,
$defaultBRText,
$defaultSpanText
);
/**
* For sourceforge users: uncomment the next line and comment the
* retrieve_url_contents line 2 lines down if it is not already done.
*/
$contents = file_get_contents(
$url,
$use_include_path,
$context,
$offset,
$maxLen
);
// $contents = retrieve_url_contents($url);
if (empty($contents) || strlen($contents) > $maxLen) {
$dom->clear();
return false;
}
return $dom->load($contents, $lowercase, $stripRN);
}
function str_get_html(
$str,
$lowercase = true,
$forceTagsClosed = true,
$target_charset = DEFAULT_TARGET_CHARSET,
$stripRN = true,
$defaultBRText = DEFAULT_BR_TEXT,
$defaultSpanText = DEFAULT_SPAN_TEXT)
{
$dom = new simple_html_dom(
null,
$lowercase,
$forceTagsClosed,
$target_charset,
$stripRN,
$defaultBRText,
$defaultSpanText
);
if (empty($str) || strlen($str) > FVM_MAX_FILE_SIZE) {
$dom->clear();
return false;
}
return $dom->load($str, $lowercase, $stripRN);
}
function dump_html_tree($node, $show_attr = true, $deep = 0)
{
$node->dump($node);
}
class simple_html_dom_node
{
public $nodetype = HDOM_TYPE_TEXT;
public $tag = 'text';
public $attr = array();
public $children = array();
public $nodes = array();
public $parent = null;
public $_ = array();
public $tag_start = 0;
private $dom = null;
function __construct($dom)
{
$this->dom = $dom;
$dom->nodes[] = $this;
}
function __destruct()
{
$this->clear();
}
function __toString()
{
return $this->outertext();
}
function clear()
{
$this->dom = null;
$this->nodes = null;
$this->parent = null;
$this->children = null;
}
function dump($show_attr = true, $depth = 0)
{
echo str_repeat("\t", $depth) . $this->tag;
if ($show_attr && count($this->attr) > 0) {
echo '(';
foreach ($this->attr as $k => $v) {
echo "[$k]=>\"$v\", ";
}
echo ')';
}
echo "\n";
if ($this->nodes) {
foreach ($this->nodes as $node) {
$node->dump($show_attr, $depth + 1);
}
}
}
function dump_node($echo = true)
{
$string = $this->tag;
if (count($this->attr) > 0) {
$string .= '(';
foreach ($this->attr as $k => $v) {
$string .= "[$k]=>\"$v\", ";
}
$string .= ')';
}
if (count($this->_) > 0) {
$string .= ' $_ (';
foreach ($this->_ as $k => $v) {
if (is_array($v)) {
$string .= "[$k]=>(";
foreach ($v as $k2 => $v2) {
$string .= "[$k2]=>\"$v2\", ";
}
$string .= ')';
} else {
$string .= "[$k]=>\"$v\", ";
}
}
$string .= ')';
}
if (isset($this->text)) {
$string .= " text: ({$this->text})";
}
$string .= ' HDOM_INNER_INFO: ';
if (isset($node->_[HDOM_INFO_INNER])) {
$string .= "'" . $node->_[HDOM_INFO_INNER] . "'";
} else {
$string .= ' NULL ';
}
$string .= ' children: ' . count($this->children);
$string .= ' nodes: ' . count($this->nodes);
$string .= ' tag_start: ' . $this->tag_start;
$string .= "\n";
if ($echo) {
echo $string;
return;
} else {
return $string;
}
}
function parent($parent = null)
{
// I am SURE that this doesn't work properly.
// It fails to unset the current node from it's current parents nodes or
// children list first.
if ($parent !== null) {
$this->parent = $parent;
$this->parent->nodes[] = $this;
$this->parent->children[] = $this;
}
return $this->parent;
}
function has_child()
{
return !empty($this->children);
}
function children($idx = -1)
{
if ($idx === -1) {
return $this->children;
}
if (isset($this->children[$idx])) {
return $this->children[$idx];
}
return null;
}
function first_child()
{
if (count($this->children) > 0) {
return $this->children[0];
}
return null;
}
function last_child()
{
if (count($this->children) > 0) {
return end($this->children);
}
return null;
}
function next_sibling()
{
if ($this->parent === null) {
return null;
}
$idx = array_search($this, $this->parent->children, true);
if ($idx !== false && isset($this->parent->children[$idx + 1])) {
return $this->parent->children[$idx + 1];
}
return null;
}
function prev_sibling()
{
if ($this->parent === null) {
return null;
}
$idx = array_search($this, $this->parent->children, true);
if ($idx !== false && $idx > 0) {
return $this->parent->children[$idx - 1];
}
return null;
}
function find_ancestor_tag($tag)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
if ($this->parent === null) {
return null;
}
$ancestor = $this->parent;
while (!is_null($ancestor)) {
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'Current tag is: ' . $ancestor->tag);
}
if ($ancestor->tag === $tag) {
break;
}
$ancestor = $ancestor->parent;
}
return $ancestor;
}
function innertext()
{
if (isset($this->_[HDOM_INFO_INNER])) {
return $this->_[HDOM_INFO_INNER];
}
if (isset($this->_[HDOM_INFO_TEXT])) {
return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
}
$ret = '';
foreach ($this->nodes as $n) {
$ret .= $n->outertext();
}
return $ret;
}
function outertext()
{
global $debug_object;
if (is_object($debug_object)) {
$text = '';
if ($this->tag === 'text') {
if (!empty($this->text)) {
$text = ' with text: ' . $this->text;
}
}
$debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text);
}
if ($this->tag === 'root') {
return $this->innertext();
}
// todo: What is the use of this callback? Remove?
if ($this->dom && $this->dom->callback !== null) {
call_user_func_array($this->dom->callback, array($this));
}
if (isset($this->_[HDOM_INFO_OUTER])) {
return $this->_[HDOM_INFO_OUTER];
}
if (isset($this->_[HDOM_INFO_TEXT])) {
return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
}
$ret = '';
if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]) {
$ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
}
if (isset($this->_[HDOM_INFO_INNER])) {
// todo: <br> should either never have HDOM_INFO_INNER or always
if ($this->tag !== 'br') {
$ret .= $this->_[HDOM_INFO_INNER];
}
} elseif ($this->nodes) {
foreach ($this->nodes as $n) {
$ret .= $this->convert_text($n->outertext());
}
}
if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END] != 0) {
$ret .= '</' . $this->tag . '>';
}
return $ret;
}
function text()
{
if (isset($this->_[HDOM_INFO_INNER])) {
return $this->_[HDOM_INFO_INNER];
}
switch ($this->nodetype) {
case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
case HDOM_TYPE_COMMENT: return '';
case HDOM_TYPE_UNKNOWN: return '';
}
if (strcasecmp($this->tag, 'script') === 0) { return ''; }
if (strcasecmp($this->tag, 'style') === 0) { return ''; }
$ret = '';
// In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed
// for some span tags, and some p tags) $this->nodes is set to NULL.
// NOTE: This indicates that there is a problem where it's set to NULL
// without a clear happening.
// WHY is this happening?
if (!is_null($this->nodes)) {
foreach ($this->nodes as $n) {
// Start paragraph after a blank line
if ($n->tag === 'p') {
$ret = trim($ret) . "\n\n";
}
$ret .= $this->convert_text($n->text());
// If this node is a span... add a space at the end of it so
// multiple spans don't run into each other. This is plaintext
// after all.
if ($n->tag === 'span') {
$ret .= $this->dom->default_span_text;
}
}
}
return $ret;
}
function xmltext()
{
$ret = $this->innertext();
$ret = str_ireplace('<![CDATA[', '', $ret);
$ret = str_replace(']]>', '', $ret);
return $ret;
}
function makeup()
{
// text, comment, unknown
if (isset($this->_[HDOM_INFO_TEXT])) {
return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
}
$ret = '<' . $this->tag;
$i = -1;
foreach ($this->attr as $key => $val) {
++$i;
// skip removed attribute
if ($val === null || $val === false) { continue; }
$ret .= $this->_[HDOM_INFO_SPACE][$i][0];
//no value attr: nowrap, checked selected...
if ($val === true) {
$ret .= $key;
} else {
switch ($this->_[HDOM_INFO_QUOTE][$i])
{
case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
case HDOM_QUOTE_SINGLE: $quote = '\''; break;
default: $quote = '';
}
$ret .= $key
. $this->_[HDOM_INFO_SPACE][$i][1]
. '='
. $this->_[HDOM_INFO_SPACE][$i][2]
. $quote
. $val
. $quote;
}
}
$ret = $this->dom->restore_noise($ret);
return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
}
function find($selector, $idx = null, $lowercase = false)
{
$selectors = $this->parse_selector($selector);
if (($count = count($selectors)) === 0) { return array(); }
$found_keys = array();
// find each selector
for ($c = 0; $c < $count; ++$c) {
// The change on the below line was documented on the sourceforge
// code tracker id 2788009
// used to be: if (($levle=count($selectors[0]))===0) return array();
if (($levle = count($selectors[$c])) === 0) { return array(); }
if (!isset($this->_[HDOM_INFO_BEGIN])) { return array(); }
$head = array($this->_[HDOM_INFO_BEGIN] => 1);
$cmd = ' '; // Combinator
// handle descendant selectors, no recursive!
for ($l = 0; $l < $levle; ++$l) {
$ret = array();
foreach ($head as $k => $v) {
$n = ($k === -1) ? $this->dom->root : $this->dom->nodes[$k];
//PaperG - Pass this optional parameter on to the seek function.
$n->seek($selectors[$c][$l], $ret, $cmd, $lowercase);
}
$head = $ret;
$cmd = $selectors[$c][$l][4]; // Next Combinator
}
foreach ($head as $k => $v) {
if (!isset($found_keys[$k])) {
$found_keys[$k] = 1;
}
}
}
// sort keys
ksort($found_keys);
$found = array();
foreach ($found_keys as $k => $v) {
$found[] = $this->dom->nodes[$k];
}
// return nth-element or array
if (is_null($idx)) { return $found; }
elseif ($idx < 0) { $idx = count($found) + $idx; }
return (isset($found[$idx])) ? $found[$idx] : null;
}
protected function seek($selector, &$ret, $parent_cmd, $lowercase = false)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
list($tag, $id, $class, $attributes, $cmb) = $selector;
$nodes = array();
if ($parent_cmd === ' ') { // Descendant Combinator
// Find parent closing tag if the current element doesn't have a closing
// tag (i.e. void element)
$end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
if ($end == 0) {
$parent = $this->parent;
while (!isset($parent->_[HDOM_INFO_END]) && $parent !== null) {
$end -= 1;
$parent = $parent->parent;
}
$end += $parent->_[HDOM_INFO_END];
}
// Get list of target nodes
$nodes_start = $this->_[HDOM_INFO_BEGIN] + 1;
$nodes_count = $end - $nodes_start;
$nodes = array_slice($this->dom->nodes, $nodes_start, $nodes_count, true);
} elseif ($parent_cmd === '>') { // Child Combinator
$nodes = $this->children;
} elseif ($parent_cmd === '+'
&& $this->parent
&& in_array($this, $this->parent->children)) { // Next-Sibling Combinator
$index = array_search($this, $this->parent->children, true) + 1;
if ($index < count($this->parent->children))
$nodes[] = $this->parent->children[$index];
} elseif ($parent_cmd === '~'
&& $this->parent
&& in_array($this, $this->parent->children)) { // Subsequent Sibling Combinator
$index = array_search($this, $this->parent->children, true);
$nodes = array_slice($this->parent->children, $index);
}
// Go throgh each element starting at this element until the end tag
// Note: If this element is a void tag, any previous void element is
// skipped.
foreach($nodes as $node) {
$pass = true;
// Skip root nodes
if(!$node->parent) {
$pass = false;
}
// Handle 'text' selector
if($pass && $tag === 'text' && $node->tag === 'text') {
$ret[array_search($node, $this->dom->nodes, true)] = 1;
unset($node);
continue;
}
// Skip if node isn't a child node (i.e. text nodes)
if($pass && !in_array($node, $node->parent->children, true)) {
$pass = false;
}
// Skip if tag doesn't match
if ($pass && $tag !== '' && $tag !== $node->tag && $tag !== '*') {
$pass = false;
}
// Skip if ID doesn't exist
if ($pass && $id !== '' && !isset($node->attr['id'])) {
$pass = false;
}
// Check if ID matches
if ($pass && $id !== '' && isset($node->attr['id'])) {
// Note: Only consider the first ID (as browsers do)
$node_id = explode(' ', trim($node->attr['id']))[0];
if($id !== $node_id) { $pass = false; }
}
// Check if all class(es) exist
if ($pass && $class !== '' && is_array($class) && !empty($class)) {
if (isset($node->attr['class'])) {
$node_classes = explode(' ', $node->attr['class']);
if ($lowercase) {
$node_classes = array_map('strtolower', $node_classes);
}
foreach($class as $c) {
if(!in_array($c, $node_classes)) {
$pass = false;
break;
}
}
} else {
$pass = false;
}
}
// Check attributes
if ($pass
&& $attributes !== ''
&& is_array($attributes)
&& !empty($attributes)) {
foreach($attributes as $a) {
list (
$att_name,
$att_expr,
$att_val,
$att_inv,
$att_case_sensitivity
) = $a;
// Handle indexing attributes (i.e. "[2]")
/**
* Note: This is not supported by the CSS Standard but adds
* the ability to select items compatible to XPath (i.e.
* the 3rd element within it's parent).
*
* Note: This doesn't conflict with the CSS Standard which
* doesn't work on numeric attributes anyway.
*/
if (is_numeric($att_name)
&& $att_expr === ''
&& $att_val === '') {
$count = 0;
// Find index of current element in parent
foreach ($node->parent->children as $c) {
if ($c->tag === $node->tag) ++$count;
if ($c === $node) break;
}
// If this is the correct node, continue with next
// attribute
if ($count === (int)$att_name) continue;
}
// Check attribute availability
if ($att_inv) { // Attribute should NOT be set
if (isset($node->attr[$att_name])) {
$pass = false;
break;
}
} else { // Attribute should be set
// todo: "plaintext" is not a valid CSS selector!
if ($att_name !== 'plaintext'
&& !isset($node->attr[$att_name])) {
$pass = false;
break;
}
}
// Continue with next attribute if expression isn't defined
if ($att_expr === '') continue;
// If they have told us that this is a "plaintext"
// search then we want the plaintext of the node - right?
// todo "plaintext" is not a valid CSS selector!
if ($att_name === 'plaintext') {
$nodeKeyValue = $node->text();
} else {
$nodeKeyValue = $node->attr[$att_name];
}
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'testing node: '
. $node->tag
. ' for attribute: '
. $att_name
. $att_expr
. $att_val
. ' where nodes value is: '
. $nodeKeyValue
);
}
// If lowercase is set, do a case insensitive test of
// the value of the selector.
if ($lowercase) {
$check = $this->match(
$att_expr,
strtolower($att_val),
strtolower($nodeKeyValue),
$att_case_sensitivity
);
} else {
$check = $this->match(
$att_expr,
$att_val,
$nodeKeyValue,
$att_case_sensitivity
);
}
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'after match: '
. ($check ? 'true' : 'false')
);
}
if (!$check) {
$pass = false;
break;
}
}
}
// Found a match. Add to list and clear node
if ($pass) $ret[$node->_[HDOM_INFO_BEGIN]] = 1;
unset($node);
}
// It's passed by reference so this is actually what this function returns.
if (is_object($debug_object)) {
$debug_object->debug_log(1, 'EXIT - ret: ', $ret);
}
}
protected function match($exp, $pattern, $value, $case_sensitivity)
{
global $debug_object;
if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}
if ($case_sensitivity === 'i') {
$pattern = strtolower($pattern);
$value = strtolower($value);
}
switch ($exp) {
case '=':
return ($value === $pattern);
case '!=':
return ($value !== $pattern);
case '^=':
return preg_match('/^' . preg_quote($pattern, '/') . '/', $value);
case '$=':
return preg_match('/' . preg_quote($pattern, '/') . '$/', $value);
case '*=':
return preg_match('/' . preg_quote($pattern, '/') . '/', $value);
case '|=':
/**
* [att|=val]
*
* Represents an element with the att attribute, its value
* either being exactly "val" or beginning with "val"
* immediately followed by "-" (U+002D).
*/
return strpos($value, $pattern) === 0;
case '~=':
/**
* [att~=val]
*
* Represents an element with the att attribute whose value is a
* whitespace-separated list of words, one of which is exactly
* "val". If "val" contains whitespace, it will never represent
* anything (since the words are separated by spaces). Also if
* "val" is the empty string, it will never represent anything.
*/
return in_array($pattern, explode(' ', trim($value)), true);
}
return false;
}
protected function parse_selector($selector_string)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
/**
* Pattern of CSS selectors, modified from mootools (https://mootools.net/)
*
* Paperg: Add the colon to the attribute, so that it properly finds
* <tag attr:ibute="something" > like google does.
*
* Note: if you try to look at this attribute, you MUST use getAttribute
* since $dom->x:y will fail the php syntax check.
*
* Notice the \[ starting the attribute? and the @? following? This
* implies that an attribute can begin with an @ sign that is not
* captured. This implies that an html attribute specifier may start
* with an @ sign that is NOT captured by the expression. Farther study
* is required to determine of this should be documented or removed.
*
* Matches selectors in this order:
*
* [0] - full match
*
* [1] - tag name
* ([\w:\*-]*)
* Matches the tag name consisting of zero or more words, colons,
* asterisks and hyphens.
*
* [2] - id name
* (?:\#([\w-]+))
* Optionally matches a id name, consisting of an "#" followed by
* the id name (one or more words and hyphens).
*
* [3] - class names (including dots)
* (?:\.([\w\.-]+))?
* Optionally matches a list of classs, consisting of an "."
* followed by the class name (one or more words and hyphens)
* where multiple classes can be chained (i.e. ".foo.bar.baz")
*
* [4] - attributes
* ((?:\[@?(?:!?[\w:-]+)(?:(?:[!*^$|~]?=)[\"']?(?:.*?)[\"']?)?(?:\s*?(?:[iIsS])?)?\])+)?
* Optionally matches the attributes list
*
* [5] - separator
* ([\/, >+~]+)
* Matches the selector list separator
*/
// phpcs:ignore Generic.Files.LineLength
$pattern = "/([\w:\*-]*)(?:\#([\w-]+))?(?:|\.([\w\.-]+))?((?:\[@?(?:!?[\w:-]+)(?:(?:[!*^$|~]?=)[\"']?(?:.*?)[\"']?)?(?:\s*?(?:[iIsS])?)?\])+)?([\/, >+~]+)/is";
preg_match_all(
$pattern,
trim($selector_string) . ' ', // Add final ' ' as pseudo separator
$matches,
PREG_SET_ORDER
);
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'Matches Array: ', $matches);
}
$selectors = array();
$result = array();
foreach ($matches as $m) {
$m[0] = trim($m[0]);
// Skip NoOps
if ($m[0] === '' || $m[0] === '/' || $m[0] === '//') { continue; }
// Convert to lowercase
if ($this->dom->lowercase) {
$m[1] = strtolower($m[1]);
}
// Extract classes
if ($m[3] !== '') { $m[3] = explode('.', $m[3]); }
/* Extract attributes (pattern based on the pattern above!)
* [0] - full match
* [1] - attribute name
* [2] - attribute expression
* [3] - attribute value
* [4] - case sensitivity
*
* Note: Attributes can be negated with a "!" prefix to their name
*/
if($m[4] !== '') {
preg_match_all(
"/\[@?(!?[\w:-]+)(?:([!*^$|~]?=)[\"']?(.*?)[\"']?)?(?:\s+?([iIsS])?)?\]/is",
trim($m[4]),
$attributes,
PREG_SET_ORDER
);
// Replace element by array
$m[4] = array();
foreach($attributes as $att) {
// Skip empty matches
if(trim($att[0]) === '') { continue; }
$inverted = (isset($att[1][0]) && $att[1][0] === '!');
$m[4][] = array(
$inverted ? substr($att[1], 1) : $att[1], // Name
(isset($att[2])) ? $att[2] : '', // Expression
(isset($att[3])) ? $att[3] : '', // Value
$inverted, // Inverted Flag
(isset($att[4])) ? strtolower($att[4]) : '', // Case-Sensitivity
);
}
}
// Sanitize Separator
if ($m[5] !== '' && trim($m[5]) === '') { // Descendant Separator
$m[5] = ' ';
} else { // Other Separator
$m[5] = trim($m[5]);
}
// Clear Separator if it's a Selector List
if ($is_list = ($m[5] === ',')) { $m[5] = ''; }
// Remove full match before adding to results
array_shift($m);
$result[] = $m;
if ($is_list) { // Selector List
$selectors[] = $result;
$result = array();
}
}
if (count($result) > 0) { $selectors[] = $result; }
return $selectors;
}
function __get($name)
{
if (isset($this->attr[$name])) {
return $this->convert_text($this->attr[$name]);
}
switch ($name) {
case 'outertext': return $this->outertext();
case 'innertext': return $this->innertext();
case 'plaintext': return $this->text();
case 'xmltext': return $this->xmltext();
default: return array_key_exists($name, $this->attr);
}
}
function __set($name, $value)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
switch ($name) {
case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
case 'innertext':
if (isset($this->_[HDOM_INFO_TEXT])) {
return $this->_[HDOM_INFO_TEXT] = $value;
}
return $this->_[HDOM_INFO_INNER] = $value;
}
if (!isset($this->attr[$name])) {
$this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
$this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
}
$this->attr[$name] = $value;
}
function __isset($name)
{
switch ($name) {
case 'outertext': return true;
case 'innertext': return true;
case 'plaintext': return true;
}
//no value attr: nowrap, checked selected...
return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
}
function __unset($name)
{
if (isset($this->attr[$name])) { unset($this->attr[$name]); }
}
function convert_text($text)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
$converted_text = $text;
$sourceCharset = '';
$targetCharset = '';
if ($this->dom) {
$sourceCharset = strtoupper($this->dom->_charset);
$targetCharset = strtoupper($this->dom->_target_charset);
}
if (is_object($debug_object)) {
$debug_object->debug_log(3,
'source charset: '
. $sourceCharset
. ' target charaset: '
. $targetCharset
);
}
if (!empty($sourceCharset)
&& !empty($targetCharset)
&& (strcasecmp($sourceCharset, $targetCharset) != 0)) {
// Check if the reported encoding could have been incorrect and the text is actually already UTF-8
if ((strcasecmp($targetCharset, 'UTF-8') == 0)
&& ($this->is_utf8($text))) {
$converted_text = $text;
} else {
$converted_text = iconv($sourceCharset, $targetCharset, $text);
}
}
// Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output.
if ($targetCharset === 'UTF-8') {
if (substr($converted_text, 0, 3) === "\xef\xbb\xbf") {
$converted_text = substr($converted_text, 3);
}
if (substr($converted_text, -3) === "\xef\xbb\xbf") {
$converted_text = substr($converted_text, 0, -3);
}
}
return $converted_text;
}
static function is_utf8($str)
{
$c = 0; $b = 0;
$bits = 0;
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$c = ord($str[$i]);
if($c > 128) {
if(($c >= 254)) { return false; }
elseif($c >= 252) { $bits = 6; }
elseif($c >= 248) { $bits = 5; }
elseif($c >= 240) { $bits = 4; }
elseif($c >= 224) { $bits = 3; }
elseif($c >= 192) { $bits = 2; }
else { return false; }
if(($i + $bits) > $len) { return false; }
while($bits > 1) {
$i++;
$b = ord($str[$i]);
if($b < 128 || $b > 191) { return false; }
$bits--;
}
}
}
return true;
}
function get_display_size()
{
global $debug_object;
$width = -1;
$height = -1;
if ($this->tag !== 'img') {
return false;
}
// See if there is aheight or width attribute in the tag itself.
if (isset($this->attr['width'])) {
$width = $this->attr['width'];
}
if (isset($this->attr['height'])) {
$height = $this->attr['height'];
}
// Now look for an inline style.
if (isset($this->attr['style'])) {
// Thanks to user gnarf from stackoverflow for this regular expression.
$attributes = array();
preg_match_all(
'/([\w-]+)\s*:\s*([^;]+)\s*;?/',
$this->attr['style'],
$matches,
PREG_SET_ORDER
);
foreach ($matches as $match) {
$attributes[$match[1]] = $match[2];
}
// If there is a width in the style attributes:
if (isset($attributes['width']) && $width == -1) {
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes['width'], -2)) === 'px') {
$proposed_width = substr($attributes['width'], 0, -2);
// Now make sure that it's an integer and not something stupid.
if (filter_var($proposed_width, FILTER_VALIDATE_INT)) {
$width = $proposed_width;
}
}
}
// If there is a width in the style attributes:
if (isset($attributes['height']) && $height == -1) {
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes['height'], -2)) == 'px') {
$proposed_height = substr($attributes['height'], 0, -2);
// Now make sure that it's an integer and not something stupid.
if (filter_var($proposed_height, FILTER_VALIDATE_INT)) {
$height = $proposed_height;
}
}
}
}
// Future enhancement:
// Look in the tag to see if there is a class or id specified that has
// a height or width attribute to it.
// Far future enhancement
// Look at all the parent tags of this image to see if they specify a
// class or id that has an img selector that specifies a height or width
// Note that in this case, the class or id will have the img subselector
// for it to apply to the image.
// ridiculously far future development
// If the class or id is specified in a SEPARATE css file thats not on
// the page, go get it and do what we were just doing for the ones on
// the page.
$result = array(
'height' => $height,
'width' => $width
);
return $result;
}
function save($filepath = '')
{
$ret = $this->outertext();
if ($filepath !== '') {
file_put_contents($filepath, $ret, LOCK_EX);
}
return $ret;
}
function addClass($class)
{
if (is_string($class)) {
$class = explode(' ', $class);
}
if (is_array($class)) {
foreach($class as $c) {
if (isset($this->class)) {
if ($this->hasClass($c)) {
continue;
} else {
$this->class .= ' ' . $c;
}
} else {
$this->class = $c;
}
}
} else {
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'Invalid type: ', gettype($class));
}
}
}
function hasClass($class)
{
if (is_string($class)) {
if (isset($this->class)) {
return in_array($class, explode(' ', $this->class), true);
}
} else {
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'Invalid type: ', gettype($class));
}
}
return false;
}
function removeClass($class = null)
{
if (!isset($this->class)) {
return;
}
if (is_null($class)) {
$this->removeAttribute('class');
return;
}
if (is_string($class)) {
$class = explode(' ', $class);
}
if (is_array($class)) {
$class = array_diff(explode(' ', $this->class), $class);
if (empty($class)) {
$this->removeAttribute('class');
} else {
$this->class = implode(' ', $class);
}
}
}
function getAllAttributes()
{
return $this->attr;
}
function getAttribute($name)
{
return $this->__get($name);
}
function setAttribute($name, $value)
{
$this->__set($name, $value);
}
function hasAttribute($name)
{
return $this->__isset($name);
}
function removeAttribute($name)
{
$this->__set($name, null);
}
function remove()
{
if ($this->parent) {
$this->parent->removeChild($this);
}
}
function removeChild($node)
{
$nidx = array_search($node, $this->nodes, true);
$cidx = array_search($node, $this->children, true);
$didx = array_search($node, $this->dom->nodes, true);
if ($nidx !== false && $cidx !== false && $didx !== false) {
foreach($node->children as $child) {
$node->removeChild($child);
}
foreach($node->nodes as $entity) {
$enidx = array_search($entity, $node->nodes, true);
$edidx = array_search($entity, $node->dom->nodes, true);
if ($enidx !== false && $edidx !== false) {
unset($node->nodes[$enidx]);
unset($node->dom->nodes[$edidx]);
}
}
unset($this->nodes[$nidx]);
unset($this->children[$cidx]);
unset($this->dom->nodes[$didx]);
$node->clear();
}
}
function getElementById($id)
{
return $this->find("#$id", 0);
}
function getElementsById($id, $idx = null)
{
return $this->find("#$id", $idx);
}
function getElementByTagName($name)
{
return $this->find($name, 0);
}
function getElementsByTagName($name, $idx = null)
{
return $this->find($name, $idx);
}
function parentNode()
{
return $this->parent();
}
function childNodes($idx = -1)
{
return $this->children($idx);
}
function firstChild()
{
return $this->first_child();
}
function lastChild()
{
return $this->last_child();
}
function nextSibling()
{
return $this->next_sibling();
}
function previousSibling()
{
return $this->prev_sibling();
}
function hasChildNodes()
{
return $this->has_child();
}
function nodeName()
{
return $this->tag;
}
function appendChild($node)
{
$node->parent($this);
return $node;
}
}
class simple_html_dom
{
public $root = null;
public $nodes = array();
public $callback = null;
public $lowercase = false;
public $original_size;
public $size;
protected $pos;
protected $doc;
protected $char;
protected $cursor;
protected $parent;
protected $noise = array();
protected $token_blank = " \t\r\n";
protected $token_equal = ' =/>';
protected $token_slash = " />\r\n\t";
protected $token_attr = ' >';
public $_charset = '';
public $_target_charset = '';
protected $default_br_text = '';
public $default_span_text = '';
protected $self_closing_tags = array(
'area' => 1,
'base' => 1,
'br' => 1,
'col' => 1,
'embed' => 1,
'hr' => 1,
'img' => 1,
'input' => 1,
'link' => 1,
'meta' => 1,
'param' => 1,
'source' => 1,
'track' => 1,
'wbr' => 1
);
protected $block_tags = array(
'body' => 1,
'div' => 1,
'form' => 1,
'root' => 1,
'span' => 1,
'table' => 1
);
protected $optional_closing_tags = array(
// Not optional, see
// https://www.w3.org/TR/html/textlevel-semantics.html#the-b-element
'b' => array('b' => 1),
'dd' => array('dd' => 1, 'dt' => 1),
// Not optional, see
// https://www.w3.org/TR/html/grouping-content.html#the-dl-element
'dl' => array('dd' => 1, 'dt' => 1),
'dt' => array('dd' => 1, 'dt' => 1),
'li' => array('li' => 1),
'optgroup' => array('optgroup' => 1, 'option' => 1),
'option' => array('optgroup' => 1, 'option' => 1),
'p' => array('p' => 1),
'rp' => array('rp' => 1, 'rt' => 1),
'rt' => array('rp' => 1, 'rt' => 1),
'td' => array('td' => 1, 'th' => 1),
'th' => array('td' => 1, 'th' => 1),
'tr' => array('td' => 1, 'th' => 1, 'tr' => 1),
);
function __construct(
$str = null,
$lowercase = true,
$forceTagsClosed = true,
$target_charset = DEFAULT_TARGET_CHARSET,
$stripRN = true,
$defaultBRText = DEFAULT_BR_TEXT,
$defaultSpanText = DEFAULT_SPAN_TEXT,
$options = 0)
{
if ($str) {
if (preg_match('/^http:\/\//i', $str) || is_file($str)) {
$this->load_file($str);
} else {
$this->load(
$str,
$lowercase,
$stripRN,
$defaultBRText,
$defaultSpanText,
$options
);
}
}
// Forcing tags to be closed implies that we don't trust the html, but
// it can lead to parsing errors if we SHOULD trust the html.
if (!$forceTagsClosed) {
$this->optional_closing_array = array();
}
$this->_target_charset = $target_charset;
}
function __destruct()
{
$this->clear();
}
function load(
$str,
$lowercase = true,
$stripRN = true,
$defaultBRText = DEFAULT_BR_TEXT,
$defaultSpanText = DEFAULT_SPAN_TEXT,
$options = 0)
{
global $debug_object;
// prepare
$this->prepare($str, $lowercase, $defaultBRText, $defaultSpanText);
// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
// Script tags removal now preceeds style tag removal.
// strip out <script> tags
$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
// strip out the \r \n's if we are told to.
if ($stripRN) {
$this->doc = str_replace("\r", ' ', $this->doc);
$this->doc = str_replace("\n", ' ', $this->doc);
// set the length of content since we have changed it.
$this->size = strlen($this->doc);
}
// strip out cdata
$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
// strip out comments
$this->remove_noise("'<!--(.*?)-->'is");
// strip out <style> tags
$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
// strip out preformatted tags
$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
// strip out server side scripts
$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
if($options & HDOM_SMARTY_AS_TEXT) { // Strip Smarty scripts
$this->remove_noise("'(\{\w)(.*?)(\})'s", true);
}
// parsing
$this->parse();
// end
$this->root->_[HDOM_INFO_END] = $this->cursor;
$this->parse_charset();
// make load function chainable
return $this;
}
function load_file()
{
$args = func_get_args();
if(($doc = call_user_func_array('file_get_contents', $args)) !== false) {
$this->load($doc, true);
} else {
return false;
}
}
function set_callback($function_name)
{
$this->callback = $function_name;
}
function remove_callback()
{
$this->callback = null;
}
function save($filepath = '')
{
$ret = $this->root->innertext();
if ($filepath !== '') { file_put_contents($filepath, $ret, LOCK_EX); }
return $ret;
}
function find($selector, $idx = null, $lowercase = false)
{
return $this->root->find($selector, $idx, $lowercase);
}
function clear()
{
if (isset($this->nodes)) {
foreach ($this->nodes as $n) {
$n->clear();
$n = null;
}
}
// This add next line is documented in the sourceforge repository.
// 2977248 as a fix for ongoing memory leaks that occur even with the
// use of clear.
if (isset($this->children)) {
foreach ($this->children as $n) {
$n->clear();
$n = null;
}
}
if (isset($this->parent)) {
$this->parent->clear();
unset($this->parent);
}
if (isset($this->root)) {
$this->root->clear();
unset($this->root);
}
unset($this->doc);
unset($this->noise);
}
function dump($show_attr = true)
{
$this->root->dump($show_attr);
}
protected function prepare(
$str, $lowercase = true,
$defaultBRText = DEFAULT_BR_TEXT,
$defaultSpanText = DEFAULT_SPAN_TEXT)
{
$this->clear();
$this->doc = trim($str);
$this->size = strlen($this->doc);
$this->original_size = $this->size; // original size of the html
$this->pos = 0;
$this->cursor = 1;
$this->noise = array();
$this->nodes = array();
$this->lowercase = $lowercase;
$this->default_br_text = $defaultBRText;
$this->default_span_text = $defaultSpanText;
$this->root = new simple_html_dom_node($this);
$this->root->tag = 'root';
$this->root->_[HDOM_INFO_BEGIN] = -1;
$this->root->nodetype = HDOM_TYPE_ROOT;
$this->parent = $this->root;
if ($this->size > 0) { $this->char = $this->doc[0]; }
}
protected function parse()
{
while (true) {
// Read next tag if there is no text between current position and the
// next opening tag.
if (($s = $this->copy_until_char('<')) === '') {
if($this->read_tag()) {
continue;
} else {
return true;
}
}
// Add a text node for text between tags
$node = new simple_html_dom_node($this);
++$this->cursor;
$node->_[HDOM_INFO_TEXT] = $s;
$this->link_nodes($node, false);
}
}
protected function parse_charset()
{
global $debug_object;
$charset = null;
if (function_exists('get_last_retrieve_url_contents_content_type')) {
$contentTypeHeader = get_last_retrieve_url_contents_content_type();
$success = preg_match('/charset=(.+)/', $contentTypeHeader, $matches);
if ($success) {
$charset = $matches[1];
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'header content-type found charset of: '
. $charset
);
}
}
}
if (empty($charset)) {
// https://www.w3.org/TR/html/document-metadata.html#statedef-http-equiv-content-type
$el = $this->root->find('meta[http-equiv=Content-Type]', 0, true);
if (!empty($el)) {
$fullvalue = $el->content;
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'meta content-type tag found'
. $fullvalue
);
}
if (!empty($fullvalue)) {
$success = preg_match(
'/charset=(.+)/i',
$fullvalue,
$matches
);
if ($success) {
$charset = $matches[1];
} else {
// If there is a meta tag, and they don't specify the
// character set, research says that it's typically
// ISO-8859-1
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'meta content-type tag couldn\'t be parsed. using iso-8859 default.'
);
}
$charset = 'ISO-8859-1';
}
}
}
}
if (empty($charset)) {
// https://www.w3.org/TR/html/document-metadata.html#character-encoding-declaration
if ($meta = $this->root->find('meta[charset]', 0)) {
$charset = $meta->charset;
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'meta charset: ' . $charset);
}
}
}
if (empty($charset)) {
// Try to guess the charset based on the content
// Requires Multibyte String (mbstring) support (optional)
if (function_exists('mb_detect_encoding')) {
/**
* mb_detect_encoding() is not intended to distinguish between
* charsets, especially single-byte charsets. Its primary
* purpose is to detect which multibyte encoding is in use,
* i.e. UTF-8, UTF-16, shift-JIS, etc.
*
* -- https://bugs.php.net/bug.php?id=38138
*
* Adding both CP1251/ISO-8859-5 and CP1252/ISO-8859-1 will
* always result in CP1251/ISO-8859-5 and vice versa.
*
* Thus, only detect if it's either UTF-8 or CP1252/ISO-8859-1
* to stay compatible.
*/
$encoding = mb_detect_encoding(
$this->doc,
array( 'UTF-8', 'CP1252', 'ISO-8859-1' )
);
if ($encoding === 'CP1252' || $encoding === 'ISO-8859-1') {
// Due to a limitation of mb_detect_encoding
// 'CP1251'/'ISO-8859-5' will be detected as
// 'CP1252'/'ISO-8859-1'. This will cause iconv to fail, in
// which case we can simply assume it is the other charset.
if (!@iconv('CP1252', 'UTF-8', $this->doc)) {
$encoding = 'CP1251';
}
}
if ($encoding !== false) {
$charset = $encoding;
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'mb_detect: ' . $charset);
}
}
}
}
if (empty($charset)) {
// Assume it's UTF-8 as it is the most likely charset to be used
$charset = 'UTF-8';
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'No match found, assume ' . $charset);
}
}
// Since CP1252 is a superset, if we get one of it's subsets, we want
// it instead.
if ((strtolower($charset) == 'iso-8859-1')
|| (strtolower($charset) == 'latin1')
|| (strtolower($charset) == 'latin-1')) {
$charset = 'CP1252';
if (is_object($debug_object)) {
$debug_object->debug_log(2,
'replacing ' . $charset . ' with CP1252 as its a superset'
);
}
}
if (is_object($debug_object)) {
$debug_object->debug_log(1, 'EXIT - ' . $charset);
}
return $this->_charset = $charset;
}
protected function read_tag()
{
// Set end position if no further tags found
if ($this->char !== '<') {
$this->root->_[HDOM_INFO_END] = $this->cursor;
return false;
}
$begin_tag_pos = $this->pos;
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
// end tag
if ($this->char === '/') {
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
// Skip whitespace in end tags (i.e. in "</ html>")
$this->skip($this->token_blank);
$tag = $this->copy_until_char('>');
// Skip attributes in end tags
if (($pos = strpos($tag, ' ')) !== false) {
$tag = substr($tag, 0, $pos);
}
$parent_lower = strtolower($this->parent->tag);
$tag_lower = strtolower($tag);
// The end tag is supposed to close the parent tag. Handle situations
// when it doesn't
if ($parent_lower !== $tag_lower) {
// Parent tag does not have to be closed necessarily (optional closing tag)
// Current tag is a block tag, so it may close an ancestor
if (isset($this->optional_closing_tags[$parent_lower])
&& isset($this->block_tags[$tag_lower])) {
$this->parent->_[HDOM_INFO_END] = 0;
$org_parent = $this->parent;
// Traverse ancestors to find a matching opening tag
// Stop at root node
while (($this->parent->parent)
&& strtolower($this->parent->tag) !== $tag_lower
){
$this->parent = $this->parent->parent;
}
// If we don't have a match add current tag as text node
if (strtolower($this->parent->tag) !== $tag_lower) {
$this->parent = $org_parent; // restore origonal parent
if ($this->parent->parent) {
$this->parent = $this->parent->parent;
}
$this->parent->_[HDOM_INFO_END] = $this->cursor;
return $this->as_text_node($tag);
}
} elseif (($this->parent->parent)
&& isset($this->block_tags[$tag_lower])
) {
// Grandparent exists and current tag is a block tag, so our
// parent doesn't have an end tag
$this->parent->_[HDOM_INFO_END] = 0; // No end tag
$org_parent = $this->parent;
// Traverse ancestors to find a matching opening tag
// Stop at root node
while (($this->parent->parent)
&& strtolower($this->parent->tag) !== $tag_lower
) {
$this->parent = $this->parent->parent;
}
// If we don't have a match add current tag as text node
if (strtolower($this->parent->tag) !== $tag_lower) {
$this->parent = $org_parent; // restore origonal parent
$this->parent->_[HDOM_INFO_END] = $this->cursor;
return $this->as_text_node($tag);
}
} elseif (($this->parent->parent)
&& strtolower($this->parent->parent->tag) === $tag_lower
) { // Grandparent exists and current tag closes it
$this->parent->_[HDOM_INFO_END] = 0;
$this->parent = $this->parent->parent;
} else { // Random tag, add as text node
return $this->as_text_node($tag);
}
}
// Set end position of parent tag to current cursor position
$this->parent->_[HDOM_INFO_END] = $this->cursor;
if ($this->parent->parent) {
$this->parent = $this->parent->parent;
}
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
// start tag
$node = new simple_html_dom_node($this);
$node->_[HDOM_INFO_BEGIN] = $this->cursor;
++$this->cursor;
$tag = $this->copy_until($this->token_slash); // Get tag name
$node->tag_start = $begin_tag_pos;
// doctype, cdata & comments...
// <!DOCTYPE html>
// <![CDATA[ ... ]]>
// <!-- Comment -->
if (isset($tag[0]) && $tag[0] === '!') {
$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
if (isset($tag[2]) && $tag[1] === '-' && $tag[2] === '-') { // Comment ("<!--")
$node->nodetype = HDOM_TYPE_COMMENT;
$node->tag = 'comment';
} else { // Could be doctype or CDATA but we don't care
$node->nodetype = HDOM_TYPE_UNKNOWN;
$node->tag = 'unknown';
}
if ($this->char === '>') { $node->_[HDOM_INFO_TEXT] .= '>'; }
$this->link_nodes($node, true);
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
// The start tag cannot contain another start tag, if so add as text
// i.e. "<<html>"
if ($pos = strpos($tag, '<') !== false) {
$tag = '<' . substr($tag, 0, -1);
$node->_[HDOM_INFO_TEXT] = $tag;
$this->link_nodes($node, false);
$this->char = $this->doc[--$this->pos]; // prev
return true;
}
// Handle invalid tag names (i.e. "<html#doc>")
if (!preg_match('/^\w[\w:-]*$/', $tag)) {
$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
// Next char is the beginning of a new tag, don't touch it.
if ($this->char === '<') {
$this->link_nodes($node, false);
return true;
}
// Next char closes current tag, add and be done with it.
if ($this->char === '>') { $node->_[HDOM_INFO_TEXT] .= '>'; }
$this->link_nodes($node, false);
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
// begin tag, add new node
$node->nodetype = HDOM_TYPE_ELEMENT;
$tag_lower = strtolower($tag);
$node->tag = ($this->lowercase) ? $tag_lower : $tag;
// handle optional closing tags
if (isset($this->optional_closing_tags[$tag_lower])) {
// Traverse ancestors to close all optional closing tags
while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)])) {
$this->parent->_[HDOM_INFO_END] = 0;
$this->parent = $this->parent->parent;
}
$node->parent = $this->parent;
}
$guard = 0; // prevent infinity loop
// [0] Space between tag and first attribute
$space = array($this->copy_skip($this->token_blank), '', '');
// attributes
do {
// Everything until the first equal sign should be the attribute name
$name = $this->copy_until($this->token_equal);
if ($name === '' && $this->char !== null && $space[0] === '') {
break;
}
if ($guard === $this->pos) { // Escape infinite loop
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
continue;
}
$guard = $this->pos;
// handle endless '<'
// Out of bounds before the tag ended
if ($this->pos >= $this->size - 1 && $this->char !== '>') {
$node->nodetype = HDOM_TYPE_TEXT;
$node->_[HDOM_INFO_END] = 0;
$node->_[HDOM_INFO_TEXT] = '<' . $tag . $space[0] . $name;
$node->tag = 'text';
$this->link_nodes($node, false);
return true;
}
// handle mismatch '<'
// Attributes cannot start after opening tag
if ($this->doc[$this->pos - 1] == '<') {
$node->nodetype = HDOM_TYPE_TEXT;
$node->tag = 'text';
$node->attr = array();
$node->_[HDOM_INFO_END] = 0;
$node->_[HDOM_INFO_TEXT] = substr(
$this->doc,
$begin_tag_pos,
$this->pos - $begin_tag_pos - 1
);
$this->pos -= 2;
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
$this->link_nodes($node, false);
return true;
}
if ($name !== '/' && $name !== '') { // this is a attribute name
// [1] Whitespace after attribute name
$space[1] = $this->copy_skip($this->token_blank);
$name = $this->restore_noise($name); // might be a noisy name
if ($this->lowercase) { $name = strtolower($name); }
if ($this->char === '=') { // attribute with value
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
$this->parse_attr($node, $name, $space); // get attribute value
} else {
//no value attr: nowrap, checked selected...
$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
$node->attr[$name] = true;
if ($this->char != '>') { $this->char = $this->doc[--$this->pos]; } // prev
}
$node->_[HDOM_INFO_SPACE][] = $space;
// prepare for next attribute
$space = array(
$this->copy_skip($this->token_blank),
'',
''
);
} else { // no more attributes
break;
}
} while ($this->char !== '>' && $this->char !== '/'); // go until the tag ended
$this->link_nodes($node, true);
$node->_[HDOM_INFO_ENDSPACE] = $space[0];
// handle empty tags (i.e. "<div/>")
if ($this->copy_until_char('>') === '/') {
$node->_[HDOM_INFO_ENDSPACE] .= '/';
$node->_[HDOM_INFO_END] = 0;
} else {
// reset parent
if (!isset($this->self_closing_tags[strtolower($node->tag)])) {
$this->parent = $node;
}
}
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
// If it's a BR tag, we need to set it's text to the default text.
// This way when we see it in plaintext, we can generate formatting that the user wants.
// since a br tag never has sub nodes, this works well.
if ($node->tag === 'br') {
$node->_[HDOM_INFO_INNER] = $this->default_br_text;
}
return true;
}
protected function parse_attr($node, $name, &$space)
{
$is_duplicate = isset($node->attr[$name]);
if (!$is_duplicate) // Copy whitespace between "=" and value
$space[2] = $this->copy_skip($this->token_blank);
switch ($this->char) {
case '"':
$quote_type = HDOM_QUOTE_DOUBLE;
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
$value = $this->copy_until_char('"');
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
break;
case '\'':
$quote_type = HDOM_QUOTE_SINGLE;
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
$value = $this->copy_until_char('\'');
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
break;
default:
$quote_type = HDOM_QUOTE_NO;
$value = $this->copy_until($this->token_attr);
}
$value = $this->restore_noise($value);
// PaperG: Attributes should not have \r or \n in them, that counts as
// html whitespace.
$value = str_replace("\r", '', $value);
$value = str_replace("\n", '', $value);
// PaperG: If this is a "class" selector, lets get rid of the preceeding
// and trailing space since some people leave it in the multi class case.
if ($name === 'class') {
$value = trim($value);
}
if (!$is_duplicate) {
$node->_[HDOM_INFO_QUOTE][] = $quote_type;
$node->attr[$name] = $value;
}
}
protected function link_nodes(&$node, $is_child)
{
$node->parent = $this->parent;
$this->parent->nodes[] = $node;
if ($is_child) {
$this->parent->children[] = $node;
}
}
protected function as_text_node($tag)
{
$node = new simple_html_dom_node($this);
++$this->cursor;
$node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
$this->link_nodes($node, false);
$this->char = (++$this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
protected function skip($chars)
{
$this->pos += strspn($this->doc, $chars, $this->pos);
$this->char = ($this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
}
protected function copy_skip($chars)
{
$pos = $this->pos;
$len = strspn($this->doc, $chars, $pos);
$this->pos += $len;
$this->char = ($this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
if ($len === 0) { return ''; }
return substr($this->doc, $pos, $len);
}
protected function copy_until($chars)
{
$pos = $this->pos;
$len = strcspn($this->doc, $chars, $pos);
$this->pos += $len;
$this->char = ($this->pos < $this->size) ? $this->doc[$this->pos] : null; // next
return substr($this->doc, $pos, $len);
}
protected function copy_until_char($char)
{
if ($this->char === null) { return ''; }
if (($pos = strpos($this->doc, $char, $this->pos)) === false) {
$ret = substr($this->doc, $this->pos, $this->size - $this->pos);
$this->char = null;
$this->pos = $this->size;
return $ret;
}
if ($pos === $this->pos) { return ''; }
$pos_old = $this->pos;
$this->char = $this->doc[$pos];
$this->pos = $pos;
return substr($this->doc, $pos_old, $pos - $pos_old);
}
protected function remove_noise($pattern, $remove_tag = false)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
$count = preg_match_all(
$pattern,
$this->doc,
$matches,
PREG_SET_ORDER | PREG_OFFSET_CAPTURE
);
for ($i = $count - 1; $i > -1; --$i) {
$key = '___noise___' . sprintf('% 5d', count($this->noise) + 1000);
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'key is: ' . $key);
}
$idx = ($remove_tag) ? 0 : 1; // 0 = entire match, 1 = submatch
$this->noise[$key] = $matches[$i][$idx][0];
$this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
}
// reset the length of content
$this->size = strlen($this->doc);
if ($this->size > 0) {
$this->char = $this->doc[0];
}
}
function restore_noise($text)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
while (($pos = strpos($text, '___noise___')) !== false) {
// Sometimes there is a broken piece of markup, and we don't GET the
// pos+11 etc... token which indicates a problem outside of us...
// todo: "___noise___1000" (or any number with four or more digits)
// in the DOM causes an infinite loop which could be utilized by
// malicious software
if (strlen($text) > $pos + 15) {
$key = '___noise___'
. $text[$pos + 11]
. $text[$pos + 12]
. $text[$pos + 13]
. $text[$pos + 14]
. $text[$pos + 15];
if (is_object($debug_object)) {
$debug_object->debug_log(2, 'located key of: ' . $key);
}
if (isset($this->noise[$key])) {
$text = substr($text, 0, $pos)
. $this->noise[$key]
. substr($text, $pos + 16);
} else {
// do this to prevent an infinite loop.
$text = substr($text, 0, $pos)
. 'UNDEFINED NOISE FOR KEY: '
. $key
. substr($text, $pos + 16);
}
} else {
// There is no valid key being given back to us... We must get
// rid of the ___noise___ or we will have a problem.
$text = substr($text, 0, $pos)
. 'NO NUMERIC NOISE KEY'
. substr($text, $pos + 11);
}
}
return $text;
}
function search_noise($text)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
foreach($this->noise as $noiseElement) {
if (strpos($noiseElement, $text) !== false) {
return $noiseElement;
}
}
}
function __toString()
{
return $this->root->innertext();
}
function __get($name)
{
switch ($name) {
case 'outertext':
return $this->root->innertext();
case 'innertext':
return $this->root->innertext();
case 'plaintext':
return $this->root->text();
case 'charset':
return $this->_charset;
case 'target_charset':
return $this->_target_charset;
}
}
function childNodes($idx = -1)
{
return $this->root->childNodes($idx);
}
function firstChild()
{
return $this->root->first_child();
}
function lastChild()
{
return $this->root->last_child();
}
function createElement($name, $value = null)
{
return @str_get_html("<$name>$value</$name>")->firstChild();
}
function createTextNode($value)
{
return @end(str_get_html($value)->nodes);
}
function getElementById($id)
{
return $this->find("#$id", 0);
}
function getElementsById($id, $idx = null)
{
return $this->find("#$id", $idx);
}
function getElementByTagName($name)
{
return $this->find($name, 0);
}
function getElementsByTagName($name, $idx = -1)
{
return $this->find($name, $idx);
}
function loadFile()
{
$args = func_get_args();
$this->load_file($args);
}
}
=== Fast Velocity Minify ===
Contributors: Alignak
Tags: PHP Minify, Lighthouse, GTmetrix, Pingdom, Pagespeed, Merging, Minification, Optimization, Speed, Performance, FVM
Requires at least: 4.9
Requires PHP: 5.6
Stable tag: 3.2.2
Tested up to: 5.7.1
Text Domain: fast-velocity-minify
License: GPLv3 or later
License URI: http://www.gnu.org/licenses/gpl-3.0.html
Improve your speed score on GTmetrix, Pingdom Tools and Google PageSpeed Insights by adjusting your CSS and JS files (defer, async, minify, combine, etc), compressing HTML, simplifying fonts and a few more speed optimization options.
== Description ==
HTML, CSS & JS optimization plugin for developers and advanced users. Note you need to look into the HELP tab after installing the plugin and manually configure it for your site. Each site is different, so the default recommendations may or may not work for you and you will need to test and find out how to adjust your settings.
Minification is done on the frontend during the first uncached request. Once the first request is processed, any other pages that require the same set of CSS and JS files will be able to reuse the same generated static CSS or JS file.
If your cache is growing significantly, this could mean one of your CSS or JS files is dynamic and changes on every pageview. In that case, you would need to add the file to the ignore list, else the cache would grow indefinitely (because obviously the original files themselves are dynamic and when you minify, the plugin sees a different file).
Kindly read the HELP section after installing the plugin, about possible issues and how to solve them.
= Additional Optimization =
I can offer you additional `custom made` optimization on top of this plugin. If you would like to hire me, please visit my profile links for further information.
= WP-CLI Commands =
* Purge all caches: `wp fvm purge`
* Purge all caches on a network site: `wp --url=blog.example.com fvm purge`
* Purge all caches on the entire network (linux): `wp site list --field=url | xargs -n1 -I % wp --url=% fvm purge`
= How to customize the cache path ? =
You need a public directory to store and serve minified cache files. If you need to customize the path and url, you need to edit your `wp-config.php` and add both `define('FVM_DIR', '/path/to/example.com/your/public/directory');` and `define('FVM_URL', 'https://example.com/your/public/directory');` .
== Installation ==
1. Upload the plugin folder to the `/wp-content/plugins/` directory or upload the zip within WordPress
2. Activate the plugin through the `Plugins` menu in WordPress
3. Configure the options under: `Settings > Fast Velocity Minify` and that's it.
== Screenshots ==
1. The Settings page.
== Changelog ==
= 3.2.2 [2021.05.09] =
* added auto varnish cache purge for Cloudways
* fixed some JS files not being minified
= 3.2.1 [2021.05.07] =
* added support for custom cache location via wp-config.php constants
* changed the default cache directory to wp-content/cache
= 3.2.0 [2021.05.06] =
* fixed an issue where some files were not being minified
* better sourceMappingURL removal during minification
= 3.1.9 [2021.05.05] =
* fixed an issue with some base64 encoded fonts and icons becoming invalid
* changed @import CSS rules order according to specification (@import rules need to get processed first when minifying)
= 3.1.8 [2021.04.30] =
* fixed missing dynamic css/js urls
* fixed some relative static assets paths
* added auto disabling of FVM on Web Stories (AMP)
= 3.1.7 [2021.04.26] =
* more php notices fixes
= 3.1.6 [2021.04.25] =
* php notices fixes
* better http2 support
= 3.1.5 [2021.04.24] =
* added support for WP Cloudflare Super Page Cache plugin
* fixed support for LiteSpeed Cache purging
* changed the cache directory to the uploads directory (WP_Filesystem_Direct)
* deprecated CSS and JS merging as this is no longer recommended for HTTP/2 servers
* stop removing RSS feeds references on the header cleanup option
* changed some descriptions and updated the HELP section
* other bug fixes
= 3.1.4 [2021.01.11] =
* disable FVM update routines when a user runs wp-cli commands outside of the root directory
* database routine improvements for users with custom table prefixes
= 3.1.3 [2021.01.10] =
* Link preload headers improvement
= 3.1.2 [2021.01.09] =
* Fixed a PHP notice on wp-admin
= 3.1.1 [2021.01.09] =
* Added option to disable preload header
* Added support for the preload header importance attribute
* Better default settings for new installs
* Other bug fixes related to UTF-8 decoding and merging
= 3.1.0 [2021.01.06] =
* Added support for WP AMP by custom4web
* Fix for <code> and <pre> tags being minified
* Better HTML document detection for minification
= 3.0.9 [2021.01.04] =
* Added page caching purging support for Hummingbird and WP-Optimize from FVM
= 3.0.8 [2021.01.02] =
* Improved compatibility and better detection of dynamic CSS and JS files (files generated with PHP instead of being static)
= 3.0.7 [2021.01.02] =
* Fixed incorrect paths on subdirectory sites (inside merged CSS files)
= 3.0.6 [2021.01.01] =
* Adjusted the HELP tab settings
* Improved compatibility with CSS merging on WP Bakery
= 3.0.5 [2021.01.01] =
* Fixed the cache paths on Windows Servers
* Fixed incorrect file paths on subdirectory sites
* Fixed the CDN integration not replacing the domain name
* Fixed CSS font-display replacements
= 3.0.4 [2020.12.31] =
* Improved compatibility on CSS merging with optimole and similar services
* Fixed some PHP notices and other minor issues
= 3.0.3 [2020.12.29] =
* Prevent minification on XML content that do not trigger WordPress conditionals
* Added support for critical path positioning before the CSS files when Async mode is enabled
* Minor bugfixes
= 3.0.2 [2020.12.29] =
* Added option to preserve settings on uninstall
* Added option to inline all CSS (merging is still the recommended method)
* Added option to force HTTPS on the generated cache file urls
* Added an ignore list to the JS section (also imported from FVM 2 settings)
* Improved compatibility with FVM 2 (you still need to specify what JS paths you want to merge)
* Preserve the old FVM 2 settings on the database (will be removed on version 3.2)
= 3.0.1 [2020.12.27] =
* Added initial translation support under the "fast-velocity-minify" text domain.
= 3.0.0 [2020.12.26] =
* New version has been remade from scratch
* JS Optimization is disabled by default and requires manual configuration
* Third party scripts can now be delayed until user interaction, to improve the initial loading time
= 2.8.9 [2020.06.23] =
* new filter for wp hide compatibility
= 2.8.8 [2020.05.01] =
* bug fixes for woocommerce, which could result in 403 errors when adding to cart under certain cases
= 2.8.7 [2020.04.30] =
* fixed the sourceMappingURL removal regex introduced on 2.8.3 for js files and css files
= 2.8.6 [2020.04.30] =
* fixed an error notice on php
= 2.8.5 [2020.04.30] =
* bug fixes and some more minification default exclusions
= 2.8.4 [2020.04.24] =
* added frontend-builder-global-functions.js to the list of minification exclusions, but allowing merging (Divi Compatibility)
= 2.8.3 [2020.04.17] =
* Removed some options out of the autoload wp_option to avoid getting cached on the alloptions when using OPCache
* Removed the CDN purge option for WP Engine (not needed since FVM automatically does cache busting)
* Added support for Kinsta, Pagely, Pressidum, Savvii and Pantheon
* Better sourcemaps regex removal from minified css and js files
= 2.8.2 [2020.04.13] =
* Skip changing clip-path: url(#some-svg); to absolute urls during css minification
* Added a better cronjob duplicate cleanup task, when uninstalling the plugin
= 2.8.1 [2020.03.15] =
* added filter for the fvm_get_url function
= 2.8.0 [2020.03.10] =
* improved compatibility with Thrive Architect editor
* improved compatibility with Divi theme
= 2.7.9 [2020.02.18] =
* changed cache file names hash to longer names to avoid colisions on elementor plugin
= 2.7.8 [2020.02.06] =
* updated PHP Minify with full support for PHP 7.4
* added try, catch wrappers for merged javacript files with console log errors (instead of letting the browser stop execution on error)
* improved compatibility with windows servers
* improved compatibility for font paths with some themes
= 2.7.7 [2019.10.15] =
* added a capability check on the status page ajax request, which could show the cache file path when debug mode is enabled to subscribers
= 2.7.6 [2019.10.10] =
* bug fix release
= 2.7.5 [2019.10.09] =
* added support to "after" scripts added via wp_add_inline_script
= 2.7.4 [2019.08.18] =
* change to open JS/CSS files suspected of having PHP code via HTTP request, instead of reading the file directly from disk
= 2.7.3 [2019.07.29] =
* Beaver Builder compatibility fix
= 2.7.2 [2019.07.29] =
* fixed a PHP notice when WP_DEBUG mode is enabled on wordpress
* small improvements on google fonts merging
= 2.7.1 [2019.07.27] =
* fixed an AMP validation javascript error
= 2.7.0 [2019.07.23] =
* some score fixes when deferring to pagespeed is enabled
= 2.6.9 [2019.07.15] =
* custom cache path permissions fix (thanks to @fariazz)
= 2.6.8 [2019.07.06] =
* header preload fixes (thanks to @vandreev)
= 2.6.7 [2019.07.04] =
* added cache purging support for the swift cache plugin
* changed cache directory to the uploads directory for compatibility reasons
* better cache purging checks
= 2.6.6 [2019.06.20] =
* cache purging bug fixes
* php notice fixes
= 2.6.5 [2019.05.04] =
* fixed cache purging on Hyper Cache plugin
* removed support for WPFC (plugin author implemented a notice stating that FVM is incompatible with WPFC)
* improved the filtering engine for pagespeed insights on desktop
= 2.6.4 [2019.03.31] =
* fixed subdirectories permissions
= 2.6.3 [2019.03.30] =
* fixed another minor PHP notice
= 2.6.2 [2019.03.27] =
* fixed a PHP notice on urls with query strings that include arrays on keys or values
= 2.6.1 [2019.03.26] =
* fixed compatibility with the latest elementor plugin
* fixed adding duplicate cron jobs + existing duplicate cronjobs cleanup
* fixed duplicate "cache/cache" directory path
* changed the minimum PHP requirements to PHP 5.5
= 2.6.0 [2019.03.02] =
* fixed cache purging with the hypercache plugin
* fixed a bug with inline scripts and styles not showing up if there is no url for the enqueued handle
* changed the cache directory from the wp-content/uploads to wp-content/cache
* improved compatibility with page cache plugins and servers (purging FVM without purging the page cache should be fine now)
* added a daily cronjob, to delete public invalid cache files that are older than 3 months (your page cache should expire before this)
= 2.0.0 [2017.05.11] =
* version 2.x branch release
= 1.0 [2016.06.19] =
* Initial Release