Initial commit

This commit is contained in:
gustavooth
2026-07-23 22:56:30 -03:00
commit 22a1006598
1816 changed files with 410742 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
+34
View File
@@ -0,0 +1,34 @@
# Only allow direct access to specific Web-available files.
# Apache 2.2
<IfModule !mod_authz_core.c>
Order Deny,Allow
Deny from all
</IfModule>
# Apache 2.4
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
# Akismet CSS and JS
<FilesMatch "^(form\.js|akismet(-frontend|-admin)?\.js|akismet(-admin)?(-rtl)?\.css|inter\.css)$">
<IfModule !mod_authz_core.c>
Allow from all
</IfModule>
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
</FilesMatch>
# Akismet images
<FilesMatch "^(logo-a-2x\.png|akismet-refresh-logo\.svg|akismet-refresh-logo@2x\.png|arrow-left\.svg|akismet-activation-banner-elements\.png|copy\.svg)$">
<IfModule !mod_authz_core.c>
Allow from all
</IfModule>
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
</FilesMatch>
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the 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 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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.
@@ -0,0 +1,797 @@
body {
--akismet-color-charcoal: #272635;
--akismet-color-light-grey: #f6f7f7;
--akismet-color-mid-grey: #a7aaad;
--akismet-color-dark-grey: #646970;
--akismet-color-grey-80: #2c3338;
--akismet-color-grey-100: #101517;
--akismet-color-grey-border: #dcdcde;
--akismet-color-white: #fff;
--akismet-color-dark-green: #2d6a40;
--akismet-color-mid-green: #357b49;
--akismet-color-light-green: #4eb26a;
--akismet-color-mid-red: #e82c3f;
--akismet-color-light-blue: #256eff;
--akismet-color-notice-light-green: #dbf0e1;
--akismet-color-notice-dark-green: #69bf82;
--akismet-color-notice-light-red: #ffdbde;
--akismet-color-notice-dark-red: #ff6676;
--akismet-color-notice-yellow: #e5c133;
--akismet-color-page-bg: #fcfcfc;
--akismet-color-border: #e0e0e0;
--akismet-color-border-light: #f0f0f0;
--akismet-color-near-black: #1e1e1e;
--akismet-color-text-grey: #757575;
--akismet-color-icon: #666666;
--akismet-color-icon-hover: #333333;
}
/* UI components */
#akismet-plugin-container {
background-color: var(--akismet-color-page-bg);
border: 1px solid var(--akismet-color-border);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen-Sans', 'Ubuntu', 'Cantarell', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
}
#akismet-plugin-container a {
color: var(--akismet-color-mid-green);
}
#akismet-plugin-container a.akismet-button {
background-color: var(--akismet-color-mid-green);
color: var(--akismet-color-white);
}
#akismet-plugin-container button:focus-visible,
#akismet-plugin-container input:focus-visible {
border: 0;
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
#akismet-plugin-container a:focus-visible {
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
.akismet-masthead {
border-bottom: 1px solid var(--akismet-color-border-light);
box-shadow: none;
}
.akismet-masthead__logo {
margin: 20px 0;
}
.akismet-section-header {
box-shadow: none;
margin-bottom: 0;
}
.akismet-section-header__label {
color: var(--akismet-color-charcoal);
font-weight: 600;
padding-left: 0.2em;
}
.akismet-button,
.akismet-button:hover {
border: 0;
color: var(--akismet-color-white);
}
.akismet-button {
background-color: var(--akismet-color-mid-green);
}
.akismet-button:hover {
background-color: var(--akismet-color-dark-green);
}
.akismet-external-link {
display: inline-block;
}
.akismet-external-link::after {
content: "↗";
display: inline-block;
padding-left: 2px;
text-decoration: none;
vertical-align: middle;
}
/* Need this specificity to override the existing header rule */
.akismet-new-snapshot h3.akismet-new-snapshot__header {
background: none;
font-size: 13px;
color: var(--akismet-color-charcoal);
text-align: left;
text-transform: none;
}
.akismet-new-snapshot__number {
color: var(--akismet-color-charcoal);
display: block;
font-size: 32px;
font-weight: 400;
letter-spacing: -1px;
line-height: 1.5em;
text-align: left;
}
.akismet-new-snapshot li.akismet-new-snapshot__item {
color: var(--akismet-color-dark-grey);
font-size: 13px;
text-align: left;
text-transform: none;
}
.akismet-masthead__logo-link {
min-height: 50px;
}
.akismet-masthead__back-link-container {
margin-top: 16px;
margin-bottom: 2px;
}
/* Need this specificity to override the existing link rule */
#akismet-plugin-container a.akismet-masthead__back-link {
background-image: url(img/arrow-left.svg);
background-position: left;
background-repeat: no-repeat;
background-size: 16px;
color: var(--akismet-color-charcoal);
font-weight: 400;
padding-left: 20px;
text-decoration: none;
}
#akismet-plugin-container a.akismet-masthead__back-link:hover {
text-decoration: underline;
}
.akismet-new-snapshot__item {
border-top: 1px solid var(--akismet-color-border-light);
border-left: 1px solid var(--akismet-color-border-light);
padding: 1em;
}
.akismet-new-snapshot li:first-child {
border-left: none;
}
.akismet-new-snapshot__list {
display: flex;
margin-bottom: 0;
}
.akismet-new-snapshot__item {
flex: 1 0 33.33%;
margin-bottom: 0;
padding-left: 1.5em;
padding-right: 1.5em;
}
.akismet-new-snapshot__chart {
padding: 1em;
}
.akismet-stats-footer {
align-items: center;
border-radius: 0 0 7px 7px;
border-top: 1px solid var(--akismet-color-border-light);
display: flex;
justify-content: space-between;
outline-offset: -2px;
padding: 1em 1.5em;
text-decoration: none;
}
.akismet-stats-footer:hover {
text-decoration: underline;
}
.akismet-stats-footer:focus {
border-radius: 0 0 7px 7px;
box-shadow: none;
}
.akismet-stats-footer:focus-visible {
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
.akismet-box {
border: 0;
}
.akismet-box:not(:first-child) {
margin-top: 1rem;
}
.akismet-box,
.akismet-card {
border: 1px solid var(--akismet-color-border);
border-radius: 8px;
overflow: hidden;
}
.akismet-card {
margin: 16px auto 0 auto;
}
.akismet-lower {
padding-top: 0;
}
.akismet-lower .inside {
padding: 0;
}
.akismet-section-header__label {
margin: 0;
}
.akismet-settings__row {
border-bottom: 1px solid var(--akismet-color-border-light);
display: block;
padding: 1em 1.5em;
}
.akismet-settings__row-input {
margin-left: auto;
}
.akismet-settings__row-title {
font-weight: 500;
font-size: 1em;
margin: 0;
margin-bottom: 1em;
}
.akismet-settings__row-description {
margin-top: 0.5em;
}
.akismet-card-actions {
display: flex;
justify-content: flex-end;
padding: 1em;
}
.akismet-card-actions__secondary-action {
align-self: center;
margin-inline-end: auto;
margin-inline-start: 6px;
}
.akismet-settings__row label {
padding-bottom: 1em;
}
.akismet-settings__row-note {
font-size: 0.9em;
margin-top: 0.4em;
}
.akismet-settings__row-note abbr {
cursor: help;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
accent-color: var(--akismet-color-mid-green);
box-shadow: none;
flex-shrink: 0;
margin: 2px 0 0 0;
}
.akismet-settings__row input[type="checkbox"] {
margin-top: 1px;
vertical-align: top;
-webkit-appearance: checkbox;
}
.akismet-settings__row input[type="radio"] {
-webkit-appearance: radio;
}
/* Fix up misbehaving wp-admin styles in Chrome (from forms and colors stylesheets) */
.akismet-settings__row input[type="checkbox"]:checked:before {
content: '';
}
.akismet-settings__row input[type="radio"]:checked:before {
background: none;
}
.akismet-settings__row input[type="checkbox"]:checked:hover,
.akismet-settings__row input[type="radio"]:checked:hover {
accent-color: var(--akismet-color-mid-green);
}
.akismet-button:disabled {
background-color: var(--akismet-color-mid-grey);
color: var(--akismet-color-white);
cursor: arrow;
}
.akismet-awaiting-stats,
.akismet-account {
padding: 0 1rem 1rem 1rem;
margin: 0;
}
.akismet-account {
display: grid;
grid-template-columns: auto 1fr;
margin-inline-start: 2px;
margin-top: 0.25em;
padding-bottom: 0;
row-gap: 0.25em;
}
.akismet-account__label {
font-weight: 500;
padding-bottom: 1em;
padding-inline-end: 1em;
}
.akismet-account__value {
margin: 0;
padding-bottom: 1em;
}
.akismet-settings__row-input-label {
align-items: center;
display: flex;
}
.akismet-settings__row-label-text {
padding-left: 0.5em;
margin-top: 2px;
}
.akismet-alert {
border-left: 8px solid;
border-radius: 8px;
margin: 20px 0;
padding: 0.2em 1em;
}
.akismet-alert__heading {
font-size: 1em;
}
.akismet-alert.is-good {
background-color: var(--akismet-color-notice-light-green);
border-left-color: var(--akismet-color-notice-dark-green);
}
.akismet-alert.is-neutral {
background-color: var(--akismet-color-white);
border-left-color: var(--akismet-color-dark-grey);
}
.akismet-alert.is-bad {
background-color: var(--akismet-color-notice-light-red);
border-left-color: var(--akismet-color-notice-dark-red);
}
.akismet-alert.is-commercial {
background-color: var(--akismet-color-white);
border-color: var(--akismet-color-mid-grey);
border-bottom-width: 1px;
border-left-color: var(--akismet-color-notice-yellow);
display: flex;
padding-bottom: 1em;
}
#akismet-plugin-container .akismet-alert.is-good a,
#akismet-plugin-container .akismet-alert.is-bad a {
/* For better contrast - green isn't great */
color: var(--akismet-color-grey-80);
}
.akismet-alert-header {
font-size: 16px;
margin-bottom: 0.5em;
}
.akismet-alert-button-wrapper {
align-self: center;
margin-left: 2em;
min-width: 120px;
}
.akismet-alert-info {
text-wrap: pretty;
margin: 0.5em 0;
}
/* Setup */
.akismet-setup-instructions__heading {
font-size: 1.375rem;
font-weight: 700;
padding-block-end: 0;
}
h3.akismet-setup-instructions__subheading {
color: var(--akismet-color-dark-grey);
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
margin: 0 0 1.25rem;
padding-block-start: 1rem;
}
.akismet-setup-instructions__feature-list {
list-style: none;
margin: 1rem 0.5rem 1.5rem;
max-width: 640px;
padding: 0 1rem;
}
.akismet-setup-instructions__feature {
align-items: start;
display: flex;
margin-block-end: 1rem;
text-align: left;
}
.akismet-setup-instructions__icon {
height: 20px;
width: 20px;
}
.akismet-setup-instructions__body {
flex: 1;
padding-inline-start: 0.5rem;
}
.akismet-setup-instructions__title {
color: #1d2327;
font-size: 1rem;
font-weight: 600;
line-height: 1.3;
margin: 0;
text-align: left;
}
p.akismet-setup-instructions__text {
color: var(--akismet-color-grey-80);
font-size: 0.875rem;
line-height: 1.5;
margin: 0.25rem 0 0;
padding: 0;
text-align: left;
}
.akismet-setup-instructions__button,
.akismet-setup-instructions__button:hover,
.akismet-setup-instructions__button:visited {
font-size: 1rem;
margin-inline-start: 1.5rem;
}
.akismet-setup__connection {
background: var(--akismet-color-light-grey);
border: 1px solid var(--akismet-color-grey-border);
border-radius: 8px;
margin: 1rem 1rem 2rem 1rem;
padding: 1rem;
}
.akismet-setup__connection-action:not(:last-child) {
margin-bottom: 1rem;
}
.akismet-setup__connection-user {
display: flex;
}
.akismet-setup__connection-avatar {
align-items: center;
display: flex;
gap: 12px;
margin-bottom: 12px;
}
.akismet-setup__connection-avatar-image {
border-radius: 50%;
}
.akismet-setup__connection-account-name {
color: var(--akismet-color-charcoal);
font-size: 0.9rem;
overflow-wrap: anywhere;
}
.akismet-setup__connection-account-email {
margin-top: 0.1rem;
overflow-wrap: anywhere;
}
.akismet-setup__connection-action {
margin-left: auto;
}
.akismet-setup__connection-button {
text-align: center;
width: 100%;
}
p.akismet-setup__connection-action-intro,
p.akismet-setup__connection-action-description {
color: var(--akismet-color-dark-grey);
font-size: 0.875rem;
padding: 0;
}
p.akismet-setup__connection-action-intro {
margin: 0 0 1rem 0;
}
p.akismet-setup__connection-action-description {
margin: 1rem 0 0;
}
/* API key field with copy button */
.akismet-api-key-wrapper {
position: relative;
display: inline-flex;
align-items: center;
}
.akismet-api-key-wrapper input {
padding-right: 36px;
}
.akismet-api-key-copy {
position: absolute;
right: 4px;
background: none;
border: none;
cursor: pointer;
padding: 4px;
color: var(--akismet-color-icon);
display: flex;
align-items: center;
}
.akismet-api-key-copy:hover {
color: var(--akismet-color-icon-hover);
}
/* Setup - API key input */
.akismet-enter-api-key-box {
margin: 1.5rem 0;
}
.akismet-enter-api-key-box__reveal {
background: none;
border: 0;
color: var(--akismet-color-mid-green);
cursor: pointer;
text-decoration: underline;
}
.akismet-enter-api-key-box__form-wrapper {
display: none;
margin-top: 1.5rem;
}
.akismet-enter-api-key-box__input-wrapper {
box-sizing: border-box;
display: flex;
flex-wrap: nowrap;
padding: 0 1.5rem;
width: 100%;
}
.akismet-enter-api-key-box__key-input {
flex-grow: 1;
margin-right: 1rem;
}
h3.akismet-enter-api-key-box__header {
padding-top: 0;
padding-bottom: 1em;
text-align: left;
}
/* Notices > Activation (shown on edit-comments.php) */
#akismet-setup-prompt {
background: none;
border: none;
margin: 0;
padding: 0;
width: 100%;
}
.akismet-activate {
align-items: center;
/* background-image is defined via an inline style in class.akismet-admin.php */
background-color: var(--akismet-color-light-grey);
background-position: calc(100% - 1em) center;
background-repeat: no-repeat;
background-size: 140px;
border: 1px solid var(--akismet-color-mid-green);
border-left-width: 4px;
display: flex;
justify-content: space-between;
margin: 15px 0;
min-height: 60px;
overflow: hidden;
padding: 5px 160px 5px 5px;
position: relative;
}
.akismet-activate__button,
.akismet-activate__button:hover,
.akismet-activate__button:visited {
margin: 0 1em;
}
.akismet-activate__description {
color: var(--akismet-color-charcoal);
flex-grow: 1;
font-size: 16px;
font-weight: 600;
margin: 0 auto;
text-align: center;
text-wrap: pretty;
}
/* Compatible plugins section */
.akismet-compatible-plugins__content {
padding: 0 1.5em 1.5em 1.5em;
}
.akismet-compatible-plugins__intro {
margin: 0;
}
.akismet-compatible-plugins__section-header-label {
display: block;
}
.akismet-compatible-plugins__section-header-label-text {
padding-right: 0.5em;
}
.akismet-compatible-plugins__list {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
margin: 1.5em 0 1em 0;
padding: 0;
}
.akismet-compatible-plugins__card {
border: 1px solid var(--akismet-color-border-light);
border-radius: 4px;
padding: 1em;
display: flex;
align-items: center;
}
.akismet-compatible-plugins__card-logo {
padding: 0 1.5em 0 0;
object-fit: contain;
width: 36px;
height: 36px;
}
.akismet-compatible-plugins__card-detail {
display: flex;
flex: 1;
justify-content: space-between;
align-items: center;
}
.akismet-compatible-plugins__card-title {
font-size: 1.2em;
margin-top: 0;
margin-bottom: 0;
}
.akismet-compatible-plugins__docs {
margin-top: 0;
}
.akismet-compatible-plugins__show-more {
all: unset;
cursor: pointer;
display: flex;
justify-content: space-between;
position: relative;
width: 100%;
}
/* Generates the show/hide chevron */
.akismet-compatible-plugins__show-more::after {
align-self: center;
border-bottom: 2px solid black;
border-right: 2px solid black;
content: "";
height: 8px;
transform: rotate(45deg);
transition: transform 0.2s ease;
width: 8px;
}
.akismet-compatible-plugins__list.is-expanded + .akismet-compatible-plugins__show-more::after {
align-self: end;
transform: rotate(225deg);
}
/* Gutenberg medium breakpoint */
@media screen and (max-width: 782px) {
.akismet-new-snapshot__list {
display: block;
}
.akismet-new-snapshot__number {
float: right;
font-size: 20px;
font-weight: 500;
margin-top: -16px;
}
.akismet-new-snapshot__header {
font-size: 14px;
font-weight: 500;
}
.akismet-new-snapshot__text {
font-size: 12px;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
height: 24px;
width: 24px;
}
.akismet-settings__row-label-text {
padding-left: 0.8em;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
margin-top: 0;
}
.akismet-activate {
background-size: 120px;
padding-right: 134px;
}
.akismet-activate__button {
white-space: normal;
}
.akismet-activate__description {
font-size: 14px;
margin-right: 1em;
}
}
/* Gutenberg small breakpoint */
@media screen and (max-width: 600px) {
.akismet-compatible-plugins__list {
gap: 8px;
}
.akismet-activate__button,
.akismet-activate__button:hover {
font-size: 13px;
}
.akismet-activate__description {
display: none;
}
}
@@ -0,0 +1,69 @@
document.addEventListener( 'DOMContentLoaded', function() {
// Prevent aggressive iframe caching in Firefox
var statsIframe = document.getElementById( 'stats-iframe' );
if ( statsIframe ) {
statsIframe.contentWindow.location.href = statsIframe.src;
}
initCompatiblePluginsShowMoreToggle();
initApiKeyCopyButton();
} );
function initApiKeyCopyButton() {
const button = document.querySelector( '.akismet-api-key-copy' );
if ( ! button ) {
return;
}
button.addEventListener( 'click', function() {
const input = document.getElementById( 'key' );
if ( ! input || ! input.value ) {
return;
}
if ( navigator.clipboard && navigator.clipboard.writeText ) {
navigator.clipboard.writeText( input.value ).then( function() {
const svg = button.querySelector( 'svg' );
const original = svg.innerHTML;
svg.innerHTML = '<polyline points="20 6 9 17 4 12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
setTimeout( function() {
svg.innerHTML = original;
}, 2000 );
} ).catch( function() {
input.select();
document.execCommand( 'copy' );
} );
} else {
input.select();
document.execCommand( 'copy' );
}
} );
}
function initCompatiblePluginsShowMoreToggle() {
const section = document.querySelector( '.akismet-compatible-plugins' );
const list = document.querySelector( '.akismet-compatible-plugins__list' );
const button = document.querySelector( '.akismet-compatible-plugins__show-more' );
if ( ! section || ! list || ! button ) {
return;
}
function isElementInViewport( element ) {
const rect = element.getBoundingClientRect();
return rect.top >= 0 && rect.bottom <= window.innerHeight;
}
function toggleCards() {
list.classList.toggle( 'is-expanded' );
const isExpanded = list.classList.contains( 'is-expanded' );
button.textContent = isExpanded ? button.dataset.labelOpen : button.dataset.labelClosed;
button.setAttribute( 'aria-expanded', isExpanded.toString() );
if ( ! isExpanded && ! isElementInViewport( section ) ) {
section.scrollIntoView( { block: 'start' } );
}
}
button.addEventListener( 'click', toggleCards );
}
@@ -0,0 +1,393 @@
/**
* Observe how the user enters content into the comment form in order to determine whether it's a bot or not.
*
* Note that no actual input is being saved here, only counts and timings between events.
*/
( function() {
// Passive event listeners are guaranteed to never call e.preventDefault(),
// but they're not supported in all browsers. Use this feature detection
// to determine whether they're available for use.
var supportsPassive = false;
try {
var opts = Object.defineProperty( {}, 'passive', {
get : function() {
supportsPassive = true;
}
} );
window.addEventListener( 'testPassive', null, opts );
window.removeEventListener( 'testPassive', null, opts );
} catch ( e ) {}
function init() {
var input_begin = '';
var keydowns = {};
var lastKeyup = null;
var lastKeydown = null;
var keypresses = [];
var modifierKeys = [];
var correctionKeys = [];
var lastMouseup = null;
var lastMousedown = null;
var mouseclicks = [];
var mouseclickCoordinates = [];
var mousemoveTimer = null;
var lastMousemoveX = null;
var lastMousemoveY = null;
var mousemoveStart = null;
var mousemoves = [];
var touchmoveCountTimer = null;
var touchmoveCount = 0;
var lastTouchEnd = null;
var lastTouchStart = null;
var touchEvents = [];
var scrollCountTimer = null;
var scrollCount = 0;
var correctionKeyCodes = [ 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown' ];
var modifierKeyCodes = [ 'Shift', 'CapsLock' ];
var forms = document.querySelectorAll( 'form[method=post]' );
for ( var i = 0; i < forms.length; i++ ) {
var form = forms[i];
var formAction = form.getAttribute( 'action' );
// Ignore forms that POST directly to other domains; these could be things like payment forms.
if ( formAction ) {
// Check that the form is posting to an external URL, not a path.
if ( formAction.indexOf( 'http://' ) == 0 || formAction.indexOf( 'https://' ) == 0 ) {
if ( formAction.indexOf( 'http://' + window.location.hostname + '/' ) != 0 && formAction.indexOf( 'https://' + window.location.hostname + '/' ) != 0 ) {
continue;
}
}
}
form.addEventListener( 'submit', function () {
var ak_bkp = prepare_array_for_request( keypresses );
var ak_bmc = prepare_array_for_request( mouseclicks );
var ak_bte = prepare_array_for_request( touchEvents );
var ak_bmm = prepare_array_for_request( mousemoves );
var ak_bcc = prepare_array_for_request( mouseclickCoordinates );
var input_fields = {
// When did the user begin entering any input?
'bib': input_begin,
// When was the form submitted?
'bfs': Date.now(),
// How many keypresses did they make?
'bkpc': keypresses.length,
// How quickly did they press a sample of keys, and how long between them?
'bkp': ak_bkp,
// How quickly did they click the mouse, and how long between clicks?
'bmc': ak_bmc,
// How many mouseclicks did they make?
'bmcc': mouseclicks.length,
// When did they press modifier keys (like Shift or Capslock)?
'bmk': modifierKeys.join( ';' ),
// When did they correct themselves? e.g., press Backspace, or use the arrow keys to move the cursor back
'bck': correctionKeys.join( ';' ),
// How many times did they move the mouse?
'bmmc': mousemoves.length,
// How many times did they move around using a touchscreen?
'btmc': touchmoveCount,
// How many times did they scroll?
'bsc': scrollCount,
// How quickly did they perform touch events, and how long between them?
'bte': ak_bte,
// How many touch events were there?
'btec' : touchEvents.length,
// How quickly did they move the mouse, and how long between moves?
'bmm' : ak_bmm,
// Click coordinates
'bcc' : ak_bcc
};
var akismet_field_prefix = 'ak_';
if ( this.getElementsByClassName ) {
// Check to see if we've used an alternate field name prefix. We store this as an attribute of the container around some of the Akismet fields.
var possible_akismet_containers = this.getElementsByClassName( 'akismet-fields-container' );
for ( var containerIndex = 0; containerIndex < possible_akismet_containers.length; containerIndex++ ) {
var container = possible_akismet_containers.item( containerIndex );
if ( container.getAttribute( 'data-prefix' ) ) {
akismet_field_prefix = container.getAttribute( 'data-prefix' );
break;
}
}
}
for ( var field_name in input_fields ) {
var field = document.createElement( 'input' );
field.setAttribute( 'type', 'hidden' );
field.setAttribute( 'name', akismet_field_prefix + field_name );
field.setAttribute( 'value', input_fields[ field_name ] );
this.appendChild( field );
}
}, supportsPassive ? { passive: true } : false );
form.addEventListener( 'keydown', function ( e ) {
// If you hold a key down, some browsers send multiple keydown events in a row.
// Ignore any keydown events for a key that hasn't come back up yet.
if ( e.key in keydowns ) {
return;
}
var keydownTime = ( new Date() ).getTime();
keydowns[ e.key ] = [ keydownTime ];
if ( ! input_begin ) {
input_begin = keydownTime;
}
// In some situations, we don't want to record an interval since the last keypress -- for example,
// on the first keypress, or on a keypress after focus has changed to another element. Normally,
// we want to record the time between the last keyup and this keydown. But if they press a
// key while already pressing a key, we want to record the time between the two keydowns.
var lastKeyEvent = Math.max( lastKeydown, lastKeyup );
if ( lastKeyEvent ) {
keydowns[ e.key ].push( keydownTime - lastKeyEvent );
}
lastKeydown = keydownTime;
}, supportsPassive ? { passive: true } : false );
form.addEventListener( 'keyup', function ( e ) {
if ( ! ( e.key in keydowns ) ) {
// This key was pressed before this script was loaded, or a mouseclick happened during the keypress, or...
return;
}
var keyupTime = ( new Date() ).getTime();
if ( 'TEXTAREA' === e.target.nodeName || 'INPUT' === e.target.nodeName ) {
if ( -1 !== modifierKeyCodes.indexOf( e.key ) ) {
modifierKeys.push( keypresses.length - 1 );
} else if ( -1 !== correctionKeyCodes.indexOf( e.key ) ) {
correctionKeys.push( keypresses.length - 1 );
} else {
// ^ Don't record timings for keys like Shift or backspace, since they
// typically get held down for longer than regular typing.
var keydownTime = keydowns[ e.key ][0];
var keypress = [];
// Keypress duration.
keypress.push( keyupTime - keydownTime );
// Amount of time between this keypress and the previous keypress.
if ( keydowns[ e.key ].length > 1 ) {
keypress.push( keydowns[ e.key ][1] );
}
keypresses.push( keypress );
}
}
delete keydowns[ e.key ];
lastKeyup = keyupTime;
}, supportsPassive ? { passive: true } : false );
form.addEventListener( "focusin", function ( e ) {
lastKeydown = null;
lastKeyup = null;
keydowns = {};
}, supportsPassive ? { passive: true } : false );
form.addEventListener( "focusout", function ( e ) {
lastKeydown = null;
lastKeyup = null;
keydowns = {};
}, supportsPassive ? { passive: true } : false );
}
document.addEventListener( 'mousedown', function ( e ) {
lastMousedown = ( new Date() ).getTime();
var mouseclickCoordinate = [];
var rect = e.target.getBoundingClientRect();
var relativeX = e.clientX - rect.left;
var relativeY = e.clientY - rect.top;
// Pixel offset of the click within the target element.
mouseclickCoordinate.push( Math.round( relativeX ) );
mouseclickCoordinate.push( Math.round( relativeY ) );
// Percentage offset of the click within the target element.
mouseclickCoordinate.push( rect.width > 0 ? Math.round( relativeX / rect.width * 100 ) : 0 );
mouseclickCoordinate.push( rect.height > 0 ? Math.round( relativeY / rect.height * 100 ) : 0 );
mouseclickCoordinates.push( mouseclickCoordinate );
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'mouseup', function ( e ) {
if ( ! lastMousedown ) {
// If the mousedown happened before this script was loaded, but the mouseup happened after...
return;
}
var now = ( new Date() ).getTime();
var mouseclick = [];
mouseclick.push( now - lastMousedown );
if ( lastMouseup ) {
mouseclick.push( lastMousedown - lastMouseup );
}
mouseclicks.push( mouseclick );
lastMouseup = now;
// If the mouse has been clicked, don't record this time as an interval between keypresses.
lastKeydown = null;
lastKeyup = null;
keydowns = {};
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'mousemove', function ( e ) {
if ( mousemoveTimer ) {
clearTimeout( mousemoveTimer );
mousemoveTimer = null;
}
else {
mousemoveStart = ( new Date() ).getTime();
lastMousemoveX = e.offsetX;
lastMousemoveY = e.offsetY;
}
mousemoveTimer = setTimeout( function ( theEvent, originalMousemoveStart ) {
var now = ( new Date() ).getTime() - 500; // To account for the timer delay.
var mousemove = [];
mousemove.push( now - originalMousemoveStart );
mousemove.push(
Math.round(
Math.sqrt(
Math.pow( theEvent.offsetX - lastMousemoveX, 2 ) +
Math.pow( theEvent.offsetY - lastMousemoveY, 2 )
)
)
);
if ( mousemove[1] > 0 ) {
// If there was no measurable distance, then it wasn't really a move.
mousemoves.push( mousemove );
}
mousemoveStart = null;
mousemoveTimer = null;
}, 500, e, mousemoveStart );
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'touchmove', function ( e ) {
if ( touchmoveCountTimer ) {
clearTimeout( touchmoveCountTimer );
}
touchmoveCountTimer = setTimeout( function () {
touchmoveCount++;
}, 500 );
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'touchstart', function ( e ) {
lastTouchStart = ( new Date() ).getTime();
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'touchend', function ( e ) {
if ( ! lastTouchStart ) {
// If the touchstart happened before this script was loaded, but the touchend happened after...
return;
}
var now = ( new Date() ).getTime();
var touchEvent = [];
touchEvent.push( now - lastTouchStart );
if ( lastTouchEnd ) {
touchEvent.push( lastTouchStart - lastTouchEnd );
}
touchEvents.push( touchEvent );
lastTouchEnd = now;
// Don't record this time as an interval between keypresses.
lastKeydown = null;
lastKeyup = null;
keydowns = {};
}, supportsPassive ? { passive: true } : false );
document.addEventListener( 'scroll', function ( e ) {
if ( scrollCountTimer ) {
clearTimeout( scrollCountTimer );
}
scrollCountTimer = setTimeout( function () {
scrollCount++;
}, 500 );
}, supportsPassive ? { passive: true } : false );
}
/**
* For the timing/coordinate data that is collected, don't send more than `limit` data points in the request.
* Choose a random slice and send those, with each batch separated by semicolons and the items in each batch
* separated by commas.
*/
function prepare_array_for_request( a, limit ) {
if ( ! limit ) {
limit = 100;
}
var rv = '';
if ( a.length > 0 ) {
var random_starting_point = Math.max( 0, Math.floor( Math.random() * a.length - limit ) );
for ( var i = 0; i < limit && i < a.length; i++ ) {
var entry = a[ random_starting_point + i ];
rv += entry.join( ',' ) + ';';
}
}
return rv;
}
if ( document.readyState !== 'loading' ) {
init();
} else {
document.addEventListener( 'DOMContentLoaded', init );
}
})();
+462
View File
@@ -0,0 +1,462 @@
.wp-admin.jetpack_page_akismet-key-config, .wp-admin.settings_page_akismet-key-config {
background-color:#f3f6f8;
}
#submitted-on {
position: relative;
}
#the-comment-list .author .akismet-user-comment-count {
display: inline;
}
#the-comment-list .author a span {
text-decoration: none;
color: #999;
}
#the-comment-list .author a span.akismet-span-link {
text-decoration: inherit;
color: inherit;
}
#the-comment-list .akismet_remove_url {
margin-left: 3px;
color: #999;
padding: 2px 3px 2px 0;
}
#the-comment-list .akismet_remove_url:hover {
color: #A7301F;
font-weight: bold;
padding: 2px 2px 2px 0;
}
#dashboard_recent_comments .akismet-status {
display: none;
}
.akismet-status {
float: right;
}
.akismet-status a {
color: #AAA;
font-style: italic;
}
table.comments td.comment p a {
text-decoration: underline;
}
table.comments td.comment p a:after {
content: attr(href);
color: #aaa;
display: inline-block; /* Show the URL without the link's underline extending under it. */
padding: 0 1ex; /* Because it's inline block, we can't just use spaces in the content: attribute to separate it from the link text. */
}
.mshot-arrow {
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid #5C5C5C;
position: absolute;
left: -6px;
top: 91px;
}
.mshot-container {
background: #5C5C5C;
position: absolute;
top: -94px;
padding: 7px;
width: 450px;
height: 338px;
z-index: 20000;
border-radius: 6px;
}
.akismet-mshot {
position: absolute;
z-index: 100;
}
.akismet-mshot .mshot-image {
margin: 0;
height: 338px;
width: 450px;
}
.checkforspam {
display: inline-block !important;
}
.checkforspam-spinner {
display: inline-block;
margin-top: 7px;
}
.akismet-right {
float: right;
}
.akismet-card .akismet-right {
margin: 1em 0;
}
.akismet-new-snapshot {
margin-top: 1em;
text-align: center;
background: #fff;
}
.akismet-new-snapshot h3 {
background: #f5f5f5;
color: #888;
font-size: 11px;
margin: 0;
}
.akismet-new-snapshot ul li {
color: #999;
font-size: 11px;
text-transform: uppercase;
box-sizing: border-box;
}
.akismet-settings th:first-child {
vertical-align: top;
padding-top: 15px;
}
.akismet-settings th.akismet-api-key {
vertical-align: middle;
padding-top: 0;
}
.akismet-settings span.akismet-note {
float: left;
padding-left: 23px;
font-size: 75%;
margin-top: -10px;
}
.jetpack_page_akismet-key-config #wpcontent, .settings_page_akismet-key-config #wpcontent {
padding-left: 0;
}
.akismet-masthead {
background-color:#fff;
text-align:center;
box-shadow:0 1px 0 rgba(200,215,225,0.5),0 1px 2px #e9eff3
}
@media (max-width: 45rem) {
.akismet-masthead {
padding:0 1.25rem
}
}
.akismet-masthead__inside-container {
padding:.375rem 0;
margin:0 auto;
width:100%;
max-width:45rem;
text-align: left;
}
.akismet-masthead__logo-container {
padding:.3125rem 0 0
}
.akismet-masthead__logo-link {
display:inline-block;
outline:none;
vertical-align:middle
}
.akismet-masthead__logo-link:focus {
line-height:0;
box-shadow:0 0 0 2px #78dcfa
}
.akismet-masthead__logo-link+code {
margin:0 10px;
padding:5px 9px;
border-radius:2px;
background:#e6ecf1;
color:#647a88
}
.akismet-masthead__links {
display:flex;
flex-flow:row wrap;
flex:2 50%;
justify-content:flex-end;
margin:0
}
@media (max-width: 480px) {
.akismet-masthead__links {
padding-right:.625rem
}
}
.akismet-masthead__link-li {
margin:0;
padding:0
}
.akismet-masthead__link {
font-style:normal;
color:#0087be;
padding:.625rem;
display:inline-block
}
.akismet-masthead__link:visited {
color:#0087be
}
.akismet-masthead__link:active,.akismet-masthead__link:hover {
color:#00aadc
}
.akismet-masthead__link:hover {
text-decoration:underline
}
.akismet-masthead__link .dashicons {
display:none
}
@media (max-width: 480px) {
.akismet-masthead__link:hover,.akismet-masthead__link:active {
text-decoration:none
}
.akismet-masthead__link .dashicons {
display:block;
font-size:1.75rem
}
.akismet-masthead__link span+span {
display:none
}
}
.akismet-masthead__link-li:last-of-type .akismet-masthead__link {
padding-right:0
}
.akismet-lower {
margin: 0 auto;
text-align: left;
max-width: 45rem;
padding: 1.5rem;
}
.akismet-lower .notice {
margin-bottom: 2rem;
}
.akismet-card {
margin-top: 1rem;
margin-bottom: 0;
position: relative;
box-sizing: border-box;
background: white;
}
.akismet-card:after, .akismet-card .inside:after, .akismet-masthead__logo-container:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.akismet-card .inside {
padding: 1.5rem;
padding-top: 1rem;
}
.akismet-card .akismet-card-actions {
margin-top: 1rem;
}
.jetpack_page_akismet-key-config .update-nag, .settings_page_akismet-key-config .update-nag {
display: none;
}
.akismet-masthead .akismet-right {
line-height: 2.125rem;
font-size: 0.9rem;
}
.akismet-box {
box-sizing: border-box;
background: white;
border: 1px solid rgba(200, 215, 225, 0.5);
}
.akismet-box h2, .akismet-box h3 {
padding: 1.5rem 1.5rem .5rem 1.5rem;
margin: 0;
}
.akismet-box p {
padding: 0 1.5rem 1.5rem 1.5rem;
margin: 0;
}
.akismet-box p:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.akismet-box .akismet-right {
padding-right: 1.5rem;
}
.akismet-boxes .akismet-box {
margin-bottom: 0;
padding: 0;
margin-top: -1px;
}
.akismet-boxes .akismet-box:last-child {
margin-bottom: 1.5rem;
}
.akismet-boxes .akismet-box:first-child {
margin-top: 1.5rem;
}
.akismet-box .centered {
text-align: center;
}
.akismet-button, .akismet-button:hover, .akismet-button:visited {
background: white;
border-color: #c8d7e1;
border-style: solid;
border-width: 1px 1px 2px;
color: #2e4453;
cursor: pointer;
display: inline-block;
margin: 0;
outline: 0;
overflow: hidden;
font-size: 14px;
font-weight: 500;
text-overflow: ellipsis;
text-decoration: none;
vertical-align: top;
box-sizing: border-box;
line-height: 21px;
border-radius: 4px;
padding: 7px 14px 9px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.akismet-button:hover {
border-color: #a8bece;
}
.akismet-button:active {
border-width: 2px 1px 1px;
}
.akismet-is-primary, .akismet-is-primary:hover, .akismet-is-primary:visited {
background: #00aadc;
border-color: #0087be;
color: white;
}
.akismet-is-primary:hover, .akismet-is-primary:focus {
border-color: #005082;
}
.akismet-is-primary:hover {
border-color: #005082;
}
.akismet-section-header {
position: relative;
margin: 0 auto 0.625rem auto;
padding: 1rem;
box-sizing: border-box;
box-shadow: 0 0 0 1px rgba(200, 215, 225, 0.5), 0 1px 2px #e9eff3;
background: #ffffff;
width: 100%;
padding-top: 0.6875rem;
padding-bottom: 0.6875rem;
display: flex;
}
.akismet-section-header__label {
display: flex;
align-items: center;
flex-grow: 1;
line-height: 1.75rem;
position: relative;
font-size: 0.875rem;
color: #4f748e;
}
.akismet-section-header__actions {
line-height: 1.75rem;
}
.akismet-setup-instructions form {
padding-bottom: 1.5rem;
}
.akismet-setup-instructions > a.akismet-button {
display: inline-block;
margin-bottom: 1.5rem;
}
div.error.akismet-usage-limit-alert {
padding: 25px 45px 25px 15px;
display: flex;
align-items: center;
}
#akismet-plugin-container .akismet-usage-limit-alert {
margin: 0 auto 0.625rem auto;
box-sizing: border-box;
box-shadow: 0 0 0 1px rgba(200, 215, 225, 0.5), 0 1px 2px #e9eff3;
border: none;
border-left: 4px solid #d63638;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo {
width: 38px;
min-width: 38px;
height: 38px;
border-radius: 20px;
margin-right: 18px;
background: black;
position: relative;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo img {
position: absolute;
width: 22px;
left: 8px;
top: 10px;
}
.akismet-usage-limit-alert .akismet-usage-limit-text {
flex-grow: 1;
margin-right: 18px;
}
.akismet-usage-limit-alert h3 {
line-height: 1.3;
margin: 0;
}
.akismet-usage-limit-alert .akismet-usage-limit-cta {
border-color: none;
text-align: right;
}
#akismet-plugin-container .akismet-usage-limit-cta a {
color: #d63638;
background: #fafafa;
}
@media (max-width: 550px) {
div.error.akismet-usage-limit-alert {
display: block;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo,
.akismet-usage-limit-alert .akismet-usage-limit-text {
margin-bottom: 15px;
}
.akismet-usage-limit-alert .akismet-usage-limit-cta {
text-align: left;
}
}
+397
View File
@@ -0,0 +1,397 @@
jQuery( function ( $ ) {
var mshotRemovalTimer = null;
var mshotRetryTimer = null;
var mshotTries = 0;
var mshotRetryInterval = 1000;
var mshotEnabledLinkSelector = 'a[id^="author_comment_url"], tr.pingback td.column-author a:first-of-type, td.comment p a';
var preloadedMshotURLs = [];
$('.akismet-status').each(function () {
var thisId = $(this).attr('commentid');
$(this).prependTo('#comment-' + thisId + ' .column-comment');
});
$('.akismet-user-comment-count').each(function () {
var thisId = $(this).attr('commentid');
$(this).insertAfter('#comment-' + thisId + ' .author strong:first').show();
});
akismet_enable_comment_author_url_removal();
$( '#the-comment-list' ).on( 'click', '.akismet_remove_url', function () {
var thisId = $(this).attr('commentid');
var data = {
action: 'comment_author_deurl',
_wpnonce: WPAkismet.comment_author_url_nonce,
id: thisId
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
beforeSend: function () {
// Removes "x" link
$("a[commentid='"+ thisId +"']").hide();
// Show temp status
$("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Removing...'] ) );
},
success: function (response) {
if (response) {
// Show status/undo link
$("#author_comment_url_"+ thisId)
.attr('cid', thisId)
.addClass('akismet_undo_link_removal')
.html(
$( '<span/>' ).text( WPAkismet.strings['URL removed'] )
)
.append( ' ' )
.append(
$( '<span/>' )
.text( WPAkismet.strings['(undo)'] )
.addClass( 'akismet-span-link' )
);
}
}
});
return false;
}).on( 'click', '.akismet_undo_link_removal', function () {
var thisId = $(this).attr('cid');
var thisUrl = $(this).attr('href');
var data = {
action: 'comment_author_reurl',
_wpnonce: WPAkismet.comment_author_url_nonce,
id: thisId,
url: thisUrl
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
beforeSend: function () {
// Show temp status
$("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Re-adding...'] ) );
},
success: function (response) {
if (response) {
// Add "x" link
$("a[commentid='"+ thisId +"']").show();
// Show link. Core strips leading http://, so let's do that too.
$("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').text( thisUrl.replace( /^http:\/\/(www\.)?/ig, '' ) );
}
}
});
return false;
});
// Show a preview image of the hovered URL. Applies to author URLs and URLs inside the comments.
if ( "enable_mshots" in WPAkismet && WPAkismet.enable_mshots ) {
$( '#the-comment-list' ).on( 'mouseover', mshotEnabledLinkSelector, function () {
clearTimeout( mshotRemovalTimer );
if ( $( '.akismet-mshot' ).length > 0 ) {
if ( $( '.akismet-mshot:first' ).data( 'link' ) == this ) {
// The preview is already showing for this link.
return;
}
else {
// A new link is being hovered, so remove the old preview.
$( '.akismet-mshot' ).remove();
}
}
clearTimeout( mshotRetryTimer );
var linkUrl = $( this ).attr( 'href' );
if ( preloadedMshotURLs.indexOf( linkUrl ) !== -1 ) {
// This preview image was already preloaded, so begin with a retry URL so the user doesn't see the placeholder image for the first second.
mshotTries = 2;
}
else {
mshotTries = 1;
}
var mShot = $( '<div class="akismet-mshot mshot-container"><div class="mshot-arrow"></div><img src="' + akismet_mshot_url( linkUrl, mshotTries ) + '" width="450" height="338" class="mshot-image" /></div>' );
mShot.data( 'link', this );
mShot.data( 'url', linkUrl );
mShot.find( 'img' ).on( 'load', function () {
$( '.akismet-mshot' ).data( 'pending-request', false );
} );
var offset = $( this ).offset();
mShot.offset( {
left : Math.min( $( window ).width() - 475, offset.left + $( this ).width() + 10 ), // Keep it on the screen if the link is near the edge of the window.
top: offset.top + ( $( this ).height() / 2 ) - 101 // 101 = top offset of the arrow plus the top border thickness
} );
$( 'body' ).append( mShot );
mshotRetryTimer = setTimeout( retryMshotUntilLoaded, mshotRetryInterval );
} ).on( 'mouseout', 'a[id^="author_comment_url"], tr.pingback td.column-author a:first-of-type, td.comment p a', function () {
mshotRemovalTimer = setTimeout( function () {
clearTimeout( mshotRetryTimer );
$( '.akismet-mshot' ).remove();
}, 200 );
} );
var preloadDelayTimer = null;
$( window ).on( 'scroll resize', function () {
clearTimeout( preloadDelayTimer );
preloadDelayTimer = setTimeout( preloadMshotsInViewport, 500 );
} );
preloadMshotsInViewport();
}
/**
* The way mShots works is if there was no screenshot already recently generated for the URL,
* it returns a "loading..." image for the first request. Then, some subsequent request will
* receive the actual screenshot, but it's unknown how long it will take. So, what we do here
* is continually re-request the mShot, waiting a second after every response until we get the
* actual screenshot.
*/
function retryMshotUntilLoaded() {
clearTimeout( mshotRetryTimer );
var imageWidth = $( '.akismet-mshot img' ).get(0).naturalWidth;
if ( imageWidth == 0 ) {
// It hasn't finished loading yet the first time. Check again shortly.
setTimeout( retryMshotUntilLoaded, mshotRetryInterval );
}
else if ( imageWidth == 400 ) {
// It loaded the preview image.
if ( mshotTries == 20 ) {
// Give up if we've requested the mShot 20 times already.
return;
}
if ( ! $( '.akismet-mshot' ).data( 'pending-request' ) ) {
$( '.akismet-mshot' ).data( 'pending-request', true );
mshotTries++;
$( '.akismet-mshot .mshot-image' ).attr( 'src', akismet_mshot_url( $( '.akismet-mshot' ).data( 'url' ), mshotTries ) );
}
mshotRetryTimer = setTimeout( retryMshotUntilLoaded, mshotRetryInterval );
}
else {
// All done.
}
}
function preloadMshotsInViewport() {
var windowWidth = $( window ).width();
var windowHeight = $( window ).height();
$( '#the-comment-list' ).find( mshotEnabledLinkSelector ).each( function ( index, element ) {
var linkUrl = $( this ).attr( 'href' );
// Don't attempt to preload an mshot for a single link twice.
if ( preloadedMshotURLs.indexOf( linkUrl ) !== -1 ) {
// The URL is already preloaded.
return true;
}
if ( typeof element.getBoundingClientRect !== 'function' ) {
// The browser is too old. Return false to stop this preloading entirely.
return false;
}
var rect = element.getBoundingClientRect();
if ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= windowHeight && rect.right <= windowWidth ) {
akismet_preload_mshot( linkUrl );
$( this ).data( 'akismet-mshot-preloaded', true );
}
} );
}
$( '.checkforspam.enable-on-load' ).on( 'click', function( e ) {
if ( $( this ).hasClass( 'ajax-disabled' ) ) {
// Akismet hasn't been configured yet. Allow the user to proceed to the button's link.
return;
}
e.preventDefault();
if ( $( this ).hasClass( 'button-disabled' ) ) {
window.location.href = $( this ).data( 'success-url' ).replace( '__recheck_count__', 0 ).replace( '__spam_count__', 0 );
return;
}
$('.checkforspam').addClass('button-disabled').addClass( 'checking' );
$('.checkforspam-spinner').addClass( 'spinner' ).addClass( 'is-active' );
akismet_check_for_spam(0, 100);
}).removeClass( 'button-disabled' );
var spam_count = 0;
var recheck_count = 0;
function akismet_check_for_spam(offset, limit) {
var check_for_spam_buttons = $( '.checkforspam' );
var nonce = check_for_spam_buttons.data( 'nonce' );
// We show the percentage complete down to one decimal point so even queues with 100k
// pending comments will show some progress pretty quickly.
var percentage_complete = Math.round( ( recheck_count / check_for_spam_buttons.data( 'pending-comment-count' ) ) * 1000 ) / 10;
// Update the progress counter on the "Check for Spam" button.
$( '.checkforspam' ).text( check_for_spam_buttons.data( 'progress-label' ).replace( '%1$s', percentage_complete ) );
$.post(
ajaxurl,
{
'action': 'akismet_recheck_queue',
'offset': offset,
'limit': limit,
'nonce': nonce
},
function(result) {
if ( 'error' in result ) {
// An error is only returned in the case of a missing nonce, so we don't need the actual error message.
window.location.href = check_for_spam_buttons.data( 'failure-url' );
return;
}
recheck_count += result.counts.processed;
spam_count += result.counts.spam;
if (result.counts.processed < limit) {
window.location.href = check_for_spam_buttons.data( 'success-url' ).replace( '__recheck_count__', recheck_count ).replace( '__spam_count__', spam_count );
}
else {
// Account for comments that were caught as spam and moved out of the queue.
akismet_check_for_spam(offset + limit - result.counts.spam, limit);
}
}
);
}
if ( "start_recheck" in WPAkismet && WPAkismet.start_recheck ) {
$( '.checkforspam:first' ).click();
}
if ( typeof MutationObserver !== 'undefined' ) {
// Dynamically add the "X" next the the author URL links when a comment is quick-edited.
var comment_list_container = document.getElementById( 'the-comment-list' );
if ( comment_list_container ) {
var observer = new MutationObserver( function ( mutations ) {
for ( var i = 0, _len = mutations.length; i < _len; i++ ) {
if ( mutations[i].addedNodes.length > 0 ) {
akismet_enable_comment_author_url_removal();
// Once we know that we'll have to check for new author links, skip the rest of the mutations.
break;
}
}
} );
observer.observe( comment_list_container, { attributes: true, childList: true, characterData: true } );
}
}
function akismet_enable_comment_author_url_removal() {
$( '#the-comment-list' )
.find( 'tr.comment, tr[id ^= "comment-"]' )
.find( '.column-author a[href^="http"]:first' ) // Ignore mailto: links, which would be the comment author's email.
.each(function () {
if ( $( this ).parent().find( '.akismet_remove_url' ).length > 0 ) {
return;
}
var linkHref = $(this).attr( 'href' );
// Ignore any links to the current domain, which are diagnostic tools, like the IP address link
// or any other links another plugin might add.
var currentHostParts = document.location.href.split( '/' );
var currentHost = currentHostParts[0] + '//' + currentHostParts[2] + '/';
if ( linkHref.indexOf( currentHost ) != 0 ) {
var thisCommentId = $(this).parents('tr:first').attr('id').split("-");
$(this)
.attr("id", "author_comment_url_"+ thisCommentId[1])
.after(
$( '<a href="#" class="akismet_remove_url">x</a>' )
.attr( 'commentid', thisCommentId[1] )
.attr( 'title', WPAkismet.strings['Remove this URL'] )
);
}
});
}
/**
* Generate an mShot URL if given a link URL.
*
* @param string linkUrl
* @param int retry If retrying a request, the number of the retry.
* @return string The mShot URL;
*/
function akismet_mshot_url( linkUrl, retry ) {
var mshotUrl = '//s0.wp.com/mshots/v1/' + encodeURIComponent( linkUrl ) + '?w=900';
if ( retry > 1 ) {
mshotUrl += '&r=' + encodeURIComponent( retry );
}
mshotUrl += '&source=akismet';
return mshotUrl;
}
/**
* Begin loading an mShot preview of a link.
*
* @param string linkUrl
*/
function akismet_preload_mshot( linkUrl ) {
var img = new Image();
img.src = akismet_mshot_url( linkUrl );
preloadedMshotURLs.push( linkUrl );
}
$( '.akismet-could-be-primary' ).each( function () {
var form = $( this ).closest( 'form' );
form.data( 'initial-state', form.serialize() );
form.on( 'change keyup', function () {
var self = $( this );
var submit_button = self.find( '.akismet-could-be-primary' );
if ( self.serialize() != self.data( 'initial-state' ) ) {
submit_button.addClass( 'akismet-is-primary' );
}
else {
submit_button.removeClass( 'akismet-is-primary' );
}
} );
} );
/**
* Shows the Enter API key form
*/
$( '.akismet-enter-api-key-box__reveal' ).on( 'click', function ( e ) {
e.preventDefault();
var div = $( '.akismet-enter-api-key-box__form-wrapper' );
div.show();
div.find( 'input[name=key]' ).focus();
$( this ).hide();
} );
});
@@ -0,0 +1,68 @@
/* NOAUTORTL */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-Regular.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-Regular.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-Italic.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-Italic.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-Medium.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-Medium.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-MediumItalic.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-MediumItalic.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-SemiBold.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-SemiBold.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-SemiBoldItalic.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-SemiBoldItalic.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-Bold.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-Bold.woff?v=3.19") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url("https://s0.wp.com/i/fonts/inter/Inter-BoldItalic.woff2?v=3.19") format("woff2"),
url("https://s0.wp.com/i/fonts/inter/Inter-BoldItalic.woff?v=3.19") format("woff");
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"></path></svg>

After

Width:  |  Height:  |  Size: 199 B

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M5 4.5h11a.5.5 0 0 1 .5.5v11a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V5a.5.5 0 0 1 .5-.5ZM3 5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm17 3v10.75c0 .69-.56 1.25-1.25 1.25H6v1.5h12.75a2.75 2.75 0 0 0 2.75-2.75V8H20Z"/>
</svg>

After

Width:  |  Height:  |  Size: 418 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 904 B

@@ -0,0 +1,799 @@
/* This file was automatically generated on Apr 09 2026 23:28:55 */
body {
--akismet-color-charcoal: #272635;
--akismet-color-light-grey: #f6f7f7;
--akismet-color-mid-grey: #a7aaad;
--akismet-color-dark-grey: #646970;
--akismet-color-grey-80: #2c3338;
--akismet-color-grey-100: #101517;
--akismet-color-grey-border: #dcdcde;
--akismet-color-white: #fff;
--akismet-color-dark-green: #2d6a40;
--akismet-color-mid-green: #357b49;
--akismet-color-light-green: #4eb26a;
--akismet-color-mid-red: #e82c3f;
--akismet-color-light-blue: #256eff;
--akismet-color-notice-light-green: #dbf0e1;
--akismet-color-notice-dark-green: #69bf82;
--akismet-color-notice-light-red: #ffdbde;
--akismet-color-notice-dark-red: #ff6676;
--akismet-color-notice-yellow: #e5c133;
--akismet-color-page-bg: #fcfcfc;
--akismet-color-border: #e0e0e0;
--akismet-color-border-light: #f0f0f0;
--akismet-color-near-black: #1e1e1e;
--akismet-color-text-grey: #757575;
--akismet-color-icon: #666666;
--akismet-color-icon-hover: #333333;
}
/* UI components */
#akismet-plugin-container {
background-color: var(--akismet-color-page-bg);
border: 1px solid var(--akismet-color-border);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen-Sans', 'Ubuntu', 'Cantarell', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
}
#akismet-plugin-container a {
color: var(--akismet-color-mid-green);
}
#akismet-plugin-container a.akismet-button {
background-color: var(--akismet-color-mid-green);
color: var(--akismet-color-white);
}
#akismet-plugin-container button:focus-visible,
#akismet-plugin-container input:focus-visible {
border: 0;
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
#akismet-plugin-container a:focus-visible {
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
.akismet-masthead {
border-bottom: 1px solid var(--akismet-color-border-light);
box-shadow: none;
}
.akismet-masthead__logo {
margin: 20px 0;
}
.akismet-section-header {
box-shadow: none;
margin-bottom: 0;
}
.akismet-section-header__label {
color: var(--akismet-color-charcoal);
font-weight: 600;
padding-right: 0.2em;
}
.akismet-button,
.akismet-button:hover {
border: 0;
color: var(--akismet-color-white);
}
.akismet-button {
background-color: var(--akismet-color-mid-green);
}
.akismet-button:hover {
background-color: var(--akismet-color-dark-green);
}
.akismet-external-link {
display: inline-block;
}
.akismet-external-link::after {
content: "↗";
display: inline-block;
padding-right: 2px;
text-decoration: none;
vertical-align: middle;
}
/* Need this specificity to override the existing header rule */
.akismet-new-snapshot h3.akismet-new-snapshot__header {
background: none;
font-size: 13px;
color: var(--akismet-color-charcoal);
text-align: right;
text-transform: none;
}
.akismet-new-snapshot__number {
color: var(--akismet-color-charcoal);
display: block;
font-size: 32px;
font-weight: 400;
letter-spacing: -1px;
line-height: 1.5em;
text-align: right;
}
.akismet-new-snapshot li.akismet-new-snapshot__item {
color: var(--akismet-color-dark-grey);
font-size: 13px;
text-align: right;
text-transform: none;
}
.akismet-masthead__logo-link {
min-height: 50px;
}
.akismet-masthead__back-link-container {
margin-top: 16px;
margin-bottom: 2px;
}
/* Need this specificity to override the existing link rule */
#akismet-plugin-container a.akismet-masthead__back-link {
background-image: url(../img/arrow-left.svg);
background-position: right;
background-repeat: no-repeat;
background-size: 16px;
color: var(--akismet-color-charcoal);
font-weight: 400;
padding-right: 20px;
text-decoration: none;
}
#akismet-plugin-container a.akismet-masthead__back-link:hover {
text-decoration: underline;
}
.akismet-new-snapshot__item {
border-top: 1px solid var(--akismet-color-border-light);
border-right: 1px solid var(--akismet-color-border-light);
padding: 1em;
}
.akismet-new-snapshot li:first-child {
border-right: none;
}
.akismet-new-snapshot__list {
display: flex;
margin-bottom: 0;
}
.akismet-new-snapshot__item {
flex: 1 0 33.33%;
margin-bottom: 0;
padding-right: 1.5em;
padding-left: 1.5em;
}
.akismet-new-snapshot__chart {
padding: 1em;
}
.akismet-stats-footer {
align-items: center;
border-radius: 0 0 7px 7px;
border-top: 1px solid var(--akismet-color-border-light);
display: flex;
justify-content: space-between;
outline-offset: -2px;
padding: 1em 1.5em;
text-decoration: none;
}
.akismet-stats-footer:hover {
text-decoration: underline;
}
.akismet-stats-footer:focus {
border-radius: 0 0 7px 7px;
box-shadow: none;
}
.akismet-stats-footer:focus-visible {
box-shadow: none;
outline: 2px solid var(--akismet-color-light-blue);
}
.akismet-box {
border: 0;
}
.akismet-box:not(:first-child) {
margin-top: 1rem;
}
.akismet-box,
.akismet-card {
border: 1px solid var(--akismet-color-border);
border-radius: 8px;
overflow: hidden;
}
.akismet-card {
margin: 16px auto 0 auto;
}
.akismet-lower {
padding-top: 0;
}
.akismet-lower .inside {
padding: 0;
}
.akismet-section-header__label {
margin: 0;
}
.akismet-settings__row {
border-bottom: 1px solid var(--akismet-color-border-light);
display: block;
padding: 1em 1.5em;
}
.akismet-settings__row-input {
margin-right: auto;
}
.akismet-settings__row-title {
font-weight: 500;
font-size: 1em;
margin: 0;
margin-bottom: 1em;
}
.akismet-settings__row-description {
margin-top: 0.5em;
}
.akismet-card-actions {
display: flex;
justify-content: flex-end;
padding: 1em;
}
.akismet-card-actions__secondary-action {
align-self: center;
margin-inline-end: auto;
margin-inline-start: 6px;
}
.akismet-settings__row label {
padding-bottom: 1em;
}
.akismet-settings__row-note {
font-size: 0.9em;
margin-top: 0.4em;
}
.akismet-settings__row-note abbr {
cursor: help;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
accent-color: var(--akismet-color-mid-green);
box-shadow: none;
flex-shrink: 0;
margin: 2px 0 0 0;
}
.akismet-settings__row input[type="checkbox"] {
margin-top: 1px;
vertical-align: top;
-webkit-appearance: checkbox;
}
.akismet-settings__row input[type="radio"] {
-webkit-appearance: radio;
}
/* Fix up misbehaving wp-admin styles in Chrome (from forms and colors stylesheets) */
.akismet-settings__row input[type="checkbox"]:checked:before {
content: '';
}
.akismet-settings__row input[type="radio"]:checked:before {
background: none;
}
.akismet-settings__row input[type="checkbox"]:checked:hover,
.akismet-settings__row input[type="radio"]:checked:hover {
accent-color: var(--akismet-color-mid-green);
}
.akismet-button:disabled {
background-color: var(--akismet-color-mid-grey);
color: var(--akismet-color-white);
cursor: arrow;
}
.akismet-awaiting-stats,
.akismet-account {
padding: 0 1rem 1rem 1rem;
margin: 0;
}
.akismet-account {
display: grid;
grid-template-columns: auto 1fr;
margin-inline-start: 2px;
margin-top: 0.25em;
padding-bottom: 0;
row-gap: 0.25em;
}
.akismet-account__label {
font-weight: 500;
padding-bottom: 1em;
padding-inline-end: 1em;
}
.akismet-account__value {
margin: 0;
padding-bottom: 1em;
}
.akismet-settings__row-input-label {
align-items: center;
display: flex;
}
.akismet-settings__row-label-text {
padding-right: 0.5em;
margin-top: 2px;
}
.akismet-alert {
border-right: 8px solid;
border-radius: 8px;
margin: 20px 0;
padding: 0.2em 1em;
}
.akismet-alert__heading {
font-size: 1em;
}
.akismet-alert.is-good {
background-color: var(--akismet-color-notice-light-green);
border-right-color: var(--akismet-color-notice-dark-green);
}
.akismet-alert.is-neutral {
background-color: var(--akismet-color-white);
border-right-color: var(--akismet-color-dark-grey);
}
.akismet-alert.is-bad {
background-color: var(--akismet-color-notice-light-red);
border-right-color: var(--akismet-color-notice-dark-red);
}
.akismet-alert.is-commercial {
background-color: var(--akismet-color-white);
border-color: var(--akismet-color-mid-grey);
border-bottom-width: 1px;
border-right-color: var(--akismet-color-notice-yellow);
display: flex;
padding-bottom: 1em;
}
#akismet-plugin-container .akismet-alert.is-good a,
#akismet-plugin-container .akismet-alert.is-bad a {
/* For better contrast - green isn't great */
color: var(--akismet-color-grey-80);
}
.akismet-alert-header {
font-size: 16px;
margin-bottom: 0.5em;
}
.akismet-alert-button-wrapper {
align-self: center;
margin-right: 2em;
min-width: 120px;
}
.akismet-alert-info {
text-wrap: pretty;
margin: 0.5em 0;
}
/* Setup */
.akismet-setup-instructions__heading {
font-size: 1.375rem;
font-weight: 700;
padding-block-end: 0;
}
h3.akismet-setup-instructions__subheading {
color: var(--akismet-color-dark-grey);
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
margin: 0 0 1.25rem;
padding-block-start: 1rem;
}
.akismet-setup-instructions__feature-list {
list-style: none;
margin: 1rem 0.5rem 1.5rem;
max-width: 640px;
padding: 0 1rem;
}
.akismet-setup-instructions__feature {
align-items: start;
display: flex;
margin-block-end: 1rem;
text-align: right;
}
.akismet-setup-instructions__icon {
height: 20px;
width: 20px;
}
.akismet-setup-instructions__body {
flex: 1;
padding-inline-start: 0.5rem;
}
.akismet-setup-instructions__title {
color: #1d2327;
font-size: 1rem;
font-weight: 600;
line-height: 1.3;
margin: 0;
text-align: right;
}
p.akismet-setup-instructions__text {
color: var(--akismet-color-grey-80);
font-size: 0.875rem;
line-height: 1.5;
margin: 0.25rem 0 0;
padding: 0;
text-align: right;
}
.akismet-setup-instructions__button,
.akismet-setup-instructions__button:hover,
.akismet-setup-instructions__button:visited {
font-size: 1rem;
margin-inline-start: 1.5rem;
}
.akismet-setup__connection {
background: var(--akismet-color-light-grey);
border: 1px solid var(--akismet-color-grey-border);
border-radius: 8px;
margin: 1rem 1rem 2rem 1rem;
padding: 1rem;
}
.akismet-setup__connection-action:not(:last-child) {
margin-bottom: 1rem;
}
.akismet-setup__connection-user {
display: flex;
}
.akismet-setup__connection-avatar {
align-items: center;
display: flex;
gap: 12px;
margin-bottom: 12px;
}
.akismet-setup__connection-avatar-image {
border-radius: 50%;
}
.akismet-setup__connection-account-name {
color: var(--akismet-color-charcoal);
font-size: 0.9rem;
overflow-wrap: anywhere;
}
.akismet-setup__connection-account-email {
margin-top: 0.1rem;
overflow-wrap: anywhere;
}
.akismet-setup__connection-action {
margin-right: auto;
}
.akismet-setup__connection-button {
text-align: center;
width: 100%;
}
p.akismet-setup__connection-action-intro,
p.akismet-setup__connection-action-description {
color: var(--akismet-color-dark-grey);
font-size: 0.875rem;
padding: 0;
}
p.akismet-setup__connection-action-intro {
margin: 0 0 1rem 0;
}
p.akismet-setup__connection-action-description {
margin: 1rem 0 0;
}
/* API key field with copy button */
.akismet-api-key-wrapper {
position: relative;
display: inline-flex;
align-items: center;
}
.akismet-api-key-wrapper input {
padding-left: 36px;
}
.akismet-api-key-copy {
position: absolute;
left: 4px;
background: none;
border: none;
cursor: pointer;
padding: 4px;
color: var(--akismet-color-icon);
display: flex;
align-items: center;
}
.akismet-api-key-copy:hover {
color: var(--akismet-color-icon-hover);
}
/* Setup - API key input */
.akismet-enter-api-key-box {
margin: 1.5rem 0;
}
.akismet-enter-api-key-box__reveal {
background: none;
border: 0;
color: var(--akismet-color-mid-green);
cursor: pointer;
text-decoration: underline;
}
.akismet-enter-api-key-box__form-wrapper {
display: none;
margin-top: 1.5rem;
}
.akismet-enter-api-key-box__input-wrapper {
box-sizing: border-box;
display: flex;
flex-wrap: nowrap;
padding: 0 1.5rem;
width: 100%;
}
.akismet-enter-api-key-box__key-input {
flex-grow: 1;
margin-left: 1rem;
}
h3.akismet-enter-api-key-box__header {
padding-top: 0;
padding-bottom: 1em;
text-align: right;
}
/* Notices > Activation (shown on edit-comments.php) */
#akismet-setup-prompt {
background: none;
border: none;
margin: 0;
padding: 0;
width: 100%;
}
.akismet-activate {
align-items: center;
/* background-image is defined via an inline style in class.akismet-admin.php */
background-color: var(--akismet-color-light-grey);
background-position: calc(100% - (100% - 1em)) center;
background-repeat: no-repeat;
background-size: 140px;
border: 1px solid var(--akismet-color-mid-green);
border-right-width: 4px;
display: flex;
justify-content: space-between;
margin: 15px 0;
min-height: 60px;
overflow: hidden;
padding: 5px 5px 5px 160px;
position: relative;
}
.akismet-activate__button,
.akismet-activate__button:hover,
.akismet-activate__button:visited {
margin: 0 1em;
}
.akismet-activate__description {
color: var(--akismet-color-charcoal);
flex-grow: 1;
font-size: 16px;
font-weight: 600;
margin: 0 auto;
text-align: center;
text-wrap: pretty;
}
/* Compatible plugins section */
.akismet-compatible-plugins__content {
padding: 0 1.5em 1.5em 1.5em;
}
.akismet-compatible-plugins__intro {
margin: 0;
}
.akismet-compatible-plugins__section-header-label {
display: block;
}
.akismet-compatible-plugins__section-header-label-text {
padding-left: 0.5em;
}
.akismet-compatible-plugins__list {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
margin: 1.5em 0 1em 0;
padding: 0;
}
.akismet-compatible-plugins__card {
border: 1px solid var(--akismet-color-border-light);
border-radius: 4px;
padding: 1em;
display: flex;
align-items: center;
}
.akismet-compatible-plugins__card-logo {
padding: 0 0 0 1.5em;
object-fit: contain;
width: 36px;
height: 36px;
}
.akismet-compatible-plugins__card-detail {
display: flex;
flex: 1;
justify-content: space-between;
align-items: center;
}
.akismet-compatible-plugins__card-title {
font-size: 1.2em;
margin-top: 0;
margin-bottom: 0;
}
.akismet-compatible-plugins__docs {
margin-top: 0;
}
.akismet-compatible-plugins__show-more {
all: unset;
cursor: pointer;
display: flex;
justify-content: space-between;
position: relative;
width: 100%;
}
/* Generates the show/hide chevron */
.akismet-compatible-plugins__show-more::after {
align-self: center;
border-bottom: 2px solid black;
border-left: 2px solid black;
content: "";
height: 8px;
transform: rotate(-45deg);
transition: transform 0.2s ease;
width: 8px;
}
.akismet-compatible-plugins__list.is-expanded + .akismet-compatible-plugins__show-more::after {
align-self: end;
transform: rotate(-225deg);
}
/* Gutenberg medium breakpoint */
@media screen and (max-width: 782px) {
.akismet-new-snapshot__list {
display: block;
}
.akismet-new-snapshot__number {
float: left;
font-size: 20px;
font-weight: 500;
margin-top: -16px;
}
.akismet-new-snapshot__header {
font-size: 14px;
font-weight: 500;
}
.akismet-new-snapshot__text {
font-size: 12px;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
height: 24px;
width: 24px;
}
.akismet-settings__row-label-text {
padding-right: 0.8em;
}
.akismet-settings__row input[type="checkbox"],
.akismet-settings__row input[type="radio"] {
margin-top: 0;
}
.akismet-activate {
background-size: 120px;
padding-left: 134px;
}
.akismet-activate__button {
white-space: normal;
}
.akismet-activate__description {
font-size: 14px;
margin-left: 1em;
}
}
/* Gutenberg small breakpoint */
@media screen and (max-width: 600px) {
.akismet-compatible-plugins__list {
gap: 8px;
}
.akismet-activate__button,
.akismet-activate__button:hover {
font-size: 13px;
}
.akismet-activate__description {
display: none;
}
}
@@ -0,0 +1,464 @@
/* This file was automatically generated on Oct 30 2025 21:26:42 */
.wp-admin.jetpack_page_akismet-key-config, .wp-admin.settings_page_akismet-key-config {
background-color:#f3f6f8;
}
#submitted-on {
position: relative;
}
#the-comment-list .author .akismet-user-comment-count {
display: inline;
}
#the-comment-list .author a span {
text-decoration: none;
color: #999;
}
#the-comment-list .author a span.akismet-span-link {
text-decoration: inherit;
color: inherit;
}
#the-comment-list .akismet_remove_url {
margin-right: 3px;
color: #999;
padding: 2px 0 2px 3px;
}
#the-comment-list .akismet_remove_url:hover {
color: #A7301F;
font-weight: bold;
padding: 2px 0 2px 2px;
}
#dashboard_recent_comments .akismet-status {
display: none;
}
.akismet-status {
float: left;
}
.akismet-status a {
color: #AAA;
font-style: italic;
}
table.comments td.comment p a {
text-decoration: underline;
}
table.comments td.comment p a:after {
content: attr(href);
color: #aaa;
display: inline-block; /* Show the URL without the link's underline extending under it. */
padding: 0 1ex; /* Because it's inline block, we can't just use spaces in the content: attribute to separate it from the link text. */
}
.mshot-arrow {
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #5C5C5C;
position: absolute;
right: -6px;
top: 91px;
}
.mshot-container {
background: #5C5C5C;
position: absolute;
top: -94px;
padding: 7px;
width: 450px;
height: 338px;
z-index: 20000;
border-radius: 6px;
}
.akismet-mshot {
position: absolute;
z-index: 100;
}
.akismet-mshot .mshot-image {
margin: 0;
height: 338px;
width: 450px;
}
.checkforspam {
display: inline-block !important;
}
.checkforspam-spinner {
display: inline-block;
margin-top: 7px;
}
.akismet-right {
float: left;
}
.akismet-card .akismet-right {
margin: 1em 0;
}
.akismet-new-snapshot {
margin-top: 1em;
text-align: center;
background: #fff;
}
.akismet-new-snapshot h3 {
background: #f5f5f5;
color: #888;
font-size: 11px;
margin: 0;
}
.akismet-new-snapshot ul li {
color: #999;
font-size: 11px;
text-transform: uppercase;
box-sizing: border-box;
}
.akismet-settings th:first-child {
vertical-align: top;
padding-top: 15px;
}
.akismet-settings th.akismet-api-key {
vertical-align: middle;
padding-top: 0;
}
.akismet-settings span.akismet-note {
float: right;
padding-right: 23px;
font-size: 75%;
margin-top: -10px;
}
.jetpack_page_akismet-key-config #wpcontent, .settings_page_akismet-key-config #wpcontent {
padding-right: 0;
}
.akismet-masthead {
background-color:#fff;
text-align:center;
box-shadow:0 1px 0 rgba(200,215,225,0.5),0 1px 2px #e9eff3
}
@media (max-width: 45rem) {
.akismet-masthead {
padding:0 1.25rem
}
}
.akismet-masthead__inside-container {
padding:.375rem 0;
margin:0 auto;
width:100%;
max-width:45rem;
text-align: right;
}
.akismet-masthead__logo-container {
padding:.3125rem 0 0
}
.akismet-masthead__logo-link {
display:inline-block;
outline:none;
vertical-align:middle
}
.akismet-masthead__logo-link:focus {
line-height:0;
box-shadow:0 0 0 2px #78dcfa
}
.akismet-masthead__logo-link+code {
margin:0 10px;
padding:5px 9px;
border-radius:2px;
background:#e6ecf1;
color:#647a88
}
.akismet-masthead__links {
display:flex;
flex-flow:row wrap;
flex:2 50%;
justify-content:flex-end;
margin:0
}
@media (max-width: 480px) {
.akismet-masthead__links {
padding-left:.625rem
}
}
.akismet-masthead__link-li {
margin:0;
padding:0
}
.akismet-masthead__link {
font-style:normal;
color:#0087be;
padding:.625rem;
display:inline-block
}
.akismet-masthead__link:visited {
color:#0087be
}
.akismet-masthead__link:active,.akismet-masthead__link:hover {
color:#00aadc
}
.akismet-masthead__link:hover {
text-decoration:underline
}
.akismet-masthead__link .dashicons {
display:none
}
@media (max-width: 480px) {
.akismet-masthead__link:hover,.akismet-masthead__link:active {
text-decoration:none
}
.akismet-masthead__link .dashicons {
display:block;
font-size:1.75rem
}
.akismet-masthead__link span+span {
display:none
}
}
.akismet-masthead__link-li:last-of-type .akismet-masthead__link {
padding-left:0
}
.akismet-lower {
margin: 0 auto;
text-align: right;
max-width: 45rem;
padding: 1.5rem;
}
.akismet-lower .notice {
margin-bottom: 2rem;
}
.akismet-card {
margin-top: 1rem;
margin-bottom: 0;
position: relative;
box-sizing: border-box;
background: white;
}
.akismet-card:after, .akismet-card .inside:after, .akismet-masthead__logo-container:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.akismet-card .inside {
padding: 1.5rem;
padding-top: 1rem;
}
.akismet-card .akismet-card-actions {
margin-top: 1rem;
}
.jetpack_page_akismet-key-config .update-nag, .settings_page_akismet-key-config .update-nag {
display: none;
}
.akismet-masthead .akismet-right {
line-height: 2.125rem;
font-size: 0.9rem;
}
.akismet-box {
box-sizing: border-box;
background: white;
border: 1px solid rgba(200, 215, 225, 0.5);
}
.akismet-box h2, .akismet-box h3 {
padding: 1.5rem 1.5rem .5rem 1.5rem;
margin: 0;
}
.akismet-box p {
padding: 0 1.5rem 1.5rem 1.5rem;
margin: 0;
}
.akismet-box p:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.akismet-box .akismet-right {
padding-left: 1.5rem;
}
.akismet-boxes .akismet-box {
margin-bottom: 0;
padding: 0;
margin-top: -1px;
}
.akismet-boxes .akismet-box:last-child {
margin-bottom: 1.5rem;
}
.akismet-boxes .akismet-box:first-child {
margin-top: 1.5rem;
}
.akismet-box .centered {
text-align: center;
}
.akismet-button, .akismet-button:hover, .akismet-button:visited {
background: white;
border-color: #c8d7e1;
border-style: solid;
border-width: 1px 1px 2px;
color: #2e4453;
cursor: pointer;
display: inline-block;
margin: 0;
outline: 0;
overflow: hidden;
font-size: 14px;
font-weight: 500;
text-overflow: ellipsis;
text-decoration: none;
vertical-align: top;
box-sizing: border-box;
line-height: 21px;
border-radius: 4px;
padding: 7px 14px 9px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.akismet-button:hover {
border-color: #a8bece;
}
.akismet-button:active {
border-width: 2px 1px 1px;
}
.akismet-is-primary, .akismet-is-primary:hover, .akismet-is-primary:visited {
background: #00aadc;
border-color: #0087be;
color: white;
}
.akismet-is-primary:hover, .akismet-is-primary:focus {
border-color: #005082;
}
.akismet-is-primary:hover {
border-color: #005082;
}
.akismet-section-header {
position: relative;
margin: 0 auto 0.625rem auto;
padding: 1rem;
box-sizing: border-box;
box-shadow: 0 0 0 1px rgba(200, 215, 225, 0.5), 0 1px 2px #e9eff3;
background: #ffffff;
width: 100%;
padding-top: 0.6875rem;
padding-bottom: 0.6875rem;
display: flex;
}
.akismet-section-header__label {
display: flex;
align-items: center;
flex-grow: 1;
line-height: 1.75rem;
position: relative;
font-size: 0.875rem;
color: #4f748e;
}
.akismet-section-header__actions {
line-height: 1.75rem;
}
.akismet-setup-instructions form {
padding-bottom: 1.5rem;
}
.akismet-setup-instructions > a.akismet-button {
display: inline-block;
margin-bottom: 1.5rem;
}
div.error.akismet-usage-limit-alert {
padding: 25px 15px 25px 45px;
display: flex;
align-items: center;
}
#akismet-plugin-container .akismet-usage-limit-alert {
margin: 0 auto 0.625rem auto;
box-sizing: border-box;
box-shadow: 0 0 0 1px rgba(200, 215, 225, 0.5), 0 1px 2px #e9eff3;
border: none;
border-right: 4px solid #d63638;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo {
width: 38px;
min-width: 38px;
height: 38px;
border-radius: 20px;
margin-left: 18px;
background: black;
position: relative;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo img {
position: absolute;
width: 22px;
right: 8px;
top: 10px;
}
.akismet-usage-limit-alert .akismet-usage-limit-text {
flex-grow: 1;
margin-left: 18px;
}
.akismet-usage-limit-alert h3 {
line-height: 1.3;
margin: 0;
}
.akismet-usage-limit-alert .akismet-usage-limit-cta {
border-color: none;
text-align: left;
}
#akismet-plugin-container .akismet-usage-limit-cta a {
color: #d63638;
background: #fafafa;
}
@media (max-width: 550px) {
div.error.akismet-usage-limit-alert {
display: block;
}
.akismet-usage-limit-alert .akismet-usage-limit-logo,
.akismet-usage-limit-alert .akismet-usage-limit-text {
margin-bottom: 15px;
}
.akismet-usage-limit-alert .akismet-usage-limit-cta {
text-align: right;
}
}
@@ -0,0 +1,224 @@
<?php
/**
* Comment Check ability for Akismet.
*
* @package Akismet
* @since 5.7
*/
declare( strict_types = 1 );
/**
* Class Akismet_Ability_Comment_Check
*
* Registers and handles the ability to check comments for spam.
*/
class Akismet_Ability_Comment_Check extends Akismet_Ability implements Akismet_Ability_Interface {
/**
* Get the ability name.
*
* @return string The ability name.
*/
protected function get_ability_name(): string {
return 'akismet/comment-check';
}
/**
* Get the human-readable label.
*
* @return string The label.
*/
protected function get_label(): string {
return __( 'Check comment for spam', 'akismet' );
}
/**
* Get the ability description.
*
* @return string The description.
*/
protected function get_description(): string {
return __( 'Checks a comment against the Akismet spam filter to determine if it is spam or legitimate content.', 'akismet' );
}
/**
* Get the input schema.
*
* @return array The input schema.
*/
protected function get_input_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'comment_author' => array(
'type' => 'string',
'description' => __( 'Name of the comment author.', 'akismet' ),
),
'comment_author_email' => array(
'type' => 'string',
'description' => __( 'Email address of the comment author.', 'akismet' ),
'format' => 'email',
),
'comment_author_url' => array(
'type' => 'string',
'description' => __( 'URL/website of the comment author.', 'akismet' ),
'format' => 'uri',
),
'comment_content' => array(
'type' => 'string',
'description' => __( 'The comment content/text.', 'akismet' ),
),
'comment_type' => array(
'type' => 'string',
'description' => __( 'The comment type (e.g., "comment", "trackback", "pingback").', 'akismet' ),
'default' => 'comment',
),
'comment_post_ID' => array(
'type' => 'integer',
'description' => __( 'The ID of the post the comment is being submitted to.', 'akismet' ),
),
'permalink' => array(
'type' => 'string',
'description' => __( 'The permanent link to the post or page.', 'akismet' ),
'format' => 'uri',
),
'user_ip' => array(
'type' => 'string',
'description' => __( 'IP address of the commenter.', 'akismet' ),
),
'user_agent' => array(
'type' => 'string',
'description' => __( 'User agent string of the web browser submitting the comment.', 'akismet' ),
),
'referrer' => array(
'type' => 'string',
'description' => __( 'The HTTP_REFERER header.', 'akismet' ),
),
'user_role' => array(
'type' => 'string',
'description' => __( 'The user role of the comment author if logged in.', 'akismet' ),
),
),
'additionalProperties' => false,
);
}
/**
* Get the output schema.
*
* @return array The output schema.
*/
protected function get_output_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'success' => array(
'type' => 'boolean',
'description' => __( 'Whether the check was successfully performed.', 'akismet' ),
),
'is_spam' => array(
'type' => 'boolean',
'description' => __( 'Whether the comment is identified as spam.', 'akismet' ),
),
'pro_tip' => array(
'type' => 'string',
'description' => __( 'Optional recommendation from Akismet (e.g., "discard" for obvious spam).', 'akismet' ),
),
'guid' => array(
'type' => 'string',
'description' => __( 'Unique identifier for this check, used for webhooks and updates.', 'akismet' ),
),
'error' => array(
'type' => 'string',
'description' => __( 'Error message if the check could not be completed.', 'akismet' ),
),
'debug_help' => array(
'type' => 'string',
'description' => __( 'Debug information to help troubleshoot issues.', 'akismet' ),
),
),
'additionalProperties' => false,
);
}
/**
* Get the ability configuration.
*
* @return array The ability configuration.
*/
public function get_config(): array {
return array(
'label' => $this->get_label(),
'description' => $this->get_description(),
'category' => Akismet_Abilities::CATEGORY_SLUG,
'input_schema' => $this->get_input_schema(),
'output_schema' => $this->get_output_schema(),
'execute_callback' => array( $this, 'execute' ),
'permission_callback' => array( $this, 'current_user_has_permission' ),
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => false,
),
'mcp' => array(
'public' => ( get_option( 'akismet_enable_mcp_access' ) === '1' ),
'type' => 'tool',
),
'show_in_rest' => true,
),
);
}
/**
* Execute callback for the comment-check ability.
*
* @param array|null $input The comment data to check.
* @return array|WP_Error The spam check result or error.
*/
public function execute( ?array $input = null ) {
// Check for required API key.
if ( ! Akismet::get_api_key() ) {
return new WP_Error(
'akismet_not_configured',
__( 'Akismet is not configured. Please enter an API key.', 'akismet' )
);
}
// Perform the comment check.
$result = Akismet::comment_check( $input );
if ( ! $result ) {
return new WP_Error(
'comment_check_failed',
__( 'Failed to check comment with Akismet API.', 'akismet' )
);
}
// Build response array.
$response = array(
'success' => true,
'is_spam' => $result->is_spam,
);
// Include optional fields if present.
if ( isset( $result->pro_tip ) ) {
$response['pro_tip'] = $result->pro_tip;
}
if ( isset( $result->guid ) ) {
$response['guid'] = $result->guid;
}
if ( isset( $result->error ) ) {
$response['error'] = $result->error;
}
if ( isset( $result->debug_help ) ) {
$response['debug_help'] = $result->debug_help;
}
return $response;
}
}
@@ -0,0 +1,202 @@
<?php
/**
* Get Stats ability for Akismet.
*
* @package Akismet
* @since 5.7
*/
declare( strict_types = 1 );
/**
* Class Akismet_Ability_Get_Stats
*
* Registers and handles the ability to retrieve Akismet statistics.
*/
class Akismet_Ability_Get_Stats extends Akismet_Ability implements Akismet_Ability_Interface {
/**
* Get the ability name.
*
* @return string The ability name.
*/
protected function get_ability_name(): string {
return 'akismet/get-stats';
}
/**
* Get the human-readable label.
*
* @return string The label.
*/
protected function get_label(): string {
return __( 'Get Akismet statistics', 'akismet' );
}
/**
* Get the ability description.
*
* @return string The description.
*/
protected function get_description(): string {
return __( 'Retrieves Akismet spam protection statistics including spam blocked count, accuracy percentage, and other key metrics.', 'akismet' );
}
/**
* Get the input schema.
*
* @return array The input schema.
*/
protected function get_input_schema(): array {
return array(
'type' => array( 'object', 'null' ),
'properties' => array(
'interval' => array(
'type' => 'string',
'description' => __( 'The time interval for stats. Options: "6-months", "all", or "60-days".', 'akismet' ),
'enum' => array( '6-months', 'all', '60-days' ),
'default' => '6-months',
),
),
'additionalProperties' => false,
);
}
/**
* Get the output schema.
*
* @return array The output schema.
*/
protected function get_output_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'success' => array(
'type' => 'boolean',
'description' => __( 'Whether the stats were successfully retrieved.', 'akismet' ),
),
'spam' => array(
'type' => 'integer',
'description' => __( 'Total number of spam comments blocked.', 'akismet' ),
),
'ham' => array(
'type' => 'integer',
'description' => __( 'Total number of legitimate comments approved.', 'akismet' ),
),
'missed_spam' => array(
'type' => 'integer',
'description' => __( 'Number of spam comments that were missed.', 'akismet' ),
),
'false_positives' => array(
'type' => 'integer',
'description' => __( 'Number of legitimate comments incorrectly marked as spam.', 'akismet' ),
),
'accuracy' => array(
'type' => 'number',
'description' => __( 'Accuracy percentage of spam detection.', 'akismet' ),
),
'time_saved' => array(
'type' => 'integer',
'description' => __( 'Estimated time saved by Akismet blocking spam, in seconds.', 'akismet' ),
),
'breakdown' => array(
'type' => 'object',
'description' => __( 'Monthly breakdown of statistics.', 'akismet' ),
'additionalProperties' => array(
'type' => 'object',
'properties' => array(
'spam' => array(
'type' => 'integer',
'description' => __( 'Total number of spam comments blocked in this period.', 'akismet' ),
),
'ham' => array(
'type' => 'integer',
'description' => __( 'Total number of legitimate comments approved in this period.', 'akismet' ),
),
'missed_spam' => array(
'type' => 'integer',
'description' => __( 'Number of spam comments that were missed in this period.', 'akismet' ),
),
'false_positives' => array(
'type' => 'integer',
'description' => __( 'Number of legitimate comments incorrectly marked as spam in this period.', 'akismet' ),
),
'da' => array(
'type' => 'string',
'description' => __( 'Date for this period.', 'akismet' ),
),
),
),
),
'interval' => array(
'type' => 'string',
'description' => __( 'The time interval for these stats.', 'akismet' ),
),
'error' => array(
'type' => 'string',
'description' => __( 'Error message if the operation could not be completed.', 'akismet' ),
),
),
'additionalProperties' => false,
);
}
/**
* Get the ability configuration.
*
* @return array The ability configuration.
*/
public function get_config(): array {
return array(
'label' => $this->get_label(),
'description' => $this->get_description(),
'category' => Akismet_Abilities::CATEGORY_SLUG,
'input_schema' => $this->get_input_schema(),
'output_schema' => $this->get_output_schema(),
'execute_callback' => array( $this, 'execute' ),
'permission_callback' => array( $this, 'current_user_has_permission' ),
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'mcp' => array(
'public' => ( get_option( 'akismet_enable_mcp_access' ) === '1' ),
'type' => 'tool',
),
'show_in_rest' => true,
),
);
}
/**
* Execute callback for the get-stats ability.
*
* @param array|null $input The input parameters with optional interval.
* @return array|WP_Error The stats data or error.
*/
public function execute( ?array $input = null ) {
// Get interval from input or use default.
$interval = isset( $input['interval'] ) ? $input['interval'] : '6-months';
// Fetch stats from Akismet API.
$data = Akismet::get_stats( $interval );
if ( ! $data ) {
return new WP_Error(
'stats_fetch_failed',
__( 'Failed to retrieve stats from Akismet API.', 'akismet' )
);
}
// Build response with data from API (already properly typed by get_stats).
return array_merge(
array(
'success' => true,
'interval' => $interval,
),
(array) $data
);
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Represents a Base Ability.
*
* This class holds a default constructor to register the ability and a default permission.
*
* @package Akismet
* @since 5.7
*/
declare( strict_types = 1 );
/**
* Base class for Akismet abilities.
*
* @package Akismet
* @since 5.7
*/
abstract class Akismet_Ability implements Akismet_Ability_Interface {
/**
* Get the ability name.
*
* Classes extending this must implement this method to provide the ability name into the registration.
*
* @return string The ability name.
*/
abstract protected function get_ability_name(): string;
/**
* Get the config.
*
* Classes extending this must implement this method to provide the ability configuration into the registration.
*
* @return array The ability configuration array.
*/
abstract public function get_config(): array;
/**
* Constructor - registers the ability.
*/
public function __construct() {
wp_register_ability(
$this->get_ability_name(),
$this->get_config()
);
}
// phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.Found -- Base class default, subclasses use $input.
/**
* Permission callback for any ability that uses this trait.
*
* @param array|null $input The input parameters (unused).
* @return bool Whether the current user can use this ability.
*/
public function current_user_has_permission( ?array $input = null ): bool {
// phpcs:enable Generic.CodeAnalysis.UnusedFunctionParameter.Found
return current_user_can( 'moderate_comments' );
}
}
@@ -0,0 +1,62 @@
<?php
/**
* Interface for Akismet abilities.
*
* @package Akismet
* @since 5.7
*/
declare( strict_types = 1 );
/**
* Interface Akismet_Ability_Interface
*/
interface Akismet_Ability_Interface {
/**
* Get the ability configuration array.
*
* Returns the configuration array used to register the ability with wp_register_ability().
*
* @return array {
* The ability configuration array.
*
* @type string $label A human-readable name for the ability. Used for display purposes. Should be translatable.
* @type string $description A detailed description of what the ability does, its purpose, and its parameters or return values.
* This is crucial for AI agents to understand how and when to use the ability.
* @type string $category The slug of the category this ability belongs to. The category must be registered before
* registering the ability.
* @type array $output_schema A JSON Schema definition describing the expected format of the data returned by the ability.
* Used for validation and documentation.
* @type callable $execute_callback The PHP function or method to execute when this ability is called. Receives optional input
* argument matching the input schema type.
* @type callable $permission_callback A callback function to check if the current user has permission to execute this ability.
* Returns boolean or WP_Error.
* @type array $input_schema Optional. JSON Schema defining expected input parameters. Required when the ability accepts inputs.
* @type array $meta Optional. An associative array for storing arbitrary additional metadata about the ability,
* including 'annotations' (readonly, destructive, idempotent flags) and 'show_in_rest'.
* @type string $ability_class Optional. Custom class name extending WP_Ability for behavior customization.
* }
*/
public function get_config(): array;
/**
* Execute callback for the ability.
*
* Runs the main functionality of the ability.
*
* @param array|null $input The input parameters for the ability. Null when no input provided.
* @return array|WP_Error The result of the execution or a WP_Error on failure.
*/
public function execute( ?array $input = null );
/**
* Permission callback for the ability.
*
* Checks if the current user has permission to execute the ability.
*
* @param array|null $input The input parameters for the ability. Null when no input provided.
* @return bool Whether the current user has permission.
*/
public function current_user_has_permission( ?array $input = null ): bool;
}
+93
View File
@@ -0,0 +1,93 @@
<?php
/**
* @package Akismet
*/
/*
Plugin Name: Akismet Anti-spam: Spam Protection
Plugin URI: https://akismet.com/
Description: Used by millions, Akismet is quite possibly the best way in the world to <strong>protect your blog from spam</strong>. Akismet Anti-spam keeps your site protected even while you sleep. To get started: activate the Akismet plugin and then go to your Akismet Settings page to set up your API key.
Version: 5.7
Requires at least: 5.8
Requires PHP: 7.2
Author: Automattic - Anti-spam Team
Author URI: https://automattic.com/wordpress-plugins/
License: GPLv2 or later
Text Domain: akismet
*/
/*
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Copyright 2005-2025 Automattic, Inc.
*/
// Make sure we don't expose any info if called directly
if ( ! function_exists( 'add_action' ) ) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
define( 'AKISMET_VERSION', '5.7' );
define( 'AKISMET__MINIMUM_WP_VERSION', '5.8' );
define( 'AKISMET__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'AKISMET_DELETE_LIMIT', 10000 );
register_activation_hook( __FILE__, array( 'Akismet', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Akismet', 'plugin_deactivation' ) );
require_once AKISMET__PLUGIN_DIR . 'class.akismet.php';
require_once AKISMET__PLUGIN_DIR . 'class.akismet-widget.php';
require_once AKISMET__PLUGIN_DIR . 'class.akismet-rest-api.php';
require_once AKISMET__PLUGIN_DIR . 'class-akismet-compatible-plugins.php';
add_action( 'init', array( 'Akismet', 'init' ) );
add_action( 'rest_api_init', array( 'Akismet_REST_API', 'init' ) );
add_action( 'init', array( 'Akismet_Compatible_Plugins', 'init' ) );
if ( function_exists( 'wp_get_connectors' ) ) {
require_once AKISMET__PLUGIN_DIR . 'class-akismet-connector.php';
add_action( 'init', array( 'Akismet_Connector', 'init' ) );
}
/**
* Conditionally loads for a WordPress 6.9+ installation, which has
* access to the core Abilities API. Only register abilities if Akismet
* is set up with an API key (either predefined or configured).
*/
if ( function_exists( 'wp_register_ability' ) ) {
require_once AKISMET__PLUGIN_DIR . 'class-akismet-abilities.php';
add_action(
'init',
function () {
if ( Akismet::get_api_key() ) {
Akismet_Abilities::init();
}
}
);
}
if ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
require_once AKISMET__PLUGIN_DIR . 'class.akismet-admin.php';
add_action( 'init', array( 'Akismet_Admin', 'init' ) );
}
// add wrapper class around deprecated akismet functions that are referenced elsewhere
require_once AKISMET__PLUGIN_DIR . 'wrapper.php';
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once AKISMET__PLUGIN_DIR . 'class.akismet-cli.php';
}
+550
View File
@@ -0,0 +1,550 @@
=== Akismet Anti-spam ===
== Archived Changelog Entries ==
This file contains older changelog entries, so we can keep the size of the standard WordPress readme.txt file reasonable.
For the latest changes, please see the "Changelog" section of the [readme.txt file](https://plugins.svn.wordpress.org/akismet/trunk/readme.txt).
= 4.2.5 =
*Release Date - 11 July 2022*
* Fixed a bug that added unnecessary comment history entries after comment rechecks.
* Added a notice that displays when WP-Cron is disabled and might be affecting comment rechecks.
= 4.2.4 =
*Release Date - 20 May 2022*
* Improved translator instructions for comment history.
* Bumped the "Tested up to" tag to WP 6.0.
= 4.2.3 =
*Release Date - 25 April 2022*
* Improved compatibility with Fluent Forms
* Fixed missing translation domains
* Updated stats URL.
* Improved accessibility of elements on the config page.
= 4.2.2 =
*Release Date - 24 January 2022*
* Improved compatibility with Formidable Forms
* Fixed a bug that could cause issues when multiple contact forms appear on one page.
* Updated delete_comment and deleted_comment actions to pass two arguments to match WordPress core since 4.9.0.
* Added a filter that allows comment types to be excluded when counting users' approved comments.
= 4.2.1 =
*Release Date - 1 October 2021*
* Fixed a bug causing AMP validation to fail on certain pages with forms.
= 4.2 =
*Release Date - 30 September 2021*
* Added links to additional information on API usage notifications.
* Reduced the number of network requests required for a comment page when running Akismet.
* Improved compatibility with the most popular contact form plugins.
* Improved API usage buttons for clarity on what upgrade is needed.
= 4.1.12 =
*Release Date - 3 September 2021*
* Fixed "Use of undefined constant" notice.
* Improved styling of alert notices.
= 4.1.11 =
*Release Date - 23 August 2021*
* Added support for Akismet API usage notifications on Akismet settings and edit-comments admin pages.
* Added support for the deleted_comment action when bulk-deleting comments from Spam.
= 4.1.10 =
*Release Date - 6 July 2021*
* Simplified the code around checking comments in REST API and XML-RPC requests.
* Updated Plus plan terminology in notices to match current subscription names.
* Added `rel="noopener"` to the widget link to avoid warnings in Google Lighthouse.
* Set the Akismet JavaScript as deferred instead of async to improve responsiveness.
* Improved the preloading of screenshot popups on the edit comments admin page.
= 4.1.9 =
*Release Date - 2 March 2021*
* Improved handling of pingbacks in XML-RPC multicalls
= 4.1.8 =
*Release Date - 6 January 2021*
* Fixed missing fields in submit-spam and submit-ham calls that could lead to reduced accuracy.
* Fixed usage of deprecated jQuery function.
= 4.1.7 =
*Release Date - 22 October 2020*
* Show the "Set up your Akismet account" banner on the comments admin screen, where it's relevant to mention if Akismet hasn't been configured.
* Don't use wp_blacklist_check when the new wp_check_comment_disallowed_list function is available.
= 4.1.6 =
*Release Date - 4 June 2020*
* Disable "Check for Spam" button until the page is loaded to avoid errors with clicking through to queue recheck endpoint directly.
* Added filter "akismet_enable_mshots" to allow disabling screenshot popups on the edit comments admin page.
= 4.1.5 =
*Release Date - 29 April 2020*
* Based on user feedback, we have dropped the in-admin notice explaining the availability of the "privacy notice" option in the AKismet settings screen. The option itself is available, but after displaying the notice for the last 2 years, it is now considered a known fact.
* Updated the "Requires at least" to WP 4.6, based on recommendations from https://wp-info.org/tools/checkplugini18n.php?slug=akismet
* Moved older changelog entries to a separate file to keep the size of this readme reasonable, also based on recommendations from https://wp-info.org/tools/checkplugini18n.php?slug=akismet
= 4.1.4 =
*Release Date - 17 March 2020*
* Only redirect to the Akismet setup screen upon plugin activation if the plugin was activated manually from within the plugin-related screens, to help users with non-standard install workflows, like WP-CLI.
* Update the layout of the initial setup screen to be more readable on small screens.
* If no API key has been entered, don't run code that expects an API key.
* Improve the readability of the comment history entries.
* Don't modify the comment form HTML if no API key has been set.
= 4.1.3 =
*Release Date - 31 October 2019*
* Prevented an attacker from being able to cause a user to unknowingly recheck their Pending comments for spam.
* Improved compatibility with Jetpack 7.7+.
* Updated the plugin activation page to use consistent language and markup.
* Redirecting users to the Akismet connnection/settings screen upon plugin activation, in an effort to make it easier for people to get setup.
= 4.1.2 =
*Release Date - 14 May 2019*
* Fixed a conflict between the Akismet setup banner and other plugin notices.
* Reduced the number of API requests made by the plugin when attempting to verify the API key.
* Include additional data in the pingback pre-check API request to help make the stats more accurate.
* Fixed a bug that was enabling the "Check for Spam" button when no comments were eligible to be checked.
* Improved Akismet's AMP compatibility.
= 4.1.1 =
*Release Date - 31 January 2019*
* Fixed the "Setup Akismet" notice so it resizes responsively.
* Only highlight the "Save Changes" button in the Akismet config when changes have been made.
* The count of comments in your spam queue shown on the dashboard show now always be up-to-date.
= 4.1 =
*Release Date - 12 November 2018*
* Added a WP-CLI method for retrieving stats.
* Hooked into the new "Personal Data Eraser" functionality from WordPress 4.9.6.
* Added functionality to clear outdated alerts from Akismet.com.
= 4.0.8 =
*Release Date - 19 June 2018*
* Improved the grammar and consistency of the in-admin privacy related notes (notice and config).
* Revised in-admin explanation of the comment form privacy notice to make its usage clearer.
* Added `rel="nofollow noopener"` to the comment form privacy notice to improve SEO and security.
= 4.0.7 =
*Release Date - 28 May 2018*
* Based on user feedback, the link on "Learn how your comment data is processed." in the optional privacy notice now has a `target` of `_blank` and opens in a new tab/window.
* Updated the in-admin privacy notice to use the term "comment" instead of "contact" in "Akismet can display a notice to your users under your comment forms."
* Only show in-admin privacy notice if Akismet has an API Key configured
= 4.0.6 =
*Release Date - 26 May 2018*
* Moved away from using `empty( get_option() )` to instantiating a variable to be compatible with older versions of PHP (5.3, 5.4, etc).
= 4.0.5 =
*Release Date - 26 May 2018*
* Corrected version number after tagging. Sorry...
= 4.0.4 =
*Release Date - 26 May 2018*
* Added a hook to provide Akismet-specific privacy information for a site's privacy policy.
* Added tools to control the display of a privacy related notice under comment forms.
* Fixed HTML in activation failure message to close META and HEAD tag properly.
* Fixed a bug that would sometimes prevent Akismet from being correctly auto-configured.
= 4.0.3 =
*Release Date - 19 February 2018*
* Added a scheduled task to remove entries in wp_commentmeta that no longer have corresponding comments in wp_comments.
* Added a new `akismet_batch_delete_count` action to the batch delete methods for people who'd like to keep track of the numbers of records being processed by those methods.
= 4.0.2 =
*Release Date - 18 December 2017*
* Fixed a bug that could cause Akismet to recheck a comment that has already been manually approved or marked as spam.
* Fixed a bug that could cause Akismet to claim that some comments are still waiting to be checked when no comments are waiting to be checked.
= 4.0.1 =
*Release Date - 6 November 2017*
* Fixed a bug that could prevent some users from connecting Akismet via their Jetpack connection.
* Ensured that any pending Akismet-related events are unscheduled if the plugin is deactivated.
* Allow some JavaScript to be run asynchronously to avoid affecting page render speeds.
= 4.0 =
*Release Date - 19 September 2017*
* Added REST API endpoints for configuring Akismet and retrieving stats.
* Increased the minimum supported WordPress version to 4.0.
* Added compatibility with comments submitted via the REST API.
* Improved the progress indicator on the "Check for Spam" button.
= 3.3.4 =
*Release Date - 3 August 2017*
* Disabled Akismet's debug log output by default unless AKISMET_DEBUG is defined.
* URL previews now begin preloading when the mouse moves near them in the comments section of wp-admin.
* When a comment is caught by the Comment Blacklist, Akismet will always allow it to stay in the trash even if it is spam as well.
* Fixed a bug that was preventing an error from being shown when a site can't reach Akismet's servers.
= 3.3.3 =
*Release Date - 13 July 2017*
* Reduced amount of bandwidth used by the URL Preview feature.
* Improved the admin UI when the API key is manually pre-defined for the site.
* Removed a workaround for WordPress installations older than 3.3 that will improve Akismet's compatibility with other plugins.
* The number of spam blocked that is displayed on the WordPress dashboard will now be more accurate and updated more frequently.
* Fixed a bug in the Akismet widget that could cause PHP warnings.
= 3.3.2 =
*Release Date - 10 May 2017*
* Fixed a bug causing JavaScript errors in some browsers.
= 3.3.1 =
*Release Date - 2 May 2017*
* Improve performance by only requesting the akismet_comment_nonce option when absolutely necessary.
* Fixed two bugs that could cause PHP warnings.
* Fixed a bug that was preventing the "Remove author URL" feature from working after a comment was edited using "Quick Edit."
* Fixed a bug that was preventing the URL preview feature from working after a comment was edited using "Quick Edit."
= 3.3 =
*Release Date - 23 February 2017*
* Updated the Akismet admin pages with a new clean design.
* Fixed bugs preventing the `akismet_add_comment_nonce` and `akismet_update_alert` wrapper functions from working properly.
* Fixed bug preventing the loading indicator from appearing when re-checking all comments for spam.
* Added a progress indicator to the "Check for Spam" button.
* Added a success message after manually rechecking the Pending queue for spam.
= 3.2 =
*Release Date - 6 September 2016*
* Added a WP-CLI module. You can now check comments and recheck the moderation queue from the command line.
* Stopped using the deprecated jQuery function `.live()`.
* Fixed a bug in `remove_comment_author_url()` and `add_comment_author_url()` that could generate PHP notices.
* Fixed a bug that could cause an infinite loop for sites with very very very large comment IDs.
* Fixed a bug that could cause the Akismet widget title to be blank.
= 3.1.11 =
*Release Date - 12 May 2016*
* Fixed a bug that could cause the "Check for Spam" button to skip some comments.
* Fixed a bug that could prevent some spam submissions from being sent to Akismet.
* Updated all links to use https:// when possible.
* Disabled Akismet debug logging unless WP_DEBUG and WP_DEBUG_LOG are both enabled.
= 3.1.10 =
*Release Date - 1 April 2016*
* Fixed a bug that could cause comments caught as spam to be placed in the Pending queue.
* Fixed a bug that could have resulted in comments that were caught by the core WordPress comment blacklist not to have a corresponding History entry.
* Fixed a bug that could have caused avoidable PHP warnings in the error log.
= 3.1.9 =
*Release Date - 28 March 2016*
* Add compatibility with Jetpack so that Jetpack can automatically configure Akismet settings when appropriate.
* Fixed a bug preventing some comment data from being sent to Akismet.
= 3.1.8 =
*Release Date - 4 March 2016*
* Fixed a bug preventing Akismet from being used with some plugins that rewrite admin URLs.
* Reduced the amount of bandwidth used on Akismet API calls
* Reduced the amount of space Akismet uses in the database
* Fixed a bug that could cause comments caught as spam to be placed in the Pending queue.
= 3.1.7 =
*Release Date - 4 January 2016*
* Added documentation for the 'akismet_comment_nonce' filter.
* The post-install activation button is now accessible to screen readers and keyboard-only users.
* Fixed a bug that was preventing the "Remove author URL" feature from working in WordPress 4.4
= 3.1.6 =
*Release Date - 14 December 2015*
* Improve the notices shown after activating Akismet.
* Update some strings to allow for the proper plural forms in all languages.
= 3.1.5 =
*Release Date - 13 October 2015*
* Closes a potential XSS vulnerability.
= 3.1.4 =
*Release Date - 24 September 2015*
* Fixed a bug that was preventing some users from automatically connecting using Jetpack if they didn't have a current Akismet subscription.
* Fixed a bug that could cause comments caught as spam to be placed in the Pending queue.
* Error messages and instructions have been simplified to be more understandable.
* Link previews are enabled for all links inside comments, not just the author's website link.
= 3.1.3 =
*Release Date - 6 July 2015*
* Notify users when their account status changes after previously being successfully set up. This should help any users who are seeing blank Akismet settings screens.
= 3.1.2 =
*Release Date - 7 June 2015*
* Reduced the amount of space Akismet uses in the commentmeta table.
* Fixed a bug where some comments with quotes in the author name weren't getting history entries
* Pre-emptive security improvements to ensure that the Akismet plugin can't be used by attackers to compromise a WordPress installation.
* Better UI for the key entry field: allow whitespace to be included at the beginning or end of the key and strip it out automatically when the form is submitted.
* When deactivating the plugin, notify the Akismet API so the site can be marked as inactive.
* Clearer error messages.
= 3.1.1 =
*Release Date - 17th March, 2015*
* Improvements to the "Remove comment author URL" JavaScript
* Include the pingback pre-check from the 2.6 branch.
= 3.1 =
*Release Date - 11th March, 2015*
* Use HTTPS by default for all requests to Akismet.
* Fix for a situation where Akismet might strip HTML from a comment.
= 3.0.4 =
*Release Date - 11th December, 2014*
* Fix to make .htaccess compatible with Apache 2.4.
* Fix to allow removal of https author URLs.
* Fix to avoid stripping part of the author URL when removing and re-adding.
* Removed the "Check for Spam" button from the "Trash" and "Approved" queues, where it would have no effect.
* Allow automatic API key configuration when Jetpack is installed and connected to a WordPress.com account
= 3.0.3 =
*Release Date - 3rd November, 2014*
* Fix for sending the wrong data to delete_comment action that could have prevented old spam comments from being deleted.
* Added a filter to disable logging of Akismet debugging information.
* Added a filter for the maximum comment age when deleting old spam comments.
* Added a filter for the number per batch when deleting old spam comments.
* Removed the "Check for Spam" button from the Spam folder.
= 3.0.2 =
*Release Date - 18th August, 2014*
* Performance improvements.
* Fixed a bug that could truncate the comment data being sent to Akismet for checking.
= 3.0.1 =
*Release Date - 9th July, 2014*
* Removed dependency on PHP's fsockopen function
* Fix spam/ham reports to work when reported outside of the WP dashboard, e.g., from Notifications or the WP app
* Remove jQuery dependency for comment form JavaScript
* Remove unnecessary data from some Akismet comment meta
* Suspended keys will now result in all comments being put in moderation, not spam.
= 3.0.0 =
*Release Date - 15th April, 2014*
* Move Akismet to Settings menu
* Drop Akismet Stats menu
* Add stats snapshot to Akismet settings
* Add Akismet subscription details and status to Akismet settings
* Add contextual help for each page
* Improve Akismet setup to use Jetpack to automate plugin setup
* Fix "Check for Spam" to use AJAX to avoid page timing out
* Fix Akismet settings page to be responsive
* Drop legacy code
* Tidy up CSS and Javascript
* Replace the old discard setting with a new "discard pervasive spam" feature.
= 2.6.0 =
*Release Date - 18th March, 2014*
* Add ajax paging to the check for spam button to handle large volumes of comments
* Optimize javascript and add localization support
* Fix bug in link to spam comments from right now dashboard widget
* Fix bug with deleting old comments to avoid timeouts dealing with large volumes of comments
* Include X-Pingback-Forwarded-For header in outbound WordPress pingback verifications
* Add pre-check for pingbacks, to stop spam before an outbound verification request is made
= 2.5.9 =
*Release Date - 1st August, 2013*
* Update 'Already have a key' link to redirect page rather than depend on javascript
* Fix some non-translatable strings to be translatable
* Update Activation banner in plugins page to redirect user to Akismet config page
= 2.5.8 =
*Release Date - 20th January, 2013*
* Simplify the activation process for new users
* Remove the reporter_ip parameter
* Minor preventative security improvements
= 2.5.7 =
*Release Date - 13th December, 2012*
* FireFox Stats iframe preview bug
* Fix mshots preview when using https
* Add .htaccess to block direct access to files
* Prevent some PHP notices
* Fix Check For Spam return location when referrer is empty
* Fix Settings links for network admins
* Fix prepare() warnings in WP 3.5
= 2.5.6 =
*Release Date - 26th April, 2012*
* Prevent retry scheduling problems on sites where wp_cron is misbehaving
* Preload mshot previews
* Modernize the widget code
* Fix a bug where comments were not held for moderation during an error condition
* Improve the UX and display when comments are temporarily held due to an error
* Make the Check For Spam button force a retry when comments are held due to an error
* Handle errors caused by an invalid key
* Don't retry comments that are too old
* Improve error messages when verifying an API key
= 2.5.5 =
*Release Date - 11th January, 2012*
* Add nonce check for comment author URL remove action
* Fix the settings link
= 2.5.4 =
*Release Date - 5th January, 2012*
* Limit Akismet CSS and Javascript loading in wp-admin to just the pages that need it
* Added author URL quick removal functionality
* Added mShot preview on Author URL hover
* Added empty index.php to prevent directory listing
* Move wp-admin menu items under Jetpack, if it is installed
* Purge old Akismet comment meta data, default of 15 days
= 2.5.3 =
*Release Date - 8th Febuary, 2011*
* Specify the license is GPL v2 or later
* Fix a bug that could result in orphaned commentmeta entries
* Include hotfix for WordPress 3.0.5 filter issue
= 2.5.2 =
*Release Date - 14th January, 2011*
* Properly format the comment count for author counts
* Look for super admins on multisite installs when looking up user roles
* Increase the HTTP request timeout
* Removed padding for author approved count
* Fix typo in function name
* Set Akismet stats iframe height to fixed 2500px. Better to have one tall scroll bar than two side by side.
= 2.5.1 =
*Release Date - 17th December, 2010*
* Fix a bug that caused the "Auto delete" option to fail to discard comments correctly
* Remove the comment nonce form field from the 'Akismet Configuration' page in favor of using a filter, akismet_comment_nonce
* Fixed padding bug in "author" column of posts screen
* Added margin-top to "cleared by ..." badges on dashboard
* Fix possible error when calling akismet_cron_recheck()
* Fix more PHP warnings
* Clean up XHTML warnings for comment nonce
* Fix for possible condition where scheduled comment re-checks could get stuck
* Clean up the comment meta details after deleting a comment
* Only show the status badge if the comment status has been changed by someone/something other than Akismet
* Show a 'History' link in the row-actions
* Translation fixes
* Reduced font-size on author name
* Moved "flagged by..." notification to top right corner of comment container and removed heavy styling
* Hid "flagged by..." notification while on dashboard
= 2.5.0 =
*Release Date - 7th December, 2010*
* Track comment actions under 'Akismet Status' on the edit comment screen
* Fix a few remaining deprecated function calls ( props Mike Glendinning )
* Use HTTPS for the stats IFRAME when wp-admin is using HTTPS
* Use the WordPress HTTP class if available
* Move the admin UI code to a separate file, only loaded when needed
* Add cron retry feature, to replace the old connectivity check
* Display Akismet status badge beside each comment
* Record history for each comment, and display it on the edit page
* Record the complete comment as originally submitted in comment_meta, to use when reporting spam and ham
* Highlight links in comment content
* New option, "Show the number of comments you've approved beside each comment author."
* New option, "Use a nonce on the comment form."
= 2.4.0 =
*Release Date - 23rd August, 2010*
* Spell out that the license is GPLv2
* Fix PHP warnings
* Fix WordPress deprecated function calls
* Fire the delete_comment action when deleting comments
* Move code specific for older WP versions to legacy.php
* General code clean up
= 2.3.0 =
*Release Date - 5th June, 2010*
* Fix "Are you sure" nonce message on config screen in WPMU
* Fix XHTML compliance issue in sidebar widget
* Change author link; remove some old references to WordPress.com accounts
* Localize the widget title (core ticket #13879)
= 2.2.9 =
*Release Date - 2nd June, 2010*
* Eliminate a potential conflict with some plugins that may cause spurious reports
= 2.2.8 =
*Release Date - 27th May, 2010*
* Fix bug in initial comment check for ipv6 addresses
* Report comments as ham when they are moved from spam to moderation
* Report comments as ham when clicking undo after spam
* Use transition_comment_status action when available instead of older actions for spam/ham submissions
* Better diagnostic messages when PHP network functions are unavailable
* Better handling of comments by logged-in users
= 2.2.7 =
*Release Date - 17th December, 2009*
* Add a new AKISMET_VERSION constant
* Reduce the possibility of over-counting spam when another spam filter plugin is in use
* Disable the connectivity check when the API key is hard-coded for WPMU
= 2.2.6 =
*Release Date - 20th July, 2009*
* Fix a global warning introduced in 2.2.5
* Add changelog and additional readme.txt tags
* Fix an array conversion warning in some versions of PHP
* Support a new WPCOM_API_KEY constant for easier use with WordPress MU
= 2.2.5 =
*Release Date - 13th July, 2009*
* Include a new Server Connectivity diagnostic check, to detect problems caused by firewalls
= 2.2.4 =
*Release Date - 3rd June, 2009*
* Fixed a key problem affecting the stats feature in WordPress MU
* Provide additional blog information in Akismet API calls
@@ -0,0 +1,91 @@
<?php
/**
* Registers Akismet abilities with the WordPress Abilities API.
*
* @package Akismet
* @since 5.7
*/
declare( strict_types = 1 );
// Load ability interface and classes.
require_once __DIR__ . '/abilities/interface-akismet-ability.php';
require_once __DIR__ . '/abilities/class-akismet-ability.php';
require_once __DIR__ . '/abilities/class-akismet-ability-get-stats.php';
require_once __DIR__ . '/abilities/class-akismet-ability-comment-check.php';
/**
* Class Akismet_Abilities
*
* Registers Akismet abilities with the WordPress Abilities API.
* Provides abilities for spam detection and comment moderation.
*/
class Akismet_Abilities {
/**
* The category slug for Akismet abilities.
*
* @var string
*/
const CATEGORY_SLUG = 'akismet';
/**
* Initialize the ability registration.
*
* @return void
*/
public static function init() {
// Register category.
if ( did_action( 'wp_abilities_api_categories_init' ) ) {
self::register_category();
} else {
add_action( 'wp_abilities_api_categories_init', array( __CLASS__, 'register_category' ) );
}
// Register abilities.
if ( did_action( 'wp_abilities_api_init' ) ) {
self::register_abilities();
} else {
add_action( 'wp_abilities_api_init', array( __CLASS__, 'register_abilities' ) );
}
}
/**
* Register the Akismet ability category.
*
* @return void
*/
public static function register_category() {
if ( ! function_exists( 'wp_register_ability_category' ) ) {
return;
}
wp_register_ability_category(
self::CATEGORY_SLUG,
array(
'label' => 'Akismet',
'description' => __( 'Abilities for spam protection and comment moderation with Akismet.', 'akismet' ),
)
);
}
/**
* Register all Akismet abilities.
*
* @return void
*/
public static function register_abilities() {
if ( ! function_exists( 'wp_register_ability' ) ) {
return;
}
$abilities = array(
Akismet_Ability_Get_Stats::class,
Akismet_Ability_Comment_Check::class,
);
foreach ( $abilities as $ability_class ) {
new $ability_class();
}
}
}
@@ -0,0 +1,309 @@
<?php
/**
* Handles compatibility checks for Akismet with other plugins.
*
* @package Akismet
* @since 5.4.0
*/
declare( strict_types = 1 );
// Following existing Akismet convention for file naming.
// phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase
/**
* Class for managing compatibility checks for Akismet with other plugins.
*
* This class includes methods for determining whether specific plugins are
* installed and active relative to the ability to work with Akismet.
*/
class Akismet_Compatible_Plugins {
/**
* The endpoint for the compatible plugins API.
*
* @var string
*/
protected const COMPATIBLE_PLUGIN_ENDPOINT = 'https://rest.akismet.com/1.2/compatible-plugins';
/**
* The error key for the compatible plugins API error.
*
* @var string
*/
protected const COMPATIBLE_PLUGIN_API_ERROR = 'akismet_compatible_plugins_api_error';
/**
* The valid fields for a compatible plugin object.
*
* @var array
*/
protected const COMPATIBLE_PLUGIN_FIELDS = array(
'slug',
'name',
'logo',
'help_url',
'path',
);
/**
* The cache key for the compatible plugins.
*
* @var string
*/
protected const CACHE_KEY = 'akismet_compatible_plugin_list';
/**
* How many plugins should be visible by default?
*
* @var int
*/
public const DEFAULT_VISIBLE_PLUGIN_COUNT = 2;
/**
* Get the list of active, installed compatible plugins.
*
* @param bool $bypass_cache Whether to bypass the cache and fetch fresh data.
* @return WP_Error|array {
* Array of active, installed compatible plugins with their metadata.
* @type string $name The display name of the plugin
* @type string $help_url URL to the plugin's help documentation
* @type string $logo URL or path to the plugin's logo
* }
*/
public static function get_installed_compatible_plugins( bool $bypass_cache = false ) {
// Retrieve and validate the full compatible plugins list.
$compatible_plugins = static::get_compatible_plugins( $bypass_cache );
if ( empty( $compatible_plugins ) ) {
return new WP_Error(
self::COMPATIBLE_PLUGIN_API_ERROR,
__( 'Error getting compatible plugins.', 'akismet' )
);
}
// Retrieve all installed plugins once.
$all_plugins = get_plugins();
// Build list of compatible plugins that are both installed and active.
$active_compatible_plugins = array();
foreach ( $compatible_plugins as $slug => $data ) {
$path = $data['path'];
// Skip if not installed.
if ( ! isset( $all_plugins[ $path ] ) ) {
continue;
}
// Check activation: per-site or network-wide (multisite).
$site_active = is_plugin_active( $path );
$network_active = is_multisite() && is_plugin_active_for_network( $path );
if ( $site_active || $network_active ) {
$active_compatible_plugins[ $slug ] = $data;
}
}
return $active_compatible_plugins;
}
/**
* Initializes action hooks for the class.
*
* @return void
*/
public static function init(): void {
add_action( 'activated_plugin', array( static::class, 'handle_plugin_change' ), true );
add_action( 'deactivated_plugin', array( static::class, 'handle_plugin_change' ), true );
}
/**
* Handles plugin activation and deactivation events.
*
* @param string $plugin The path to the main plugin file from plugins directory.
* @return void
*/
public static function handle_plugin_change( string $plugin ): void {
$cached_plugins = static::get_cached_plugins();
/**
* Terminate if nothing's cached.
*/
if ( false === $cached_plugins ) {
return;
}
$plugin_change_should_invalidate_cache = in_array( $plugin, array_column( $cached_plugins, 'path' ) );
/**
* Purge the cache if the plugin is activated or deactivated.
*/
if ( $plugin_change_should_invalidate_cache ) {
static::purge_cache();
}
}
/**
* Gets plugins that are compatible with Akismet from the Akismet API.
*
* @param bool $bypass_cache Whether to bypass the cache and fetch fresh data.
* @return array
*/
private static function get_compatible_plugins( bool $bypass_cache = false ): array {
// Return cached result if present (false => cache miss; empty array is valid).
$cached_plugins = static::get_cached_plugins();
if ( false !== $cached_plugins && ! $bypass_cache ) {
return $cached_plugins;
}
$response = wp_remote_get(
self::COMPATIBLE_PLUGIN_ENDPOINT
);
$sanitized = static::validate_compatible_plugin_response( $response );
if ( false === $sanitized ) {
return array();
}
/**
* Sets local static associative array of plugin data keyed by plugin slug.
*/
$compatible_plugins = array();
foreach ( $sanitized as $plugin ) {
$compatible_plugins[ $plugin['slug'] ] = $plugin;
}
static::set_cached_plugins( $compatible_plugins );
return $compatible_plugins;
}
/**
* Validates a response object from the Compatible Plugins API.
*
* @param array|WP_Error $response
* @return array|false
*/
private static function validate_compatible_plugin_response( $response ) {
/**
* Terminates the function if the response is a WP_Error object.
*/
if ( is_wp_error( $response ) ) {
return false;
}
/**
* The response returned is an array of header + body string data.
* This pops off the body string for processing.
*/
$response_body = wp_remote_retrieve_body( $response );
if ( empty( $response_body ) ) {
return false;
}
$plugins = json_decode( $response_body, true );
if ( false === is_array( $plugins ) ) {
return false;
}
foreach ( $plugins as $plugin ) {
if ( ! is_array( $plugin ) ) {
/**
* Skips to the next iteration if for some reason the plugin is not an array.
*/
continue;
}
// Ensure that the plugin config read in from the API has all the required fields.
$plugin_key_count = count(
array_intersect_key( $plugin, array_flip( static::COMPATIBLE_PLUGIN_FIELDS ) )
);
$does_not_have_all_required_fields = ! (
$plugin_key_count === count( static::COMPATIBLE_PLUGIN_FIELDS )
);
if ( $does_not_have_all_required_fields ) {
return false;
}
if ( false === static::has_valid_plugin_path( $plugin['path'] ) ) {
return false;
}
}
return static::sanitize_compatible_plugin_response( $plugins );
}
/**
* Validates a plugin path format.
*
* The path should be in the format of 'plugin-name/plugin-name.php'.
* Allows alphanumeric characters, dashes, underscores, and optional dots in folder names.
*
* @param string $path
* @return bool
*/
private static function has_valid_plugin_path( string $path ): bool {
return preg_match( '/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9_-]+\.php$/', $path ) === 1;
}
/**
* Sanitizes a response object from the Compatible Plugins API.
*
* @param array $plugins
* @return array
*/
private static function sanitize_compatible_plugin_response( array $plugins = array() ): array {
foreach ( $plugins as $key => $plugin ) {
$plugins[ $key ] = array_map( 'sanitize_text_field', $plugin );
$plugins[ $key ]['help_url'] = sanitize_url( $plugins[ $key ]['help_url'] );
$plugins[ $key ]['logo'] = sanitize_url( $plugins[ $key ]['logo'] );
}
return $plugins;
}
/**
* @param array $plugins
* @return bool
*/
private static function set_cached_plugins( array $plugins ): bool {
$_blog_id = (int) get_current_blog_id();
return set_transient(
static::CACHE_KEY . "_$_blog_id",
$plugins,
DAY_IN_SECONDS
);
}
/**
* Attempts to get cached compatible plugins.
*
* @return mixed|false
*/
private static function get_cached_plugins() {
$_blog_id = (int) get_current_blog_id();
return get_transient(
static::CACHE_KEY . "_$_blog_id"
);
}
/**
* Purges the cache for the compatible plugins.
*
* @return bool
*/
private static function purge_cache(): bool {
$_blog_id = (int) get_current_blog_id();
return delete_transient(
static::CACHE_KEY . "_$_blog_id"
);
}
}
@@ -0,0 +1,147 @@
<?php
/**
* Akismet Connector integration.
*
* @package Akismet
*/
declare( strict_types = 1 );
/**
* Integrates Akismet with the WordPress Connectors framework,
* handling API key validation and connection status reporting.
*/
class Akismet_Connector {
/**
* Register hooks for the WordPress Connectors integration.
*/
public static function init() {
add_action( 'wp_connectors_init', array( 'Akismet_Connector', 'register_connector' ) );
// Priority 9 so we validate the real key before core's connector masking filter at priority 10.
add_filter( 'rest_post_dispatch', array( 'Akismet_Connector', 'validate_api_key' ), 9, 3 );
add_filter( 'script_module_data_options-connectors-wp-admin', array( 'Akismet_Connector', 'set_connected_status' ), 11 );
// Invalidate the connector key status cache on any key change.
foreach ( array( 'add', 'update', 'delete' ) as $action ) {
add_action( "{$action}_option_wordpress_api_key", array( 'Akismet_Connector', 'invalidate_key_status_cache' ) );
}
}
/**
* Validate the Akismet API key when saved via the connectors REST settings endpoint.
* If the key is invalid, revert it to an empty string.
*
* @param WP_REST_Response $response The response object.
* @param WP_REST_Server $server The server instance.
* @param WP_REST_Request $request The request object.
* @return WP_REST_Response
*/
public static function validate_api_key( $response, $server, $request ) {
if ( '/wp/v2/settings' !== $request->get_route() ) {
return $response;
}
if ( 'POST' !== $request->get_method() && 'PUT' !== $request->get_method() ) {
return $response;
}
$data = $response->get_data();
if ( ! is_array( $data ) || ! array_key_exists( 'wordpress_api_key', $data ) ) {
return $response;
}
$key = $data['wordpress_api_key'];
if ( ! is_string( $key ) || '' === $key ) {
return $response;
}
if ( Akismet::KEY_STATUS_INVALID === Akismet::verify_key( $key ) ) {
update_option( 'wordpress_api_key', '' );
$data['wordpress_api_key'] = '';
$response->set_data( $data );
}
return $response;
}
/**
* Set the isConnected status for the Akismet connector based on actual key validity.
*
* @param array $data Script module data.
* @return array
*/
public static function set_connected_status( $data ) {
if ( ! isset( $data['connectors']['akismet']['authentication'] ) ) {
return $data;
}
$key = Akismet::get_api_key();
if ( empty( $key ) ) {
$data['connectors']['akismet']['authentication']['isConnected'] = false;
return $data;
}
$is_connected = get_transient( 'akismet_connector_key_status' );
if ( false === $is_connected ) {
$is_connected = Akismet::verify_key( $key );
// Don't cache failures (e.g. network timeouts) so we retry on the next page load.
if ( Akismet::KEY_STATUS_FAILED !== $is_connected ) {
set_transient( 'akismet_connector_key_status', $is_connected, DAY_IN_SECONDS );
}
}
$data['connectors']['akismet']['authentication']['isConnected'] = ( Akismet::KEY_STATUS_VALID === $is_connected );
return $data;
}
/**
* Clear the connector key status cache so it doesn't serve stale data.
*/
public static function invalidate_key_status_cache() {
delete_transient( 'akismet_connector_key_status' );
}
/**
* Register the Akismet connector with an is_active callback so the
* connectors page can detect Akismet as active when installed as a mu-plugin.
*
* We re-register the full connector rather than patching the core one
* so that Akismet still has a connector even if core removes its own.
*
* @see https://github.com/WordPress/gutenberg/pull/76994
*
* @param WP_Connector_Registry $registry Connector registry instance.
*/
public static function register_connector( $registry ) {
if ( method_exists( $registry, 'is_registered' ) && $registry->is_registered( 'akismet' ) ) {
$registry->unregister( 'akismet' );
}
$registry->register(
'akismet',
array(
'name' => __( 'Akismet Anti-spam', 'akismet' ),
'description' => __( 'Protect your site from spam.', 'akismet' ),
'type' => 'spam_filtering',
'plugin' => array(
'file' => 'akismet/akismet.php',
'is_active' => function () {
return defined( 'AKISMET_VERSION' );
},
),
'authentication' => array(
'method' => 'api_key',
'credentials_url' => 'https://akismet.com/get/',
'setting_name' => 'wordpress_api_key',
'constant_name' => 'WPCOM_API_KEY',
),
)
);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,186 @@
<?php
WP_CLI::add_command( 'akismet', 'Akismet_CLI' );
/**
* Filter spam comments.
*/
class Akismet_CLI extends WP_CLI_Command {
/**
* Checks one or more comments against the Akismet API.
*
* ## OPTIONS
* <comment_id>...
* : The ID(s) of the comment(s) to check.
*
* [--noaction]
* : Don't change the status of the comment. Just report what Akismet thinks it is.
*
* ## EXAMPLES
*
* wp akismet check 12345
*
* @alias comment-check
*/
public function check( $args, $assoc_args ) {
foreach ( $args as $comment_id ) {
if ( isset( $assoc_args['noaction'] ) ) {
// Check the comment, but don't reclassify it.
$api_response = Akismet::check_db_comment( $comment_id, 'wp-cli' );
} else {
$api_response = Akismet::recheck_comment( $comment_id, 'wp-cli' );
}
if ( 'true' === $api_response ) {
/* translators: %d: Comment ID. */
WP_CLI::line( sprintf( __( 'Comment #%d is spam.', 'akismet' ), $comment_id ) );
} elseif ( 'false' === $api_response ) {
/* translators: %d: Comment ID. */
WP_CLI::line( sprintf( __( 'Comment #%d is not spam.', 'akismet' ), $comment_id ) );
} elseif ( false === $api_response ) {
/* translators: %d: Comment ID. */
WP_CLI::error( __( 'Failed to connect to Akismet.', 'akismet' ) );
} elseif ( is_wp_error( $api_response ) ) {
/* translators: %d: Comment ID. */
WP_CLI::warning( sprintf( __( 'Comment #%d could not be checked.', 'akismet' ), $comment_id ) );
}
}
}
/**
* Recheck all comments in the Pending queue.
*
* ## EXAMPLES
*
* wp akismet recheck_queue
*
* @alias recheck-queue
*/
public function recheck_queue() {
$batch_size = 100;
$start = 0;
$total_counts = array();
do {
$result_counts = Akismet_Admin::recheck_queue_portion( $start, $batch_size );
if ( $result_counts['processed'] > 0 ) {
foreach ( $result_counts as $key => $count ) {
if ( ! isset( $total_counts[ $key ] ) ) {
$total_counts[ $key ] = $count;
} else {
$total_counts[ $key ] += $count;
}
}
$start += $batch_size;
$start -= $result_counts['spam']; // These comments will have been removed from the queue.
}
} while ( $result_counts['processed'] > 0 );
/* translators: %d: Number of comments. */
WP_CLI::line( sprintf( _n( 'Processed %d comment.', 'Processed %d comments.', $total_counts['processed'], 'akismet' ), number_format( $total_counts['processed'] ) ) );
/* translators: %d: Number of comments. */
WP_CLI::line( sprintf( _n( '%d comment moved to Spam.', '%d comments moved to Spam.', $total_counts['spam'], 'akismet' ), number_format( $total_counts['spam'] ) ) );
if ( $total_counts['error'] ) {
/* translators: %d: Number of comments. */
WP_CLI::line( sprintf( _n( '%d comment could not be checked.', '%d comments could not be checked.', $total_counts['error'], 'akismet' ), number_format( $total_counts['error'] ) ) );
}
}
/**
* Fetches stats from the Akismet API.
*
* ## OPTIONS
*
* [<interval>]
* : The time period for which to retrieve stats.
* ---
* default: all
* options:
* - days
* - months
* - all
* ---
*
* [--format=<format>]
* : Allows overriding the output of the command when listing connections.
* ---
* default: table
* options:
* - table
* - json
* - csv
* - yaml
* - count
* ---
*
* [--summary]
* : When set, will display a summary of the stats.
*
* ## EXAMPLES
*
* wp akismet stats
* wp akismet stats all
* wp akismet stats days
* wp akismet stats months
* wp akismet stats all --summary
*/
public function stats( $args, $assoc_args ) {
$api_key = Akismet::get_api_key();
if ( empty( $api_key ) ) {
WP_CLI::error( __( 'API key must be set to fetch stats.', 'akismet' ) );
}
switch ( $args[0] ) {
case 'days':
$interval = '60-days';
break;
case 'months':
$interval = '6-months';
break;
default:
$interval = 'all';
break;
}
$request_args = array(
'blog' => get_option( 'home' ),
'key' => $api_key,
'from' => $interval,
);
$request_args = apply_filters( 'akismet_request_args', $request_args, 'get-stats' );
$response = Akismet::http_post( Akismet::build_query( $request_args ), 'get-stats' );
if ( empty( $response[1] ) ) {
WP_CLI::error( __( 'Currently unable to fetch stats. Please try again.', 'akismet' ) );
}
$response_body = json_decode( $response[1], true );
if ( is_null( $response_body ) ) {
WP_CLI::error( __( 'Stats response could not be decoded.', 'akismet' ) );
}
if ( isset( $assoc_args['summary'] ) ) {
$keys = array(
'spam',
'ham',
'missed_spam',
'false_positives',
'accuracy',
'time_saved',
);
WP_CLI\Utils\format_items( $assoc_args['format'], array( $response_body ), $keys );
} else {
$stats = $response_body['breakdown'];
WP_CLI\Utils\format_items( $assoc_args['format'], $stats, array_keys( end( $stats ) ) );
}
}
}
@@ -0,0 +1,623 @@
<?php
class Akismet_REST_API {
/**
* Register the REST API routes.
*/
public static function init() {
if ( ! function_exists( 'register_rest_route' ) ) {
// The REST API wasn't integrated into core until 4.4, and we support 4.0+ (for now).
return false;
}
register_rest_route(
'akismet/v1',
'/key',
array(
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'get_key' ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'set_key' ),
'args' => array(
'key' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
'description' => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
),
),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'delete_key' ),
),
)
);
register_rest_route(
'akismet/v1',
'/settings/',
array(
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'get_settings' ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'set_boolean_settings' ),
'args' => array(
'akismet_strictness' => array(
'required' => false,
'type' => 'boolean',
'description' => __( 'If true, Akismet will automatically discard the worst spam automatically rather than putting it in the spam folder.', 'akismet' ),
),
'akismet_show_user_comments_approved' => array(
'required' => false,
'type' => 'boolean',
'description' => __( 'If true, show the number of approved comments beside each comment author in the comments list page.', 'akismet' ),
),
'akismet_enable_mcp_access' => array(
'required' => false,
'type' => 'boolean',
'description' => __( 'If true, allow MCP clients to access Akismet data and functionality.', 'akismet' ),
),
),
),
)
);
register_rest_route(
'akismet/v1',
'/stats',
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'get_stats' ),
'args' => array(
'interval' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_interval' ),
'description' => __( 'The time period for which to retrieve stats. Options: 60-days, 6-months, all', 'akismet' ),
'default' => 'all',
),
),
)
);
register_rest_route(
'akismet/v1',
'/stats/(?P<interval>[\w+])',
array(
'args' => array(
'interval' => array(
'description' => __( 'The time period for which to retrieve stats. Options: 60-days, 6-months, all', 'akismet' ),
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( 'Akismet_REST_API', 'privileged_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'get_stats' ),
),
)
);
register_rest_route(
'akismet/v1',
'/alert',
array(
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'get_alert' ),
'args' => array(
'key' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
'description' => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'set_alert' ),
'args' => array(
'key' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
'description' => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
),
),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
'callback' => array( 'Akismet_REST_API', 'delete_alert' ),
'args' => array(
'key' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => array( 'Akismet_REST_API', 'sanitize_key' ),
'description' => __( 'A 12-character Akismet API key. Available at akismet.com/account', 'akismet' ),
),
),
),
)
);
register_rest_route(
'akismet/v1',
'/webhook',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( 'Akismet_REST_API', 'receive_webhook' ),
'permission_callback' => array( 'Akismet_REST_API', 'remote_call_permission_callback' ),
)
);
}
/**
* Get the current Akismet API key.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function get_key( $request = null ) {
return rest_ensure_response( Akismet::get_api_key() );
}
/**
* Set the API key, if possible.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function set_key( $request ) {
if ( defined( 'WPCOM_API_KEY' ) ) {
return rest_ensure_response( new WP_Error( 'hardcoded_key', __( 'This site\'s API key is hardcoded and cannot be changed via the API.', 'akismet' ), array( 'status' => 409 ) ) );
}
$new_api_key = $request->get_param( 'key' );
if ( ! self::key_is_valid( $new_api_key ) ) {
return rest_ensure_response( new WP_Error( 'invalid_key', __( 'The value provided is not a valid and registered API key.', 'akismet' ), array( 'status' => 400 ) ) );
}
update_option( 'wordpress_api_key', $new_api_key );
return self::get_key();
}
/**
* Unset the API key, if possible.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function delete_key( $request ) {
if ( defined( 'WPCOM_API_KEY' ) ) {
return rest_ensure_response( new WP_Error( 'hardcoded_key', __( 'This site\'s API key is hardcoded and cannot be deleted.', 'akismet' ), array( 'status' => 409 ) ) );
}
delete_option( 'wordpress_api_key' );
return rest_ensure_response( true );
}
/**
* Get the Akismet settings.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function get_settings( $request = null ) {
return rest_ensure_response(
array(
'akismet_strictness' => ( get_option( 'akismet_strictness', '1' ) === '1' ),
'akismet_show_user_comments_approved' => ( get_option( 'akismet_show_user_comments_approved', '1' ) === '1' ),
'akismet_enable_mcp_access' => ( get_option( 'akismet_enable_mcp_access', '0' ) === '1' ),
)
);
}
/**
* Update the Akismet settings.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function set_boolean_settings( $request ) {
foreach ( array(
'akismet_strictness',
'akismet_show_user_comments_approved',
'akismet_enable_mcp_access',
) as $setting_key ) {
$setting_value = $request->get_param( $setting_key );
if ( is_null( $setting_value ) ) {
// This setting was not specified.
continue;
}
// From 4.7+, WP core will ensure that these are always boolean
// values because they are registered with 'type' => 'boolean',
// but we need to do this ourselves for prior versions.
$setting_value = self::parse_boolean( $setting_value );
update_option( $setting_key, $setting_value ? '1' : '0' );
}
return self::get_settings();
}
/**
* Parse a numeric or string boolean value into a boolean.
*
* @param mixed $value The value to convert into a boolean.
* @return bool The converted value.
*/
public static function parse_boolean( $value ) {
switch ( $value ) {
case true:
case 'true':
case '1':
case 1:
return true;
case false:
case 'false':
case '0':
case 0:
return false;
default:
return (bool) $value;
}
}
/**
* Get the Akismet stats for a given time period.
*
* Possible `interval` values:
* - all
* - 60-days
* - 6-months
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function get_stats( $request ) {
$api_key = Akismet::get_api_key();
$interval = $request->get_param( 'interval' );
$stat_totals = array();
$request_args = array(
'blog' => get_option( 'home' ),
'key' => $api_key,
'from' => $interval,
);
$request_args = apply_filters( 'akismet_request_args', $request_args, 'get-stats' );
$response = Akismet::http_post( Akismet::build_query( $request_args ), 'get-stats' );
if ( ! empty( $response[1] ) ) {
$stat_totals[ $interval ] = json_decode( $response[1] );
}
return rest_ensure_response( $stat_totals );
}
/**
* Get the current alert code and message. Alert codes are used to notify the site owner
* if there's a problem, like a connection issue between their site and the Akismet API,
* invalid requests being sent, etc.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function get_alert( $request ) {
return rest_ensure_response(
array(
'code' => get_option( 'akismet_alert_code' ),
'message' => get_option( 'akismet_alert_msg' ),
)
);
}
/**
* Update the current alert code and message by triggering a call to the Akismet server.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function set_alert( $request ) {
delete_option( 'akismet_alert_code' );
delete_option( 'akismet_alert_msg' );
// Make a request so the most recent alert code and message are retrieved.
Akismet::verify_key( Akismet::get_api_key() );
return self::get_alert( $request );
}
/**
* Clear the current alert code and message.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function delete_alert( $request ) {
delete_option( 'akismet_alert_code' );
delete_option( 'akismet_alert_msg' );
return self::get_alert( $request );
}
private static function key_is_valid( $key ) {
$request_args = array(
'key' => $key,
'blog' => get_option( 'home' ),
);
$request_args = apply_filters( 'akismet_request_args', $request_args, 'verify-key' );
$response = Akismet::http_post( Akismet::build_query( $request_args ), 'verify-key' );
if ( $response[1] == 'valid' ) {
return true;
}
return false;
}
public static function privileged_permission_callback() {
return current_user_can( 'manage_options' );
}
/**
* For calls that Akismet.com makes to the site to clear outdated alert codes, use the API key for authorization.
*/
public static function remote_call_permission_callback( $request ) {
$local_key = Akismet::get_api_key();
return $local_key && ( strtolower( $request->get_param( 'key' ) ?? '' ) === strtolower( $local_key ) );
}
public static function sanitize_interval( $interval, $request, $param ) {
$interval = trim( $interval );
$valid_intervals = array( '60-days', '6-months', 'all' );
if ( ! in_array( $interval, $valid_intervals ) ) {
$interval = 'all';
}
return $interval;
}
public static function sanitize_key( $key, $request, $param ) {
return trim( $key );
}
/**
* Process a webhook request from the Akismet servers.
*
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response
*/
public static function receive_webhook( $request ) {
Akismet::log( array( 'Webhook request received', $request->get_body() ) );
/**
* The request body should look like this:
* array(
* 'key' => '1234567890abcd',
* 'endpoint' => '[comment-check|submit-ham|submit-spam]',
* 'comments' => array(
* array(
* 'guid' => '[...]',
* 'result' => '[true|false]',
* 'comment_author' => '[...]',
* [...]
* ),
* array(
* 'guid' => '[...]',
* [...],
* ),
* [...]
* )
* )
*
* Multiple comments can be included in each request, and the only truly required
* field for each is the guid, although it would be friendly to include also
* comment_post_ID, comment_parent, and comment_author_email, if possible to make
* searching easier.
*/
// The response will include statuses for the result of each comment that was supplied.
$response = array(
'comments' => array(),
);
$endpoint = $request->get_param( 'endpoint' );
switch ( $endpoint ) {
case 'comment-check':
$webhook_comments = $request->get_param( 'comments' );
if ( ! is_array( $webhook_comments ) ) {
return rest_ensure_response( new WP_Error( 'malformed_request', __( 'The \'comments\' parameter must be an array.', 'akismet' ), array( 'status' => 400 ) ) );
}
foreach ( $webhook_comments as $webhook_comment ) {
$guid = $webhook_comment['guid'];
if ( ! $guid ) {
// Without the GUID, we can't be sure that we're matching the right comment.
// We'll make it a rule that any comment without a GUID is ignored intentionally.
continue;
}
// Search on the fields that are indexed in the comments table, plus the GUID.
// The GUID is the only thing we really need to search on, but comment_meta
// is not indexed in a useful way if there are many many comments. This
// should help narrow it down first.
$queryable_fields = array(
'comment_post_ID' => 'post_id',
'comment_parent' => 'parent',
'comment_author_email' => 'author_email',
);
$query_args = array();
$query_args['status'] = 'any';
$query_args['meta_key'] = 'akismet_guid';
$query_args['meta_value'] = $guid;
foreach ( $queryable_fields as $queryable_field => $wp_comment_query_field ) {
if ( isset( $webhook_comment[ $queryable_field ] ) ) {
$query_args[ $wp_comment_query_field ] = $webhook_comment[ $queryable_field ];
}
}
$comments_query = new WP_Comment_Query( $query_args );
$comments = $comments_query->comments;
if ( ! $comments ) {
// Unexpected, although the comment could have been deleted since being submitted.
Akismet::log( 'Webhook failed: no matching comment found.' );
$response['comments'][ $guid ] = array(
'status' => 'error',
'message' => __( 'Could not find matching comment.', 'akismet' ),
);
continue;
} if ( count( $comments ) > 1 ) {
// Two comments shouldn't be able to match the same GUID.
Akismet::log( 'Webhook failed: multiple matching comments found.', $comments );
$response['comments'][ $guid ] = array(
'status' => 'error',
'message' => __( 'Multiple comments matched request.', 'akismet' ),
);
continue;
} else {
// We have one single match, as hoped for.
Akismet::log( 'Found matching comment.', $comments );
$comment = $comments[0];
$current_status = wp_get_comment_status( $comment );
$result = $webhook_comment['result'];
if ( 'true' == $result ) {
Akismet::log( 'Comment should be spam' );
// The comment should be classified as spam.
if ( 'spam' != $current_status ) {
// The comment is not classified as spam. If Akismet was the one to act on it, move it to spam.
if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
Akismet::log( 'Comment is not spam; marking as spam.' );
wp_spam_comment( $comment );
Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-spam' );
} else {
Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-spam-noaction' );
}
}
} elseif ( 'false' == $result ) {
Akismet::log( 'Comment should be ham' );
// The comment should be classified as ham.
if ( 'spam' == $current_status ) {
Akismet::log( 'Comment is spam.' );
// The comment is classified as spam. If Akismet was the one to label it as spam, unspam it.
if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
Akismet::log( 'Akismet marked it as spam; unspamming.' );
wp_unspam_comment( $comment );
akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham' );
} else {
Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham-noaction' );
}
} else if ( 'unapproved' == $current_status ) {
Akismet::log( 'Comment is pending.' );
// The comment is in Pending. If Akismet was the one to put it there, approve it (but only if the site
// settings dictate that).
if ( Akismet::last_comment_status_change_came_from_akismet( $comment->comment_ID ) ) {
Akismet::log( 'Akismet marked it as Pending; approving.' );
if ( check_comment( $comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent, $comment->comment_type ) ) {
wp_set_comment_status( $comment->comment_ID, 1 );
}
akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham' );
} else {
Akismet::log( 'Comment is not spam, but it has already been manually handled by some other process.' );
Akismet::update_comment_history( $comment->comment_ID, '', 'webhook-ham-noaction' );
}
}
$moderation_email_was_delayed = get_comment_meta( $comment->comment_ID, 'akismet_delayed_moderation_email', true );
if ( $moderation_email_was_delayed ) {
Akismet::log( 'Moderation email was delayed for comment #' . $comment->comment_ID . '; sending now.' );
delete_comment_meta( $comment->comment_ID, 'akismet_delayed_moderation_email' );
wp_new_comment_notify_moderator( $comment->comment_ID );
wp_new_comment_notify_postauthor( $comment->comment_ID );
}
delete_comment_meta( $comment->comment_ID, 'akismet_delay_moderation_email' );
}
$response['comments'][ $guid ] = array( 'status' => 'success' );
}
}
break;
case 'submit-ham':
case 'submit-spam':
// Nothing to do for submit-ham or submit-spam.
break;
default:
// Unsupported endpoint.
break;
}
/**
* Allow plugins to do things with a successfully processed webhook request, like logging.
*
* @since 5.3.2
*
* @param WP_REST_Request $request The REST request object.
*/
do_action( 'akismet_webhook_received', $request );
Akismet::log( 'Done processing webhook.' );
return rest_ensure_response( $response );
}
}
@@ -0,0 +1,177 @@
<?php
/**
* @package Akismet
*/
// We plan to gradually remove all of the disabled lint rules below.
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
/**
* Akismet Widget Class
*/
class Akismet_Widget extends WP_Widget {
/**
* Constructor
*/
function __construct() {
parent::__construct(
'akismet_widget',
__( 'Akismet Widget', 'akismet' ),
array( 'description' => __( 'Display the number of spam comments Akismet has caught', 'akismet' ) )
);
}
/**
* Outputs the widget settings form
*
* @param array $instance The widget options
*/
public function form( $instance ) {
if ( $instance && isset( $instance['title'] ) ) {
$title = $instance['title'];
} else {
$title = __( 'Spam Blocked', 'akismet' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'akismet' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
/**
* Updates the widget settings
*
* @param array $new_instance New widget instance
* @param array $old_instance Old widget instance
* @return array Updated widget instance
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = sanitize_text_field( $new_instance['title'] );
return $instance;
}
/**
* Outputs the widget content
*
* @param array $args Widget arguments
* @param array $instance Widget instance
*/
public function widget( $args, $instance ) {
$count = get_option( 'akismet_spam_count' );
if ( ! isset( $instance['title'] ) ) {
$instance['title'] = __( 'Spam Blocked', 'akismet' );
}
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'];
echo esc_html( $instance['title'] );
echo $args['after_title'];
}
?>
<style>
.a-stats {
--akismet-color-mid-green: #357b49;
--akismet-color-white: #fff;
--akismet-color-light-grey: #f6f7f7;
max-width: 350px;
width: auto;
}
.a-stats * {
all: unset;
box-sizing: border-box;
}
.a-stats strong {
font-weight: 600;
}
.a-stats a.a-stats__link,
.a-stats a.a-stats__link:visited,
.a-stats a.a-stats__link:active {
background: var(--akismet-color-mid-green);
border: none;
box-shadow: none;
border-radius: 8px;
color: var(--akismet-color-white);
cursor: pointer;
display: block;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen-Sans', 'Ubuntu', 'Cantarell', 'Helvetica Neue', sans-serif;
font-weight: 500;
padding: 12px;
text-align: center;
text-decoration: none;
transition: all 0.2s ease;
}
/* Extra specificity to deal with TwentyTwentyOne focus style */
.widget .a-stats a.a-stats__link:focus {
background: var(--akismet-color-mid-green);
color: var(--akismet-color-white);
text-decoration: none;
}
.a-stats a.a-stats__link:hover {
filter: brightness(110%);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06), 0 0 2px rgba(0, 0, 0, 0.16);
}
.a-stats .count {
color: var(--akismet-color-white);
display: block;
font-size: 1.5em;
line-height: 1.4;
padding: 0 13px;
white-space: nowrap;
}
</style>
<div class="a-stats">
<a href="https://akismet.com?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=widget_stats" class="a-stats__link" target="_blank" rel="noopener" style="background-color: var(--akismet-color-mid-green); color: var(--akismet-color-white);">
<?php
echo wp_kses(
sprintf(
/* translators: The placeholder is the number of pieces of spam blocked by Akismet. */
_n(
'<strong class="count">%1$s spam</strong> blocked by <strong>Akismet</strong>',
'<strong class="count">%1$s spam</strong> blocked by <strong>Akismet</strong>',
$count,
'akismet'
),
number_format_i18n( $count )
),
array(
'strong' => array(
'class' => true,
),
)
);
?>
</a>
</div>
<?php
echo $args['after_widget'];
}
}
/**
* Register the Akismet widget
*/
function akismet_register_widgets() {
register_widget( 'Akismet_Widget' );
}
add_action( 'widgets_init', 'akismet_register_widgets' );
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
<?php
declare( strict_types = 1 );
// Silence is golden.
+160
View File
@@ -0,0 +1,160 @@
=== Akismet Anti-spam: Spam Protection ===
Contributors: matt, ryan, andy, mdawaffe, tellyworth, josephscott, lessbloat, eoigal, cfinke, automattic, jgs, procifer, stephdau, kbrownkd, bluefuton, derekspringer, lschuyler, andyperdomo, akismetantispam
Tags: comments, spam, antispam, anti-spam, contact form
Requires at least: 5.8
Tested up to: 7.0
Stable tag: 5.7
License: GPLv2 or later
The best anti-spam protection to block spam comments and spam in a contact form. The most trusted antispam solution for WordPress and WooCommerce.
== Description ==
The best anti-spam protection to block spam comments and spam in a contact form. The most trusted antispam solution for WordPress and WooCommerce.
Akismet checks your comments and contact form submissions against our global database of spam to prevent your site from publishing malicious content. You can review the comment spam it catches on your blog's "Comments" admin screen.
Major features in Akismet include:
* Automatically checks all comments and filters out the ones that look like spam.
* Each comment has a status history, so you can easily see which comments were caught or cleared by Akismet and which were spammed or unspammed by a moderator.
* URLs are shown in the comment body to reveal hidden or misleading links.
* Moderators can see the number of approved comments for each user.
* A discard feature that outright blocks the worst spam, saving you disk space and speeding up your site.
PS: You'll be prompted to get an Akismet.com API key to use it, once activated. Keys are free for personal blogs; paid subscriptions are available for businesses and commercial sites.
== Installation ==
Upload the Akismet plugin to your blog, activate it, and then enter your Akismet.com API key.
1, 2, 3: You're done!
== Changelog ==
= 5.7 =
*Release Date - 23 April 2026*
* Add Abilities API support for stats and comment checking, including MCP tool integration.
* Add support for the new Connectors page in the upcoming WordPress 7.0.
* Improve detection of automated spam submissions on the front end.
* Make comment history sorting more resilient when called with invalid data.
* Use wp_get_inline_script_tag() for safer inline script output, and other small security enhancements.
* Add action hooks to allow customization of the admin page header and footer.
* Accessibility improvements.
= 5.6 =
*Release Date - 12 November 2025*
* Improve caching of compatible plugins.
* Explain the key features of Akismet more clearly on the setup page.
* Improve the configuration process to better explain errors when they occur.
* Setup UI cleanup and refresh.
* Improve messaging related to usage limits.
= 5.5 =
*Release Date - 15 July 2025*
* Enable webhooks so that Akismet can process comments asynchronously to detect more types of spam.
* Only include the Akismet widget CSS when the Akismet widget is present
* Improve contrast/readability for certain UI elements
= 5.4 =
*Release Date - 7 May 2025*
* The stats pages now use the user's locale instead of the site's locale if they're different.
* Adds a 'Compatible plugins' section that will show installed and active plugins that are compatible with Akismet.
* Akismet now requires PHP version 7.2 or above.
= 5.3.7 =
*Release Date - 14 February 2025*
* Simplify the logic used during a comment-check request to compare comments.
= 5.3.6 =
*Release Date - 4 February 2025*
* Improve the utility of submit-spam and submit-ham requests.
* Modernize styles for the Akismet classic widget.
= 5.3.5 =
*Release Date - 18 November 2024*
* Address compatibility issues with < PHP 7.3 in v5.3.4 release.
= 5.3.4 =
*Release Date - 18 November 2024*
* Improve activation notice on Comments for users who haven't set up their API key yet.
* Improve notice about commercial site status.
= 5.3.3 =
*Release Date - 10 July 2024*
* Make setup step clearer for new users.
* Remove the stats section from the configuration page if the site has been revoked from the key.
* Skip the Akismet comment check when the comment matches something in the disallowed list.
* Prompt users on legacy plans to contact Akismet support for upgrades.
= 5.3.2 =
*Release Date - 21 March 2024*
* Improve the empty state shown to new users when no spam has been caught yet.
* Update the message shown to users without a current subscription.
* Add foundations for future webhook support.
= 5.3.1 =
*Release Date - 17 January 2024*
* Make the plugin more resilient when asset files are missing (as seen in WordPress Playground).
* Add a link to the 'Account overview' page on akismet.com.
* Fix a minor error that occurs when another plugin removes all comment actions from the dashboard.
* Add the akismet_request_args filter to allow request args in Akismet API requests to be filtered.
* Fix a bug that causes some contact forms to include unnecessary data in the comment_content parameter.
= 5.3 =
*Release Date - 14 September 2023*
* Improve display of user notices.
* Add stylesheets for RTL languages.
* Remove initial disabled state from 'Save changes' button.
* Improve accessibility of API key entry form.
* Add new filter hooks for Fluent Forms.
* Fix issue with PHP 8.1 compatibility.
= 5.2 =
*Release Date - 21 June 2023*
* Visual refresh of Akismet stats.
* Improve PHP 8.1 compatibility.
* Improve appearance of plugin to match updated stats.
* Change minimum supported PHP version to 5.6 to match WordPress.
* Drop IE11 support and update minimum WordPress version to 5.8 (where IE11 support was removed from WP Core).
= 5.1 =
*Release Date - 20 March 2023*
* Removed unnecessary limit notices from admin page.
* Improved spam detection by including post taxonomies in the comment-check call.
* Removed API keys from stats iframes to avoid possible inadvertent exposure.
= 5.0.2 =
*Release Date - 1 December 2022*
* Improved compatibility with themes that hide or show UI elements based on mouse movements.
* Increased security of API keys by sending them in request bodies instead of subdomains.
= 5.0.1 =
*Release Date - 28 September 2022*
* Added an empty state for the Statistics section on the admin page.
* Fixed a bug that broke some admin page links when Jetpack plugins are active.
* Marked some event listeners as passive to improve performance in newer browsers.
* Disabled interaction observation on forms that post to other domains.
= 5.0 =
*Release Date - 26 July 2022*
* Added a new feature to catch spammers by observing how they interact with the page.
For older changelog entries, please see the [additional changelog.txt file](https://plugins.svn.wordpress.org/akismet/trunk/changelog.txt) delivered with the plugin.
@@ -0,0 +1,7 @@
<div class="akismet-box">
<?php Akismet::view( 'setup' ); ?>
</div>
<div class="akismet-box">
<?php Akismet::view( 'enter' ); ?>
</div>
@@ -0,0 +1,125 @@
<?php
/** @var array|WP_Error $compatible_plugins */
$bypass_cache = ! empty( $_GET['akismet_refresh_compatible_plugins'] );
$compatible_plugins = Akismet_Compatible_Plugins::get_installed_compatible_plugins( $bypass_cache );
if ( is_array( $compatible_plugins ) ) :
$compatible_plugin_count = count( $compatible_plugins );
?>
<div class="akismet-card akismet-compatible-plugins">
<div class="akismet-section-header">
<h2 class="akismet-section-header__label akismet-compatible-plugins__section-header-label">
<?php esc_html_e( 'Compatible plugins', 'akismet' ); ?>
</h2>
</div>
<div class="akismet-compatible-plugins__content">
<?php
echo '<p>';
echo esc_html( __( 'Akismet works with other plugins to keep spam away.', 'akismet' ) );
echo '</p>';
echo '<p>';
if ( 0 === $compatible_plugin_count ) {
echo '<a class="akismet-external-link" href="https://akismet.com/developers/plugins-and-libraries/?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=compatible_plugins">';
echo esc_html( __( 'See supported integrations', 'akismet' ) );
echo '</a>';
} else {
echo esc_html(
_n(
"This plugin you've installed is compatible. Follow the documentation link to get started.",
"These plugins you've installed are compatible. Follow the documentation links to get started.",
$compatible_plugin_count,
'akismet'
)
);
}
echo '</p>';
?>
<?php if ( ! empty( $compatible_plugins ) ) : ?>
<ul class="akismet-compatible-plugins__list" id="akismet-compatible-plugins__list">
<?php
foreach ( $compatible_plugins as $compatible_plugin ) :
if ( empty( $compatible_plugin['help_url'] ) ) {
continue;
}
?>
<li class="akismet-compatible-plugins__card">
<?php if ( strlen( $compatible_plugin['logo'] ) > 0 ) : ?>
<?php
$logo_alt = sprintf(
/* translators: The placeholder is the name of a plugin, like "Jetpack" . */
__( '%s logo', 'akismet' ),
$compatible_plugin['name']
);
?>
<img
src="<?php echo esc_url( $compatible_plugin['logo'] ); ?>"
alt="<?php echo esc_attr( $logo_alt ); ?>"
class="akismet-compatible-plugins__card-logo"
width="36"
height="36"
/>
<?php endif ?>
<div class="akismet-compatible-plugins__card-detail">
<h3 class="akismet-compatible-plugins__card-title"><?php echo esc_html( $compatible_plugin['name'] ); ?></h3>
<div class="akismet-compatible-plugins__docs">
<a
class="akismet-external-link"
href="<?php echo esc_url( $compatible_plugin['help_url'] ); ?>"
aria-label="
<?php
echo esc_attr(
sprintf(
/* translators: The placeholder is the name of a plugin, like "Jetpack" . */
__( 'Documentation for %s', 'akismet' ),
$compatible_plugin['name']
)
);
?>
"><?php esc_html_e( 'View documentation', 'akismet' ); ?></a>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php if ( $compatible_plugin_count > Akismet_Compatible_Plugins::DEFAULT_VISIBLE_PLUGIN_COUNT ) : ?>
<button class="akismet-compatible-plugins__show-more"
aria-expanded="false"
aria-controls="akismet-compatible-plugins__list"
data-label-closed="
<?php
/* translators: %d: number of compatible plugins, which is guaranteed to be more than 1. */
echo esc_attr( sprintf( __( 'Show all %d plugins', 'akismet' ), $compatible_plugin_count ) );
?>
"
data-label-open="<?php echo esc_attr( __( 'Show less', 'akismet' ) ); ?>">
<?php
/* translators: %d: number of compatible plugins, which is guaranteed to be more than 1. */
echo esc_html( sprintf( __( 'Show all %d plugins', 'akismet' ), $compatible_plugin_count ) );
?>
</button>
<?php endif; ?>
<?php endif; ?>
</div>
</div>
<?php
endif;
+353
View File
@@ -0,0 +1,353 @@
<?php
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
$kses_allow_link_href = array(
'a' => array(
'href' => true,
),
);
?>
<div id="akismet-plugin-container">
<?php if ( has_action( 'akismet_header' ) ) : ?>
<?php do_action( 'akismet_header' ); ?>
<?php else : ?>
<div class="akismet-masthead">
<div class="akismet-masthead__inside-container">
<?php Akismet::view( 'logo' ); ?>
</div>
</div>
<?php endif; ?>
<div class="akismet-lower">
<?php if ( Akismet::get_api_key() ) { ?>
<?php Akismet_Admin::display_status(); ?>
<?php } ?>
<?php if ( ! empty( $notices ) ) { ?>
<?php foreach ( $notices as $notice ) { ?>
<?php Akismet::view( 'notice', array_merge( $notice, array( 'parent_view' => $name ) ) ); ?>
<?php } ?>
<?php } ?>
<?php if ( isset( $stat_totals['all'] ) && isset( $stat_totals['6-months'] ) ) : ?>
<div class="akismet-card">
<div class="akismet-section-header">
<h2 class="akismet-section-header__label">
<span><?php esc_html_e( 'Statistics', 'akismet' ); ?></span>
</h2>
</div> <!-- close akismet-section-header -->
<div class="akismet-new-snapshot">
<?php /* name attribute on iframe is used as a cache-buster here to force Firefox to load the new style charts: https://bugzilla.mozilla.org/show_bug.cgi?id=356558 */ ?>
<div class="akismet-new-snapshot__chart">
<iframe id="stats-iframe" allowtransparency="true" scrolling="no" frameborder="0" style="width: 100%; height: 220px; overflow: hidden;" src="<?php echo esc_url( sprintf( 'https://tools.akismet.com/1.0/snapshot.php?blog=%s&token=%s&height=200&locale=%s&is_redecorated=1', rawurlencode( get_option( 'home' ) ), rawurlencode( Akismet::get_access_token() ), get_user_locale() ) ); ?>" name="<?php echo esc_attr( 'snapshot-' . filemtime( __FILE__ ) ); ?>" title="<?php echo esc_attr__( 'Akismet stats', 'akismet' ); ?>"></iframe>
</div>
<ul class="akismet-new-snapshot__list">
<li class="akismet-new-snapshot__item">
<h3 class="akismet-new-snapshot__header"><?php esc_html_e( 'Past six months', 'akismet' ); ?></h3>
<span class="akismet-new-snapshot__number"><?php echo number_format( $stat_totals['6-months']->spam ); ?></span>
<span class="akismet-new-snapshot__text"><?php echo esc_html( _n( 'Spam blocked', 'Spam blocked', $stat_totals['6-months']->spam, 'akismet' ) ); ?></span>
</li>
<li class="akismet-new-snapshot__item">
<h3 class="akismet-new-snapshot__header"><?php esc_html_e( 'All time', 'akismet' ); ?></h3>
<span class="akismet-new-snapshot__number"><?php echo number_format( $stat_totals['all']->spam ); ?></span>
<span class="akismet-new-snapshot__text"><?php echo esc_html( _n( 'Spam blocked', 'Spam blocked', $stat_totals['all']->spam, 'akismet' ) ); ?></span>
</li>
<li class="akismet-new-snapshot__item">
<h3 class="akismet-new-snapshot__header"><?php esc_html_e( 'Accuracy', 'akismet' ); ?></h3>
<span class="akismet-new-snapshot__number"><?php echo floatval( $stat_totals['all']->accuracy ); ?>%</span>
<span class="akismet-new-snapshot__text">
<?php
/* translators: %s: number of spam missed by Akismet */
echo esc_html( sprintf( _n( '%s missed spam', '%s missed spam', $stat_totals['all']->missed_spam, 'akismet' ), number_format( $stat_totals['all']->missed_spam ) ) ) . ', ';
/* translators: %s: number of false positive spam flagged by Akismet */
echo esc_html( sprintf( _n( '%s false positive', '%s false positives', $stat_totals['all']->false_positives, 'akismet' ), number_format( $stat_totals['all']->false_positives ) ) );
?>
</span>
</li>
</ul>
</div> <!-- close akismet-new-snapshot -->
<a href="<?php echo esc_url( Akismet_Admin::get_page_url( 'stats' ) ); ?>" class="akismet-stats-footer">
<?php esc_html_e( 'View detailed stats', 'akismet' ); ?>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<polyline points="9 18 15 12 9 6"/>
</svg>
</a>
</div> <!-- close akismet-card -->
<?php endif; ?>
<?php if ( apply_filters( 'akismet_show_compatible_plugins', true ) ) : ?>
<?php Akismet::view( 'compatible-plugins' ); ?>
<?php endif; ?>
<?php if ( $akismet_user ) : ?>
<div class="akismet-card">
<div class="akismet-section-header">
<h2 class="akismet-section-header__label">
<span><?php esc_html_e( 'Settings', 'akismet' ); ?></span>
</h2>
</div>
<div class="inside">
<form action="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>" autocomplete="off" method="POST" id="akismet-settings-form">
<div class="akismet-settings">
<?php if ( ! Akismet::predefined_api_key() ) : ?>
<div class="akismet-settings__row">
<h3 class="akismet-settings__row-title">
<label class="akismet-settings__row-label" for="key"><?php esc_html_e( 'API key', 'akismet' ); ?></label>
</h3>
<div class="akismet-settings__row-input">
<div class="akismet-api-key-wrapper">
<input id="key" name="key" type="text" size="15" value="<?php echo esc_attr( get_option( 'wordpress_api_key' ) ); ?>" class="<?php echo esc_attr( 'regular-text code ' . $akismet_user->status ); ?>">
<button type="button" class="akismet-api-key-copy" aria-label="<?php esc_attr_e( 'Copy API key', 'akismet' ); ?>">
<?php include plugin_dir_path( __FILE__ ) . '../_inc/img/copy.svg'; ?>
</button>
</div>
</div>
</div>
<?php endif; ?>
<?php
//phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['ssl_status'] ) ) :
?>
<div class="akismet-settings__row">
<div class="akismet-settings__row-text">
<h3 class="akismet-settings__row-title"><?php esc_html_e( 'SSL status', 'akismet' ); ?></h3>
<div class="akismet-settings__row-description">
<?php if ( ! wp_http_supports( array( 'ssl' ) ) ) : ?>
<strong><?php esc_html_e( 'Disabled.', 'akismet' ); ?></strong>
<?php esc_html_e( 'Your Web server cannot make SSL requests; contact your Web host and ask them to add support for SSL requests.', 'akismet' ); ?>
<?php else : ?>
<?php $ssl_disabled = get_option( 'akismet_ssl_disabled' ); ?>
<?php if ( $ssl_disabled ) : ?>
<strong><?php esc_html_e( 'Temporarily disabled.', 'akismet' ); ?></strong>
<?php esc_html_e( 'Akismet encountered a problem with a previous SSL request and disabled it temporarily. It will begin using SSL for requests again shortly.', 'akismet' ); ?>
<?php else : ?>
<strong><?php esc_html_e( 'Enabled.', 'akismet' ); ?></strong>
<?php esc_html_e( 'All systems functional.', 'akismet' ); ?>
<?php endif; ?>
<?php endif; ?>
</div>
</div>
</div>
<?php endif; ?>
<div class="akismet-settings__row">
<div class="akismet-settings__row-text">
<h3 class="akismet-settings__row-title"><?php esc_html_e( 'Comments', 'akismet' ); ?></h3>
</div>
<div class="akismet-settings__row-input">
<label class="akismet-settings__row-input-label" for="akismet_show_user_comments_approved">
<input
name="akismet_show_user_comments_approved"
id="akismet_show_user_comments_approved"
value="1"
type="checkbox"
<?php
// If the option isn't set, or if it's enabled ('1'), or if it was enabled a long time ago ('true'), check the checkbox.
checked( true, ( in_array( get_option( 'akismet_show_user_comments_approved' ), array( false, '1', 'true' ), true ) ) );
?>
/>
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Show the number of approved comments beside each comment author.', 'akismet' ); ?>
</span>
</label>
</div>
</div>
<div class="akismet-settings__row is-radio">
<div class="akismet-settings__row-text">
<h3 class="akismet-settings__row-title"><?php esc_html_e( 'Spam filtering', 'akismet' ); ?></h3>
</div>
<div class="akismet-settings__row-input">
<fieldset>
<legend class="screen-reader-text">
<span><?php esc_html_e( 'Akismet Anti-spam strictness', 'akismet' ); ?></span>
</legend>
<div>
<label class="akismet-settings__row-input-label" for="akismet_strictness_1">
<input type="radio" name="akismet_strictness" id="akismet_strictness_1" value="1" <?php checked( '1', get_option( 'akismet_strictness' ) ); ?> />
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Silently discard the worst and most pervasive spam so I never see it.', 'akismet' ); ?>
</span>
</label>
</div>
<div>
<label class="akismet-settings__row-input-label" for="akismet_strictness_0">
<input type="radio" name="akismet_strictness" id="akismet_strictness_0" value="0" <?php checked( true, get_option( 'akismet_strictness' ) !== '1' ); ?> />
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Always put spam in the Spam folder for review.', 'akismet' ); ?>
</span>
</label>
</div>
</fieldset>
<div class="akismet-settings__row-note">
<strong><?php esc_html_e( 'Note:', 'akismet' ); ?></strong>
<?php
$delete_interval = max( 1, intval( apply_filters( 'akismet_delete_comment_interval', 15 ) ) );
$spam_folder_link = sprintf(
'<a href="%s">%s</a>',
esc_url( admin_url( 'edit-comments.php?comment_status=spam' ) ),
esc_html__( 'spam folder', 'akismet' )
);
// The _n() needs to be on one line so the i18n tooling can extract the translator comment.
/* translators: %1$s: spam folder link, %2$d: delete interval in days */
$delete_message = _n( 'Spam in the %1$s older than %2$d day is deleted automatically.', 'Spam in the %1$s older than %2$d days is deleted automatically.', $delete_interval, 'akismet' );
printf(
wp_kses( $delete_message, $kses_allow_link_href ),
wp_kses( $spam_folder_link, $kses_allow_link_href ),
esc_html( $delete_interval )
);
?>
</div>
</div>
</div>
<div class="akismet-settings__row is-radio">
<div class="akismet-settings__row-text">
<h3 class="akismet-settings__row-title"><?php esc_html_e( 'Privacy', 'akismet' ); ?></h3>
</div>
<div class="akismet-settings__row-input">
<fieldset>
<legend class="screen-reader-text">
<span><?php esc_html_e( 'Akismet privacy notice', 'akismet' ); ?></span>
</legend>
<div>
<label class="akismet-settings__row-input-label" for="akismet_comment_form_privacy_notice_display">
<input type="radio" name="akismet_comment_form_privacy_notice" id="akismet_comment_form_privacy_notice_display" value="display" <?php checked( 'display', get_option( 'akismet_comment_form_privacy_notice' ) ); ?> />
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Display a privacy notice under your comment forms.', 'akismet' ); ?>
</span>
</label>
</div>
<div>
<label class="akismet-settings__row-input-label" for="akismet_comment_form_privacy_notice_hide">
<input type="radio" name="akismet_comment_form_privacy_notice" id="akismet_comment_form_privacy_notice_hide" value="hide" <?php echo in_array( get_option( 'akismet_comment_form_privacy_notice' ), array( 'display', 'hide' ), true ) ? checked( 'hide', get_option( 'akismet_comment_form_privacy_notice' ), false ) : 'checked="checked"'; ?> />
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Do not display privacy notice.', 'akismet' ); ?>
</span>
</label>
</div>
</fieldset>
<div class="akismet-settings__row-note">
<?php esc_html_e( 'To help your site with transparency under privacy laws like the GDPR, Akismet can display a notice to your users under your comment forms.', 'akismet' ); ?>
</div>
</div>
</div>
<?php if ( apply_filters( 'akismet_show_mcp_setting', true ) ) : ?>
<div class="akismet-settings__row">
<div class="akismet-settings__row-text">
<h3 class="akismet-settings__row-title">
<?php esc_html_e( 'Tool access', 'akismet' ); ?>
</h3>
</div>
<div class="akismet-settings__row-input">
<label class="akismet-settings__row-input-label" for="akismet_enable_mcp_access">
<input
name="akismet_enable_mcp_access"
id="akismet_enable_mcp_access"
value="1"
type="checkbox"
<?php checked( '1', get_option( 'akismet_enable_mcp_access' ) ); ?>
/>
<span class="akismet-settings__row-label-text">
<?php esc_html_e( 'Allow ', 'akismet' ); ?><abbr title="<?php esc_attr_e( 'Model Context Protocol', 'akismet' ); ?>"><?php esc_html_e( 'MCP', 'akismet' ); ?></abbr><?php esc_html_e( ' clients to access Akismet data and functionality', 'akismet' ); ?>
</span>
</label>
<div class="akismet-settings__row-note">
<?php esc_html_e( 'MCP (Model Context Protocol) allows AI assistants to access Akismet statistics and spam checking features.', 'akismet' ); ?>
</div>
</div>
</div>
<?php endif; ?>
</div>
<div class="akismet-card-actions">
<?php if ( ! Akismet::predefined_api_key() ) : ?>
<div id="delete-action" class="akismet-card-actions__secondary-action">
<a class="submitdelete deletion" href="<?php echo esc_url( Akismet_Admin::get_page_url( 'delete_key' ) ); ?>"><?php esc_html_e( 'Disconnect this account', 'akismet' ); ?></a>
</div>
<?php endif; ?>
<?php wp_nonce_field( Akismet_Admin::NONCE ); ?>
<div id="publishing-action">
<input type="hidden" name="action" value="enter-key">
<input type="submit" name="submit" id="submit" class="akismet-button akismet-could-be-primary" value="<?php esc_attr_e( 'Save changes', 'akismet' ); ?>">
</div>
</div>
</form>
</div>
</div>
<?php if ( ! Akismet::predefined_api_key() ) : ?>
<div class="akismet-card">
<div class="akismet-section-header">
<h2 class="akismet-section-header__label">
<span><?php esc_html_e( 'Account', 'akismet' ); ?></span>
</h2>
</div>
<div class="inside">
<dl class="akismet-account">
<dt class="akismet-account__label"><?php esc_html_e( 'Subscription type', 'akismet' ); ?></dt>
<dd class="akismet-account__value"><?php echo esc_html( $akismet_user->account_name ); ?></dd>
<dt class="akismet-account__label"><?php esc_html_e( 'Status', 'akismet' ); ?></dt>
<dd class="akismet-account__value">
<?php
if ( Akismet::USER_STATUS_CANCELLED === $akismet_user->status ) :
esc_html_e( 'Cancelled', 'akismet' );
elseif ( Akismet::USER_STATUS_SUSPENDED === $akismet_user->status ) :
esc_html_e( 'Suspended', 'akismet' );
elseif ( Akismet::USER_STATUS_MISSING === $akismet_user->status ) :
esc_html_e( 'Missing', 'akismet' );
elseif ( Akismet::USER_STATUS_NO_SUB === $akismet_user->status ) :
esc_html_e( 'No subscription found', 'akismet' );
else :
esc_html_e( 'Active', 'akismet' );
endif;
?>
</dd>
<?php if ( $akismet_user->next_billing_date ) : ?>
<dt class="akismet-account__label"><?php esc_html_e( 'Next billing date', 'akismet' ); ?></dt>
<dd class="akismet-account__value"><?php echo esc_html( gmdate( 'F j, Y', $akismet_user->next_billing_date ) ); ?></dd>
<?php endif; ?>
</dl>
<div class="akismet-card-actions">
<?php if ( $akismet_user->status === Akismet::USER_STATUS_ACTIVE ) : ?>
<div class="akismet-card-actions__secondary-action">
<a href="https://akismet.com/account?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=account_overview" class="akismet-external-link" aria-label="Account overview on akismet.com"><?php esc_html_e( 'Account overview', 'akismet' ); ?></a>
</div>
<?php endif; ?>
<div id="publishing-action">
<?php
Akismet::view(
'get',
array(
'text' => ( $akismet_user->account_type === 'free-api-key' && $akismet_user->status === Akismet::USER_STATUS_ACTIVE ? __( 'Upgrade', 'akismet' ) : __( 'Change', 'akismet' ) ),
'redirect' => 'upgrade',
'utm_content' => ( $akismet_user->account_type === 'free-api-key' && $akismet_user->status === Akismet::USER_STATUS_ACTIVE ? 'config_upgrade' : 'config_change' ),
)
);
?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php Akismet::view( 'footer' ); ?>
</div>
@@ -0,0 +1,14 @@
<?php
declare( strict_types = 1 );
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
?>
<div class="akismet-box">
<?php Akismet::view( 'setup', array( 'use_jetpack_connection' => true ) ); ?>
<?php Akismet::view( 'setup-jetpack', array( 'akismet_user' => $akismet_user ) ); ?>
</div>
<div class="akismet-box">
<?php Akismet::view( 'enter' ); ?>
</div>
@@ -0,0 +1,14 @@
<div class="akismet-enter-api-key-box centered">
<button class="akismet-enter-api-key-box__reveal"><?php esc_html_e( 'Manually enter an API key', 'akismet' ); ?></button>
<div class="akismet-enter-api-key-box__form-wrapper">
<form action="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>" method="post">
<?php wp_nonce_field( Akismet_Admin::NONCE ); ?>
<input type="hidden" name="action" value="enter-key">
<h3 class="akismet-enter-api-key-box__header" id="akismet-enter-api-key-box__header"><?php esc_html_e( 'Enter your API key', 'akismet' ); ?></h3>
<div class="akismet-enter-api-key-box__input-wrapper">
<input id="key" name="key" type="text" size="15" value="" placeholder="<?php esc_attr_e( 'API key', 'akismet' ); ?>" class="akismet-enter-api-key-box__key-input regular-text code" aria-labelledby="akismet-enter-api-key-box__header">
<input type="submit" name="submit" id="submit" class="akismet-button" value="<?php esc_attr_e( 'Connect with API key', 'akismet' ); ?>">
</div>
</form>
</div>
</div>
@@ -0,0 +1,9 @@
<?php
/**
* Akismet footer template.
*
* Renders the akismet_footer action hook.
*/
declare( strict_types = 1 );
do_action( 'akismet_footer' );
+32
View File
@@ -0,0 +1,32 @@
<?php
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
$submit_classes_attr = 'akismet-button';
if ( isset( $classes ) && ( is_countable( $classes ) ? count( $classes ) : 0 ) > 0 ) {
$submit_classes_attr = implode( ' ', $classes );
}
$query_args = array(
'passback_url' => Akismet_Admin::get_page_url(),
'redirect' => isset( $redirect ) ? $redirect : 'plugin-signup',
);
// Set default UTM parameters, overriding with any provided values.
$utm_args = array(
'utm_source' => isset( $utm_source ) ? $utm_source : 'akismet_plugin',
'utm_medium' => isset( $utm_medium ) ? $utm_medium : 'in_plugin',
'utm_campaign' => isset( $utm_campaign ) ? $utm_campaign : 'plugin_static_link',
'utm_content' => isset( $utm_content ) ? $utm_content : 'get_view_link',
);
$query_args = array_merge( $query_args, $utm_args );
$url = add_query_arg( $query_args, 'https://akismet.com/get/' );
?>
<a href="<?php echo esc_url( $url ); ?>" class="<?php echo esc_attr( $submit_classes_attr ); ?>" target="_blank">
<?php echo esc_html( is_string( $text ) ? $text : '' ); ?>
<span class="screen-reader-text"><?php esc_html_e( '(opens in a new tab)', 'akismet' ); ?></span>
</a>
+13
View File
@@ -0,0 +1,13 @@
<?php
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
?>
<div class="akismet-masthead__logo-container">
<?php if ( isset( $include_logo_link ) && $include_logo_link === true ) : ?>
<a href="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>" class="akismet-masthead__logo-link">
<?php endif; ?>
<img class="akismet-masthead__logo" src="<?php echo esc_url( plugins_url( '../_inc/img/akismet-refresh-logo@2x.png', __FILE__ ) ); ?>" srcset="<?php echo esc_url( plugins_url( '../_inc/img/akismet-refresh-logo.svg', __FILE__ ) ); ?>" alt="Akismet logo" />
<?php if ( isset( $include_logo_link ) && $include_logo_link === true ) : ?>
</a>
<?php endif; ?>
</div>
+368
View File
@@ -0,0 +1,368 @@
<?php
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
$kses_allow_link = array(
'a' => array(
'href' => true,
'target' => true,
'class' => true,
),
);
$kses_allow_strong = array( 'strong' => true );
if ( ! isset( $type ) ) {
$type = false; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
}
/*
* Some notices (plugin, spam-check, spam-check-cron-disabled, alert and usage-limit) are also shown elsewhere in wp-admin, so have different classes applied so that they match the standard WordPress notice format.
*/
?>
<?php if ( $type === 'plugin' ) : ?>
<?php // Displayed on edit-comments.php to users who have not set up Akismet yet. ?>
<div class="updated" id="akismet-setup-prompt">
<form name="akismet_activate" action="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>" method="post">
<div class="akismet-activate">
<input type="submit" class="akismet-activate__button akismet-button" value="<?php esc_attr_e( 'Set up your Akismet account', 'akismet' ); ?>" />
<div class="akismet-activate__description">
<?php esc_html_e( 'Almost done! Configure Akismet and say goodbye to spam', 'akismet' ); ?>
</div>
</div>
</form>
</div>
<?php elseif ( $type === 'spam-check' ) : ?>
<?php // This notice is only displayed on edit-comments.php. ?>
<div class="notice notice-warning">
<p><strong><?php esc_html_e( 'Akismet has detected a problem.', 'akismet' ); ?></strong></p>
<p><?php esc_html_e( 'Some comments have not yet been checked for spam by Akismet. They have been temporarily held for moderation and will automatically be rechecked later.', 'akismet' ); ?></p>
<?php if ( ! empty( $link_text ) ) : ?>
<p><?php echo wp_kses( $link_text, $kses_allow_link ); ?></p>
<?php endif; ?>
</div>
<?php elseif ( $type === 'spam-check-cron-disabled' ) : ?>
<?php // This notice is only displayed on edit-comments.php. ?>
<div class="notice notice-warning">
<p><strong><?php esc_html_e( 'Akismet has detected a problem.', 'akismet' ); ?></strong></p>
<p><?php esc_html_e( 'WP-Cron has been disabled using the DISABLE_WP_CRON constant. Comment rechecks may not work properly.', 'akismet' ); ?></p>
</div>
<?php elseif ( $type === 'alert' && $code === Akismet::ALERT_CODE_COMMERCIAL && isset( $parent_view ) && $parent_view === 'config' ) : ?>
<?php // Display a different commercial warning alert on the config page ?>
<div class="akismet-card akismet-alert is-commercial">
<div>
<h3 class="akismet-alert-header"><?php esc_html_e( 'We detected commercial activity on your site', 'akismet' ); ?></h3>
<p class="akismet-alert-info">
<?php
/* translators: The placeholder is a URL. */
echo wp_kses( sprintf( __( 'Your current subscription is for <a class="akismet-external-link" href="%s">personal, non-commercial use</a>. Please upgrade your plan to continue using Akismet.', 'akismet' ), esc_url( 'https://akismet.com/support/getting-started/free-or-paid/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=commercial_support' ) ), $kses_allow_link );
?>
</p>
<p class="akismet-alert-info">
<?php
/* translators: The placeholder is a URL to the contact form. */
echo wp_kses( sprintf( __( 'If you believe your site should not be classified as commercial, <a class="akismet-external-link" href="%s">please get in touch</a>', 'akismet' ), esc_url( 'https://akismet.com/contact/?purpose=commercial&utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=commercial_contact' ) ), $kses_allow_link );
?>
</p>
</div>
<div class="akismet-alert-button-wrapper">
<?php
Akismet::view(
'get',
array(
'text' => __( 'Upgrade plan', 'akismet' ),
'classes' => array( 'akismet-alert-button', 'akismet-button' ),
'redirect' => 'upgrade',
'utm_content' => 'commercial_upgrade',
)
);
?>
</div>
</div>
<?php elseif ( $type === 'alert' ) : ?>
<div class="<?php echo isset( $parent_view ) && $parent_view === 'config' ? 'akismet-alert is-bad' : 'error'; ?>">
<?php /* translators: The placeholder is an error code returned by Akismet. */ ?>
<p><strong><?php printf( esc_html__( 'Akismet error code: %s', 'akismet' ), esc_html( $code ) ); ?></strong></p>
<p><?php echo isset( $msg ) ? esc_html( $msg ) : ''; ?></p>
<p>
<?php
echo wp_kses(
sprintf(
/* translators: the placeholder is a clickable URL that leads to more information regarding an error code. */
__( 'For more information, see the <a class="akismet-external-link" href="%s">error documentation on akismet.com</a>', 'akismet' ),
esc_url( 'https://akismet.com/developers/detailed-docs/errors/akismet-error-' . absint( $code ) . '?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=error_info' )
),
$kses_allow_link
);
?>
</p>
</div>
<?php elseif ( $type === 'notice' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php echo wp_kses( $notice_header, Akismet_Admin::get_notice_kses_allowed_elements() ); ?></h3>
<p>
<?php echo wp_kses( $notice_text, Akismet_Admin::get_notice_kses_allowed_elements() ); ?>
</p>
</div>
<?php elseif ( $type === 'missing-functions' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'Network functions are disabled.', 'akismet' ); ?></h3>
<p>
<?php
echo wp_kses( __( 'Your web host or server administrator has disabled PHP&#8217;s <code>gethostbynamel</code> function.', 'akismet' ), array_merge( $kses_allow_link, $kses_allow_strong, array( 'code' => true ) ) );
?>
</p>
<p>
<?php
/* translators: The placeholder is a URL. */
echo wp_kses( sprintf( __( 'Please contact your web host or firewall administrator and give them <a class="akismet-external-link" href="%s" target="_blank">this information about Akismet&#8217;s system requirements</a>', 'akismet' ), esc_url( 'https://akismet.com/akismet-hosting-faq/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=hosting_faq_php' ) ), array_merge( $kses_allow_link, $kses_allow_strong, array( 'code' => true ) ) );
?>
</p>
</div>
<?php elseif ( $type === 'servers-be-down' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'Your site can&#8217;t connect to the Akismet servers.', 'akismet' ); ?></h3>
<p>
<?php
/* translators: The placeholder is a URL. */
echo wp_kses( sprintf( __( 'Your firewall may be blocking Akismet from connecting to its API. Please contact your host and refer to <a class="akismet-external-link" href="%s" target="_blank">our guide about firewalls</a>', 'akismet' ), esc_url( 'https://akismet.com/akismet-hosting-faq/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=hosting_faq_firewall' ) ), $kses_allow_link );
?>
</p>
</div>
<?php elseif ( $type === 'cancelled' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'Your Akismet plan has been cancelled.', 'akismet' ); ?></h3>
<p>
<?php
/* translators: The placeholder is a URL. */
echo wp_kses( sprintf( __( 'Please visit <a class="akismet-external-link" href="%s" target="_blank">Akismet.com</a> to purchase a new subscription.', 'akismet' ), esc_url( 'https://akismet.com/pricing/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=pricing_cancelled' ) ), $kses_allow_link );
?>
</p>
</div>
<?php elseif ( $type === 'suspended' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'Your Akismet subscription is suspended.', 'akismet' ); ?></h3>
<p>
<?php
/* translators: The placeholder is a URL. */
echo wp_kses( sprintf( __( 'Please contact <a class="akismet-external-link" href="%s" target="_blank">Akismet support</a> for assistance.', 'akismet' ), esc_url( 'https://akismet.com/contact/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=support_suspended' ) ), $kses_allow_link );
?>
</p>
</div>
<?php elseif ( $type === 'active-notice' && $time_saved ) : ?>
<div class="akismet-alert is-neutral">
<h3 class="akismet-alert__heading"><?php echo esc_html( $time_saved ); ?></h3>
<p>
<?php
/* translators: the placeholder is a clickable URL to the Akismet account upgrade page. */
echo wp_kses( sprintf( __( 'You can help us fight spam and upgrade your account by <a class="akismet-external-link" href="%s" target="_blank">contributing a token amount</a>', 'akismet' ), esc_url( 'https://akismet.com/pricing?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=upgrade_contribution' ) ), $kses_allow_link );
?>
</p>
</div>
<?php elseif ( $type === 'missing' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'There is a problem with your API key.', 'akismet' ); ?></h3>
<p>
<?php
/* translators: The placeholder is a URL to the Akismet contact form. */
echo wp_kses( sprintf( __( 'Please contact <a class="akismet-external-link" href="%s" target="_blank">Akismet support</a> for assistance.', 'akismet' ), esc_url( 'https://akismet.com/contact/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=support_missing' ) ), $kses_allow_link );
?>
</p>
</div>
<?php elseif ( $type === 'no-sub' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'You don&#8217;t have an Akismet plan.', 'akismet' ); ?></h3>
<p>
<?php
/* translators: the placeholder is the URL to the Akismet pricing page. */
echo wp_kses( sprintf( __( 'Please <a class="akismet-external-link" href="%s" target="_blank">choose a free or paid plan</a> so Akismet can protect your site from spam.', 'akismet' ), esc_url( 'https://akismet.com/pricing?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=choose_plan' ) ), $kses_allow_link );
?>
</p>
<p><?php echo esc_html__( 'Once you\'ve chosen a plan, return here to complete your setup.', 'akismet' ); ?></p>
</div>
<?php elseif ( $type === 'new-key-valid' ) : ?>
<?php
global $wpdb;
$check_pending_link = false;
$at_least_one_comment_in_moderation = ! ! $wpdb->get_var( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved = '0' LIMIT 1" );
if ( $at_least_one_comment_in_moderation ) {
$check_pending_link = 'edit-comments.php?akismet_recheck=' . wp_create_nonce( 'akismet_recheck' );
}
?>
<div class="akismet-alert is-good">
<p><?php esc_html_e( 'Akismet is now protecting your site from spam.', 'akismet' ); ?></p>
<?php if ( $check_pending_link ) : ?>
<p>
<?php
echo wp_kses(
sprintf(
/* translators: The placeholder is a URL for checking pending comments. */
__( 'Would you like to <a href="%s">scan pending comments for spam</a>?', 'akismet' ),
esc_url( $check_pending_link )
),
$kses_allow_link
);
?>
</p>
<?php endif; ?>
</div>
<?php elseif ( $type === 'new-key-invalid' ) : ?>
<div class="akismet-alert is-bad">
<p><?php esc_html_e( 'The key you entered is invalid. Please double-check it.', 'akismet' ); ?></p>
</div>
<?php elseif ( $type === Akismet_Admin::NOTICE_EXISTING_KEY_INVALID ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php echo esc_html( __( 'Your API key is no longer valid.', 'akismet' ) ); ?></h3>
<p>
<?php
echo wp_kses(
sprintf(
/* translators: The placeholder is a URL to the Akismet contact form. */
__( 'Please enter a new key or <a class="akismet-external-link" href="%s" target="_blank">contact Akismet support</a>', 'akismet' ),
'https://akismet.com/contact/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=support_invalid_key'
),
$kses_allow_link
);
?>
</p>
</div>
<?php elseif ( $type === 'new-key-failed' ) : ?>
<div class="akismet-alert is-bad">
<h3 class="akismet-alert__heading"><?php esc_html_e( 'The API key you entered could not be verified.', 'akismet' ); ?></h3>
<p>
<?php
echo wp_kses(
sprintf(
/* translators: The placeholder is a URL. */
__( 'The connection to akismet.com could not be established. Please refer to <a class="akismet-external-link" href="%s" target="_blank">our guide about firewalls</a> and check your server configuration.', 'akismet' ),
'https://akismet.com/akismet-hosting-faq/?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=hosting_faq'
),
$kses_allow_link
);
?>
</p>
</div>
<?php elseif ( $type === 'usage-limit' && isset( Akismet::$limit_notices[ $code ] ) ) : ?>
<div class="error akismet-usage-limit-alert">
<div class="akismet-usage-limit-logo">
<img src="<?php echo esc_url( plugins_url( '../_inc/img/logo-a-2x.png', __FILE__ ) ); ?>" alt="Akismet logo" />
</div>
<div class="akismet-usage-limit-text">
<h3>
<?php
switch ( Akismet::$limit_notices[ $code ] ) {
case 'FIRST_MONTH_OVER_LIMIT':
case 'SECOND_MONTH_OVER_LIMIT':
esc_html_e( 'Your Akismet account usage is over your plan&#8217;s limit', 'akismet' );
break;
case 'THIRD_MONTH_APPROACHING_LIMIT':
esc_html_e( 'Your Akismet account usage is approaching your plan&#8217;s limit', 'akismet' );
break;
case 'THIRD_MONTH_OVER_LIMIT':
case 'FOUR_PLUS_MONTHS_OVER_LIMIT':
esc_html_e( 'Your account has been restricted', 'akismet' );
break;
default:
}
?>
</h3>
<p>
<?php
switch ( Akismet::$limit_notices[ $code ] ) {
case 'FIRST_MONTH_OVER_LIMIT':
echo esc_html(
sprintf(
/* translators: The first placeholder is a date, the second is a (formatted) number, the third is another formatted number. */
__( 'Since %1$s, your account made %2$s API calls, compared to your plan&#8217;s limit of %3$s.', 'akismet' ),
esc_html( gmdate( 'F' ) . ' 1' ),
number_format( $api_calls ),
number_format( $usage_limit )
)
);
echo '&nbsp;';
echo '<a class="akismet-external-link" href="https://akismet.com/support/general/akismet-api-usage-limits/?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=usage_limit_docs" target="_blank">';
echo esc_html( __( 'Learn more about usage limits', 'akismet' ) );
echo '</a>';
break;
case 'SECOND_MONTH_OVER_LIMIT':
echo esc_html( __( 'Your Akismet usage has been over your plan&#8217;s limit for two consecutive months. Next month, we will restrict your account after you reach the limit. Increase your limit to make sure your site stays protected from spam.', 'akismet' ) );
echo '&nbsp;';
echo '<a class="akismet-external-link" href="https://akismet.com/support/general/akismet-api-usage-limits/?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=usage_limit_docs" target="_blank">';
echo esc_html( __( 'Learn more about usage limits', 'akismet' ) );
echo '</a>';
break;
case 'THIRD_MONTH_APPROACHING_LIMIT':
echo esc_html( __( 'Your Akismet usage is nearing your plan&#8217;s limit for the third consecutive month. We will restrict your account after you reach the limit. Increase your limit to make sure your site stays protected from spam.', 'akismet' ) );
echo '&nbsp;';
echo '<a class="akismet-external-link" href="https://akismet.com/support/general/akismet-api-usage-limits/?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=usage_limit_docs" target="_blank">';
echo esc_html( __( 'Learn more about usage limits', 'akismet' ) );
echo '</a>';
break;
case 'THIRD_MONTH_OVER_LIMIT':
case 'FOUR_PLUS_MONTHS_OVER_LIMIT':
echo esc_html( __( 'Your Akismet usage has been over your plan&#8217;s limit for three consecutive months. We have restricted your account for the rest of the month. Increase your limit to make sure your site stays protected from spam.', 'akismet' ) );
echo '&nbsp;';
echo '<a class="akismet-external-link" href="https://akismet.com/support/general/akismet-api-usage-limits/?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=usage_limit_docs" target="_blank">';
echo esc_html( __( 'Learn more about usage limits', 'akismet' ) );
echo '</a>';
break;
default:
}
?>
</p>
</div>
<div class="akismet-usage-limit-cta">
<a href="<?php echo esc_url( $upgrade_url . ( strpos( $upgrade_url, '?' ) !== false ? '&' : '?' ) . 'utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=usage_limit_upgrade' ); ?>" class="button" target="_blank">
<?php
if ( isset( $upgrade_via_support ) && $upgrade_via_support ) {
// Direct user to contact support.
esc_html_e( 'Contact Akismet support', 'akismet' );
} elseif ( ! empty( $upgrade_type ) && 'qty' === $upgrade_type ) {
// If a qty upgrade is required, use recommended plan name if available.
if ( ! empty( $recommended_plan_name ) && is_string( $recommended_plan_name ) ) {
echo esc_html(
sprintf(
/* translators: The placeholder is the name of an Akismet subscription plan, like "Akismet Pro" or "Akismet Business" . */
__( 'Add an %s subscription', 'akismet' ),
$recommended_plan_name
)
);
} else {
esc_html_e( 'Increase your limit', 'akismet' );
}
} else {
echo esc_html(
sprintf(
/* translators: The placeholder is the name of a subscription level, like "Akismet Business" or "Akismet Enterprise" . */
__( 'Upgrade to %s', 'akismet' ),
$upgrade_plan
)
);
}
?>
</a>
</div>
</div>
<?php endif; ?>
@@ -0,0 +1,11 @@
<div class="akismet-box">
<h2><?php esc_html_e( 'Manual configuration', 'akismet' ); ?></h2>
<p>
<?php
/* translators: %s is the wp-config.php file */
printf( esc_html__( 'An Akismet API key has been defined in the %s file for this site.', 'akismet' ), '<code>wp-config.php</code>' );
?>
</p>
</div>
@@ -0,0 +1,97 @@
<?php
declare( strict_types = 1 );
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
$user_status = $akismet_user->status ?? null;
?>
<div class="akismet-setup__connection">
<?php if ( ! empty( $akismet_user->user_email ) && ! empty( $akismet_user->user_login ) ) : ?>
<div class="akismet-setup__connection-user">
<div class="akismet-setup__connection-avatar">
<?php
// Decorative avatar; empty alt for screen readers.
echo get_avatar(
$akismet_user->user_email,
48,
'',
'',
array(
'class' => 'akismet-setup__connection-avatar-image',
'alt' => '',
)
);
?>
<div class="akismet-setup__connection-account">
<div class="akismet-setup__connection-account-name">
<?php
printf(
/* translators: %s is the WordPress.com username */
esc_html__( 'Signed in as %s', 'akismet' ),
'<strong>' . esc_html( $akismet_user->user_login ) . '</strong>'
);
?>
</div>
<div class="akismet-setup__connection-account-email"><?php echo esc_html( $akismet_user->user_email ); ?></div>
</div>
</div>
</div>
<?php endif; ?>
<div class="akismet-setup__connection-action">
<?php if ( in_array( $user_status, array( Akismet::USER_STATUS_CANCELLED, Akismet::USER_STATUS_MISSING, Akismet::USER_STATUS_NO_SUB ) ) ) : ?>
<p class="akismet-setup__connection-action-intro">
<?php esc_html_e( "Your Jetpack account is connected, but it doesn't have an active Akismet subscription yet. To continue, please choose a plan on Akismet.com.", 'akismet' ); ?>
</p>
<a href="https://akismet.com/get?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=jetpack_flow_<?php echo esc_attr( str_replace( '-', '_', $user_status ) ); ?>" class="akismet-setup__connection-button akismet-button">
<?php esc_html_e( 'Choose a plan on Akismet.com', 'akismet' ); ?>
</a>
<p class="akismet-setup__connection-action-description">
<?php esc_html_e( "Once you've chosen a plan, return here to complete your setup.", 'akismet' ); ?>
</p>
<?php elseif ( $user_status === Akismet::USER_STATUS_SUSPENDED ) : ?>
<p class="akismet-setup__connection-action-intro">
<?php esc_html_e( "Your Akismet account appears to be suspended. This sometimes happens if there's a billing or verification issue. Please contact our support team so we can help you get it sorted.", 'akismet' ); ?>
</p>
<a href="https://akismet.com/contact?utm_source=akismet_plugin&amp;utm_campaign=plugin_static_link&amp;utm_medium=in_plugin&amp;utm_content=jetpack_flow_suspended" class="akismet-setup__connection-button akismet-button">
<?php esc_html_e( 'Contact support', 'akismet' ); ?>
</a>
<?php else : ?>
<form name="akismet_use_wpcom_key" action="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>" method="post" id="akismet-activate">
<input type="hidden" name="key" value="<?php echo esc_attr( $akismet_user->api_key ); ?>"/>
<input type="hidden" name="action" value="enter-key">
<?php wp_nonce_field( Akismet_Admin::NONCE ); ?>
<input type="submit" class="akismet-setup__connection-button akismet-button" value="<?php esc_attr_e( 'Connect with Jetpack', 'akismet' ); ?>"/>
</form>
<p class="akismet-setup__connection-action-description">
<?php esc_html_e( "By connecting, we'll use your Jetpack account to activate Akismet on this site.", 'akismet' ); ?>
</p>
<?php endif; ?>
<?php if ( ! in_array( $user_status, array( Akismet::USER_STATUS_CANCELLED, Akismet::USER_STATUS_MISSING, Akismet::USER_STATUS_NO_SUB ) ) ) : ?>
<p class="akismet-setup__connection-action-description">
<?php
echo wp_kses(
sprintf(
/* translators: The placeholder is a URL. */
__( 'Want to use a different account? <a href="%s" class="akismet-external-link">Visit akismet.com</a> to set it up and get your API key.', 'akismet' ),
esc_url( 'https://akismet.com/get?utm_source=akismet_plugin&utm_campaign=plugin_static_link&utm_medium=in_plugin&utm_content=jetpack_flow_different_account' )
),
array(
'a' => array(
'href' => array(),
'class' => array(),
),
)
);
?>
</p>
<?php endif; ?>
</div>
</div>
@@ -0,0 +1,78 @@
<?php
declare( strict_types = 1 );
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
$tick_icon = '<svg class="akismet-setup-instructions__icon" width="48" height="48" viewBox="0 0 48 48" aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<circle cx="24" cy="24" r="22" fill="#2E7D32"/>
<path d="M16 24l6 6 12-14" fill="none" stroke="#FFFFFF" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>';
?>
<section class="akismet-setup-instructions">
<h2 class="akismet-setup-instructions__heading"><?php esc_html_e( 'Eliminate spam from your site', 'akismet' ); ?></h2>
<h3 class="akismet-setup-instructions__subheading">
<?php echo esc_html__( 'Protect your site from comment spam and contact form spam — automatically.', 'akismet' ); ?>
</h3>
<ul class="akismet-setup-instructions__feature-list">
<li class="akismet-setup-instructions__feature">
<?php echo $tick_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<div class="akismet-setup-instructions__body">
<h4 class="akismet-setup-instructions__title">
<?php echo esc_html__( 'Machine learning accuracy', 'akismet' ); ?>
</h4>
<p class="akismet-setup-instructions__text">
<?php echo esc_html__( 'Learns from billions of spam signals across the web to stop junk before it reaches you.', 'akismet' ); ?>
</p>
</div>
</li>
<li class="akismet-setup-instructions__feature">
<?php echo $tick_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<div class="akismet-setup-instructions__body">
<h4 class="akismet-setup-instructions__title">
<?php echo esc_html__( 'Zero effort', 'akismet' ); ?>
</h4>
<p class="akismet-setup-instructions__text">
<?php echo esc_html__( 'Akismet runs quietly in the background, saving you hours of manual moderation.', 'akismet' ); ?>
</p>
</div>
</li>
<li class="akismet-setup-instructions__feature">
<?php echo $tick_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<div class="akismet-setup-instructions__body">
<h4 class="akismet-setup-instructions__title">
<?php echo esc_html__( 'Works with popular contact forms', 'akismet' ); ?>
</h4>
<p class="akismet-setup-instructions__text">
<?php echo esc_html__( 'Seamlessly integrates with plugins like Elementor, Contact Form 7, Jetpack and WPForms.', 'akismet' ); ?>
</p>
</div>
</li>
<li class="akismet-setup-instructions__feature">
<?php echo $tick_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<div class="akismet-setup-instructions__body">
<h4 class="akismet-setup-instructions__title">
<?php echo esc_html__( 'Flexible pricing', 'akismet' ); ?>
</h4>
<p class="akismet-setup-instructions__text">
<?php echo esc_html__( 'Name your own price for personal sites. Businesses start on a paid plan.', 'akismet' ); ?>
</p>
</div>
</li>
</ul>
<?php
if ( empty( $use_jetpack_connection ) ) :
Akismet::view(
'get',
array(
'text' => __( 'Get started', 'akismet' ),
'classes' => array( 'akismet-button', 'akismet-is-primary', 'akismet-setup-instructions__button' ),
'utm_content' => 'setup_instructions',
)
);
endif;
?>
</section>
@@ -0,0 +1,31 @@
<?php
//phpcs:disable VariableAnalysis
// There are "undefined" variables here because they're defined in the code that includes this file as a template.
?>
<div id="akismet-plugin-container">
<?php if ( has_action( 'akismet_header' ) ) : ?>
<?php do_action( 'akismet_header' ); ?>
<?php else : ?>
<div class="akismet-masthead">
<div class="akismet-masthead__inside-container">
<?php Akismet::view( 'logo' ); ?>
</div>
</div>
<?php endif; ?>
<div class="akismet-lower">
<?php Akismet_Admin::display_status(); ?>
<div class="akismet-boxes">
<?php
if ( Akismet::predefined_api_key() ) {
Akismet::view( 'predefined' );
} elseif ( $akismet_user && in_array( $akismet_user->status, array( Akismet::USER_STATUS_ACTIVE, Akismet::USER_STATUS_NO_SUB, Akismet::USER_STATUS_MISSING, Akismet::USER_STATUS_CANCELLED, Akismet::USER_STATUS_SUSPENDED ) ) ) {
Akismet::view( 'connect-jp', compact( 'akismet_user' ) );
} else {
Akismet::view( 'activate' );
}
?>
</div>
</div>
<?php Akismet::view( 'footer' ); ?>
</div>
@@ -0,0 +1,17 @@
<div id="akismet-plugin-container">
<?php if ( has_action( 'akismet_header' ) ) : ?>
<?php do_action( 'akismet_header' ); ?>
<?php else : ?>
<div class="akismet-masthead">
<div class="akismet-masthead__inside-container">
<?php Akismet::view( 'logo', array( 'include_logo_link' => true ) ); ?>
<div class="akismet-masthead__back-link-container">
<a class="akismet-masthead__back-link" href="<?php echo esc_url( Akismet_Admin::get_page_url() ); ?>"><?php esc_html_e( 'Back to settings', 'akismet' ); ?></a>
</div>
</div>
</div>
<?php endif; ?>
<?php /* name attribute on iframe is used as a cache-buster here to force Firefox to load the new style charts: https://bugzilla.mozilla.org/show_bug.cgi?id=356558 */ ?>
<iframe id="stats-iframe" src="<?php echo esc_url( sprintf( 'https://tools.akismet.com/1.0/user-stats.php?blog=%s&token=%s&locale=%s&is_redecorated=1', urlencode( get_option( 'home' ) ), urlencode( Akismet::get_access_token() ), esc_attr( get_user_locale() ) ) ); ?>" name="<?php echo esc_attr( 'user-stats- ' . filemtime( __FILE__ ) ); ?>" width="100%" height="2500px" frameborder="0" title="<?php echo esc_attr__( 'Akismet detailed stats', 'akismet' ); ?>"></iframe>
<?php Akismet::view( 'footer' ); ?>
</div>
+215
View File
@@ -0,0 +1,215 @@
<?php
global $wpcom_api_key, $akismet_api_host, $akismet_api_port;
$wpcom_api_key = defined( 'WPCOM_API_KEY' ) ? constant( 'WPCOM_API_KEY' ) : '';
$akismet_api_host = Akismet::get_api_key() . '.rest.akismet.com';
$akismet_api_port = 80;
function akismet_test_mode() {
return Akismet::is_test_mode();
}
function akismet_http_post( $request, $host, $path, $port = 80, $ip = null ) {
$path = str_replace( '/1.1/', '', $path );
return Akismet::http_post( $request, $path, $ip );
}
function akismet_microtime() {
return Akismet::_get_microtime();
}
function akismet_delete_old() {
return Akismet::delete_old_comments();
}
function akismet_delete_old_metadata() {
return Akismet::delete_old_comments_meta();
}
function akismet_check_db_comment( $id, $recheck_reason = 'recheck_queue' ) {
return Akismet::check_db_comment( $id, $recheck_reason );
}
function akismet_rightnow() {
if ( ! class_exists( 'Akismet_Admin' ) ) {
return false;
}
return Akismet_Admin::rightnow_stats();
}
function akismet_admin_init() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_version_warning() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_load_js_and_css() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_nonce_field( $action = -1 ) {
return wp_nonce_field( $action );
}
function akismet_plugin_action_links( $links, $file ) {
return Akismet_Admin::plugin_action_links( $links, $file );
}
function akismet_conf() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_stats_display() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_stats() {
return Akismet_Admin::dashboard_stats();
}
function akismet_admin_warnings() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_comment_row_action( $a, $comment ) {
return Akismet_Admin::comment_row_actions( $a, $comment );
}
function akismet_comment_status_meta_box( $comment ) {
return Akismet_Admin::comment_status_meta_box( $comment );
}
function akismet_comments_columns( $columns ) {
_deprecated_function( __FUNCTION__, '3.0' );
return $columns;
}
function akismet_comment_column_row( $column, $comment_id ) {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_text_add_link_callback( $m ) {
return Akismet_Admin::text_add_link_callback( $m );
}
function akismet_text_add_link_class( $comment_text ) {
return Akismet_Admin::text_add_link_class( $comment_text );
}
function akismet_check_for_spam_button( $comment_status ) {
return Akismet_Admin::check_for_spam_button( $comment_status );
}
function akismet_submit_nonspam_comment( $comment_id ) {
return Akismet::submit_nonspam_comment( $comment_id );
}
function akismet_submit_spam_comment( $comment_id ) {
return Akismet::submit_spam_comment( $comment_id );
}
function akismet_transition_comment_status( $new_status, $old_status, $comment ) {
return Akismet::transition_comment_status( $new_status, $old_status, $comment );
}
function akismet_spam_count( $type = false ) {
return Akismet_Admin::get_spam_count( $type );
}
function akismet_recheck_queue() {
return Akismet_Admin::recheck_queue();
}
function akismet_remove_comment_author_url() {
return Akismet_Admin::remove_comment_author_url();
}
function akismet_add_comment_author_url() {
return Akismet_Admin::add_comment_author_url();
}
function akismet_check_server_connectivity() {
return Akismet_Admin::check_server_connectivity();
}
function akismet_get_server_connectivity( $cache_timeout = 86400 ) {
return Akismet_Admin::get_server_connectivity( $cache_timeout );
}
function akismet_server_connectivity_ok() {
_deprecated_function( __FUNCTION__, '3.0' );
return true;
}
function akismet_admin_menu() {
return Akismet_Admin::admin_menu();
}
function akismet_load_menu() {
return Akismet_Admin::load_menu();
}
function akismet_init() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_get_key() {
return Akismet::get_api_key();
}
function akismet_check_key_status( $key, $ip = null ) {
return Akismet::check_key_status( $key, $ip );
}
function akismet_update_alert( $response ) {
return Akismet::update_alert( $response );
}
function akismet_verify_key( $key, $ip = null ) {
return Akismet::verify_key( $key, $ip );
}
function akismet_get_user_roles( $user_id ) {
return Akismet::get_user_roles( $user_id );
}
function akismet_result_spam( $approved ) {
return Akismet::comment_is_spam( $approved );
}
function akismet_result_hold( $approved ) {
return Akismet::comment_needs_moderation( $approved );
}
function akismet_get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) {
return Akismet::get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url );
}
function akismet_update_comment_history( $comment_id, $message, $event = null ) {
return Akismet::update_comment_history( $comment_id, $message, $event );
}
function akismet_get_comment_history( $comment_id ) {
return Akismet::get_comment_history( $comment_id );
}
function akismet_cmp_time( $a, $b ) {
return Akismet::_cmp_time( $a, $b );
}
function akismet_auto_check_update_meta( $id, $comment ) {
return Akismet::auto_check_update_meta( $id, $comment );
}
function akismet_auto_check_comment( $commentdata ) {
return Akismet::auto_check_comment( $commentdata );
}
function akismet_get_ip_address() {
return Akismet::get_ip_address();
}
function akismet_cron_recheck() {
return Akismet::cron_recheck();
}
function akismet_add_comment_nonce( $post_id ) {
return Akismet::add_comment_nonce( $post_id );
}
function akismet_fix_scheduled_recheck() {
return Akismet::fix_scheduled_recheck();
}
function akismet_spam_comments() {
_deprecated_function( __FUNCTION__, '3.0' );
return array();
}
function akismet_spam_totals() {
_deprecated_function( __FUNCTION__, '3.0' );
return array();
}
function akismet_manage_page() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_caught() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function redirect_old_akismet_urls() {
_deprecated_function( __FUNCTION__, '3.0' );
}
function akismet_kill_proxy_check( $option ) {
_deprecated_function( __FUNCTION__, '3.0' );
return 0;
}
function akismet_pingback_forwarded_for( $r, $url ) {
// This functionality is now in core.
return false;
}
function akismet_pre_check_pingback( $method ) {
return Akismet::pre_check_pingback( $method );
}
@@ -0,0 +1,56 @@
<?php
namespace FluentCrm\App\Api;
/**
* Internal PHP API Class
*
* Please do not use this class directly. use FluentCrmApi($module) instead.
*
* @package FluentCrm\App\Api\Classes
*
* @version 1.0.0
*/
final class Api
{
public $app;
public function __construct($app)
{
$this->app = $app;
$this->register();
}
private function register()
{
foreach ($this->getClasses() as $key => $class) {
$this->app->singleton($this->key($key), function($app) use ($class) {
return new FCApi($app->make($class));
});
}
}
private function getClasses()
{
return require_once(
$this->app['path.app'].'Api/config.php'
);
}
private function key($key)
{
return '__fluentcrm_api__.' . $key;
}
public function __get($key)
{
try {
return $this->app[$this->key($key)];
} catch(\Exception $e) {
/* translators: %s: requested FluentCRM API module key */
throw new \Exception(sprintf(esc_html__("The '%s' doesn't exist in FluentCrmApi.", 'fluent-crm'), esc_html($key)));
}
}
}
@@ -0,0 +1,203 @@
<?php
namespace FluentCrm\App\Api\Classes;
defined('ABSPATH') || exit;
use FluentCrm\App\Models\Company;
use FluentCrm\App\Models\CustomCompanyField;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\Framework\Support\Arr;
/**
* Company Class - PHP APi Wrapper
*
* Company API Wrapper Class that can be used as <code>FluentCrmApi('companies')</code> to get the class instance
*
* @package FluentCrm\App\Api\Classes
* @namespace FluentCrm\App\Api\Classes
*
* @version 2.8.0
*/
class Companies
{
private $instance = null;
private $allowedInstanceMethods = [
'all',
'get',
'find',
'first',
'paginate'
];
public function __construct(Company $instance)
{
$this->instance = $instance;
}
public function getCompany($idOrName, $with = [])
{
if (is_numeric($idOrName)) {
return Company::where('id', $idOrName)->with($with)->first();
}
if (is_string($idOrName)) {
return Company::where('email', $idOrName)->with($with)->first();
}
return false;
}
public function createOrUpdate($data)
{
$exist = null;
if (!empty($data['id'])) {
$exist = Company::where('id', $data['id'])->first();
} else {
$exist = Company::where('name', $data['name'])->first();
}
if ($exist) {
if (!empty($data['owner_id']) && $data['owner_id'] != $exist->owner_id) {
$contact = Subscriber::find($data['owner_id']);
if ($contact) {
$contact->attachCompanies([$exist->id]);
if (empty($contact->company_id)) {
$contact->company_id = $exist->id;
$contact->save();
}
}
}
if (isset($data['custom_values'])) {
$existingMeta = $exist->meta;
$values = Arr::get($data, 'custom_values', []);
$values = (new CustomCompanyField())->formatCustomFieldValues($values);
$temp = $existingMeta['custom_values'];
foreach ($values as $key => $value)
{
$temp[$key] = $value;
}
$existingMeta['custom_values'] = $temp;
$exist->meta = $existingMeta;
unset($data['custom_values']);
}
$exist->fill($data);
$exist->save();
do_action('fluent_crm/company_updated', $exist, $data);
return $exist;
} else if (empty($data['name'])) {
return false;
}
$fillables = (new Company())->getFillable();
$fillables[] = 'custom_values';
$data = Arr::only($data, $fillables);
$values = Arr::get($data, 'custom_values', []);
$values = (new CustomCompanyField())->formatCustomFieldValues($values);
$data['meta'] = [
'custom_values' => $values
];
$company = Company::create($data);
do_action('fluent_crm/company_created', $company, $data);
if ($company->owner_id) {
$owner = Subscriber::find($company->owner_id);
if ($owner) {
$owner->attachCompanies([$company->id]);
if (empty($owner->company_id)) {
$owner->company_id = $company->id;
$owner->save();
}
}
}
return $company;
}
public function attachContactsByIds($contactIds, $companyIds)
{
$companyIds = array_map('intval', $companyIds);
$subscriberIds = array_map('intval', $contactIds);
$subscribers = Subscriber::whereIn('id', $subscriberIds)->get();
$companies = Company::whereIn('id', $companyIds)->get();
if ((count($companyIds) != count($companies)) || $subscribers->isEmpty() || $companies->isEmpty()) {
return false;
}
$firstCompanyId = $companyIds[0];
$validIds = [];
foreach ($companies as $company) {
$validIds[] = $company->id;
}
foreach ($subscribers as $subscriber) {
$subscriber->attachCompanies($validIds);
if (!$subscriber->company_id) {
$subscriber->company_id = $firstCompanyId;
$subscriber->save();
}
}
return [
'companies' => $companies,
'subscribers' => $subscribers
];
}
public function detachContactsByIds($contactIds, $companyIds)
{
$companyIds = array_map('intval', $companyIds);
$subscriberIds = array_map('intval', $contactIds);
$subscribers = Subscriber::whereIn('id', $subscriberIds)->get();
$companies = Company::whereIn('id', $companyIds)->get();
if ((count($companyIds) != count($companies)) || $subscribers->isEmpty() || $companies->isEmpty()) {
return false;
}
$validIds = [];
foreach ($companies as $company) {
if ($company->owner_id && in_array($company->owner_id, $subscriberIds)) {
$company->owner_id = NULL;
$company->save();
}
$validIds[] = $company->id;
}
$lastPrimaryId = false;
foreach ($subscribers as $subscriber) {
$subscriber = $subscriber->detachCompanies($validIds);
if (in_array($subscriber->company_id, $validIds)) {
$companies = $subscriber->companies;
if (count($companies)) {
$lastPrimaryId = $companies[0]->id;
$subscriber->company_id = $lastPrimaryId;
$subscriber->save();
continue;
}
$subscriber->company_id = NULL;
$subscriber->save();
}
}
return [
'companies' => $companies,
'last_primary_company_id' => $lastPrimaryId
];
}
}
@@ -0,0 +1,269 @@
<?php
namespace FluentCrm\App\Api\Classes;
defined('ABSPATH') || exit;
use FluentCrm\App\Models\CustomContactField;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Models\SubscriberMeta;
use FluentCrm\App\Services\ContactsQuery;
use FluentCrm\Framework\Support\Arr;
/**
* Contacts Class - PHP APi Wrapper
*
* Contacts API Wrapper Class that can be used as <code>FluentCrmApi('contacts')</code> to get the class instance
*
* @package FluentCrm\App\Api\Classes
* @namespace FluentCrm\App\Api\Classes
*
* @version 1.0.0
*/
class Contacts
{
private $instance = null;
private $allowedInstanceMethods = [
'all',
'get',
'find',
'first',
'paginate'
];
public function __construct(Subscriber $instance)
{
$this->instance = $instance;
}
/**
* Get Contact by contact id or email
*
* Use:
* <code>FluentCrmApi('contacts')->getContact($idOrEmail);</code>
*
* @param int|string $idOrEmail Contact ID or Email
* @return false|Subscriber Model of the subscriber
*/
public function getContact($idOrEmail)
{
if (is_numeric($idOrEmail)) {
return Subscriber::where('id', $idOrEmail)->first();
} else if (is_string($idOrEmail)) {
return Subscriber::where('email', $idOrEmail)->first();
}
return false;
}
/**
* Get Contact by user id or Email
*
* Use:
* <code>FluentCrmApi('contacts')->getContactByUserRef($userIdOrEmail);</code>
*
* @param int|string $userIdOrEmail User ID or Email
* @return false|Subscriber Model of the subscriber
*/
public function getContactByUserRef($userIdOrEmail)
{
$userIdFallback = false;
if (is_numeric($userIdOrEmail)) {
$subscriber = Subscriber::where('user_id', $userIdOrEmail)->first();
if ($subscriber) {
return $subscriber;
}
$user = get_user_by('ID', $userIdOrEmail);
if (!$user) {
return false;
}
$userIdFallback = $user->ID;
$userIdOrEmail = $user->user_email;
}
$contact = false;
if (is_string($userIdOrEmail)) {
$contact = Subscriber::where('email', $userIdOrEmail)->first();
if ($contact && $userIdFallback) {
$contact->user_id = $userIdFallback;
$contact->save();
}
}
return $contact;
}
/**
* Get Contact by contact id
*
* @param int $userId User ID
* @return false|Subscriber Model of the subscriber
*/
public function getContactByUserId($userId)
{
return Subscriber::where('user_id', $userId)->first();
}
/**
* Create or Update Contact
*
* Usage:
*
* <code>FluentCrmApi('contacts')->createOrUpdateContact($data, $forceUpdate, $deleteOtherValues, $sync)</code>;
*
* @param array $data contact data to add or update
* @param bool $forceUpdate if true, will update the contact status forcefully
* @param bool $deleteOtherValues if true, will delete all custom fields data and add the new one
* @param bool $sync no use case yet
* @return false|Subscriber
*/
public function createOrUpdate($data, $forceUpdate = false, $deleteOtherValues = false, $sync = false)
{
if (empty($data['email']) || !is_email($data['email'])) {
return false;
}
if (!$forceUpdate) {
$exist = Subscriber::where('email', $data['email'])->first();
if ($exist && $exist->status != 'subscribed' && !empty($data['status'])) {
$forceUpdate = true;
}
}
if (!isset($data['custom_values'])) {
$customFieldKeys = [];
$customFields = (new CustomContactField)->getGlobalFields()['fields'];
foreach ($customFields as $field) {
$customFieldKeys[] = $field['slug'];
}
if ($customFieldKeys) {
$customFieldsData = Arr::only($data, $customFieldKeys);
$customFieldsData = array_filter($customFieldsData);
if ($customFields) {
$data['custom_values'] = (new CustomContactField)->formatCustomFieldValues($customFieldsData);
}
}
}
return $this->instance->updateOrCreate($data, $forceUpdate, $deleteOtherValues, $sync);
}
/**
* Get The current logged in contact
*
* Use
* <pre>FluentCrmApi('contacts')->getCurrentContact()</pre>
*
* @return false|Subscriber
*/
public function getCurrentContact($cached = true, $useSecureCookie = false)
{
static $currentContact;
if ($cached && $currentContact) {
return $currentContact;
}
$userId = get_current_user_id();
if ($userId) {
$user = get_user_by('ID', $userId);
$currentContact = $this->instance->where('user_id', $user->ID)->orWhere('email', $user->user_email)->first();
}
if (!$currentContact && $useSecureCookie) {
$currentContact = $this->getContactBySecureHash(\FluentCrm\Framework\Support\Arr::get($_COOKIE, 'fc_hash_secure'));
}
return $currentContact;
}
public function getContactBySecureHash($hash)
{
if (!$hash) {
return null;
}
$secureMeta = SubscriberMeta::where('value', $hash)->where('key', '_secure_hash')
->first();
if ($secureMeta) {
return $this->instance->where('id', $secureMeta->subscriber_id)->first();
}
return null;
}
public function getContactByManagedSecureHash($hash)
{
if (!$hash) {
return null;
}
$secureMeta = SubscriberMeta::where('value', $hash)->where('key', '_secure_managed_hash')
->first();
if ($secureMeta) {
return $this->instance->where('id', $secureMeta->subscriber_id)->first();
}
return null;
}
/**
* To Contact's Advanced Query Class
* Use
* <pre>FluentCrmApi('contacts')->query($args)</pre>
* @param $args array
* @return \FluentCrm\App\Services\ContactsQuery
*/
public function query($args)
{
return new ContactsQuery($args);
}
/**
* @return \FluentCrm\App\Models\Subscriber
*/
public function getInstance()
{
return $this->instance;
}
public function getCustomFields($types = [], $byOptions = false)
{
$customFields = fluentcrm_get_custom_contact_fields();
if ($types) {
$customFields = array_filter($customFields, function ($field) use ($types) {
return in_array($field['type'], $types);
});
}
if ($byOptions) {
$formatted = [];
foreach ($customFields as $field) {
$formatted[] = [
'id' => $field['slug'],
'title' => $field['label']
];
}
return $formatted;
}
return $customFields;
}
public function __call($method, $params)
{
if (in_array($method, $this->allowedInstanceMethods)) {
return call_user_func_array([$this->instance, $method], $params);
}
/* translators: %s: method name */
throw new \Exception(sprintf('Method %s does not exist.', esc_html($method)));
}
}
@@ -0,0 +1,166 @@
<?php
namespace FluentCrm\App\Api\Classes;
use FluentCrm\App\Models\Subscriber;
defined('ABSPATH') || exit;
/**
* Extend API Wrapper for FluentCRM FluentCrmApi('extend')
*
* Contacts API Wrapper Class that can be used as <code>FluentCrmApi('extend')</code> to get the class instance
*
* @package FluentCrm\App\Api\Classes
* @namespace FluentCrm\App\Api\Classes
*
* @version 1.0.0
*/
final class Extender
{
public function addProfileSection($key, $sectionTitle, $callback, $saveCallback = null)
{
add_filter('fluentcrm_profile_sections', function ($sections) use ($key, $sectionTitle) {
$sections[$key] = [
'name' => 'fluentcrm_profile_extended',
'title' => $sectionTitle,
'handler' => 'route',
'query' => [
'handler' => $key
]
];
return $sections;
});
add_filter('fluencrm_profile_section_' . $key, function ($content, $subscriber) use ($callback) {
if (is_callable($callback)) {
return $callback($content, $subscriber);
}
return $content;
}, 10, 2);
if ($saveCallback) {
add_filter('fluencrm_profile_section_save_' . $key, function ($response, $data, $subscriber) use ($saveCallback) {
if (is_callable($saveCallback)) {
return $saveCallback($response, $data, $subscriber);
}
return $response;
}, 10, 3);
}
}
public function addCompanyProfileSection($key, $sectionTitle, $callback, $saveCallback = null)
{
add_filter('fluent_crm/company_profile_sections', function ($sections) use ($key, $sectionTitle) {
$sections[$key] = [
'name' => 'fluent_crm_company_section_extended',
'title' => $sectionTitle,
'handler' => 'route',
'query' => [
'handler' => $key
]
];
return $sections;
});
add_filter('fluent_crm/company_profile_section_' . $key, function ($content, $subscriber) use ($callback) {
if (is_callable($callback)) {
return $callback($content, $subscriber);
}
return $content;
}, 10, 2);
if ($saveCallback) {
add_filter('fluent_crm/company_profile_section_save_' . $key, function ($response, $data, $company) use ($saveCallback) {
if (is_callable($saveCallback)) {
return $saveCallback($response, $data, $company);
}
return $response;
}, 10, 3);
}
}
public function addSmartCode($key, $title, $shortcodes, $callback)
{
$reservedKeys = [
'crm',
'other',
'contact',
'wp',
'fluentcrm',
'user',
'learndash',
'tutorlms',
'aff_wp',
'edd_customer',
'lifterlms',
'woo_customer'
];
if (in_array($key, $reservedKeys)) {
return;
}
/*
* this is shortcode processor function
*/
add_filter('fluent_crm/extended_smart_codes', function ($groups) use ($key, $title, $shortcodes) {
$groups[] = [
'key' => $key,
'title' => $title,
'shortcodes' => $this->formatShortcodes($key, $shortcodes)
];
return $groups;
}, 100);
/*
* This is the callback function for the shortcode parser
*/
add_filter('fluent_crm/smartcode_group_callback_' . $key, function ($code, $valueKey, $defaultValue, $subscriber) use ($callback) {
if (is_callable($callback)) {
return $callback($code, $valueKey, $defaultValue, $subscriber);
}
return $code; // return the code if no parser function is provided
}, 10, 4);
}
/**
* @param $groupKey string
* @param $shortcodes array
* @return array
*/
private function formatShortcodes($groupKey, $shortcodes)
{
$processed = [];
foreach ($shortcodes as $key => $title) {
$processed['{{' . $groupKey . '.' . $key . '}}'] = $title;
}
return $processed;
}
public function addContactWidget($callback, $priority = 20)
{
add_filter('fluent_crm/subscriber_info_widgets', function ($widgets, $subscriber) use ($callback) {
if (is_callable($callback)) {
$data = $callback($subscriber);
if (is_array($data) && isset($data['title']) && isset($data['content'])) {
$widgets[] = [
'title' => $data['title'],
'content' => $data['content']
];
}
}
return $widgets;
}, $priority, 2);
}
public function getCompaniesByContactEmail($email)
{
$subscriber = Subscriber::where('email', $email)->with('companies')->first();
if (!$subscriber) {
return [];
}
return $subscriber->companies;
}
}
@@ -0,0 +1,96 @@
<?php
namespace FluentCrm\App\Api\Classes;
use FluentCrm\App\Models\Lists as CrmLists;
use FluentCrm\Framework\Support\Arr;
/**
* Contacts List Class - PHP APi Wrapper
*
* Contacts API Wrapper Class that can be used as <code>FluentCrmApi('lists')</code> to get the class instance.
* This will contain all the methods of \FluentCrm\App\Models\Lists model.
*
* @package FluentCrm\App\Api\Classes
*
* @version 1.0.0
*/
class Lists
{
private $instance = null;
private $allowedInstanceMethods = [
'all',
'get',
'find',
'first',
'paginate'
];
public function __construct(CrmLists $instance)
{
$this->instance = $instance;
}
public function getInstance()
{
return $this->instance;
}
/**
* Add Lists as Bulk
*
* Use As: <code>FluentCrmApi('lists')->addBulk($lists)</code>
*
* @param array $lists Array of Lists with title, slug etc
* @return array of List Objects
*/
public function importBulk($lists)
{
$newLists = [];
foreach ($lists as $list) {
if (!$list['title']) {
continue;
}
if(empty($list['slug'])) {
$list['slug'] = sanitize_title($list['title'], 'display');
} else {
$list['slug'] = sanitize_title($list['slug'], 'display');
}
$list['slug'] = sanitize_text_field($list['slug']);
$list = \FluentCrm\App\Models\Lists::updateOrCreate(
array_filter([
'slug' => $list['slug'],
'title' => sanitize_text_field($list['title']),
'description' => sanitize_textarea_field(Arr::get($list, 'description'))
]),
['slug' => $list['slug']]
);
if($list->wasRecentlyCreated) {
do_action('fluentcrm_list_created', $list->id);
do_action('fluent_crm/list_created', $list);
} else {
do_action('fluentcrm_list_updated', $list->id);
do_action('fluent_crm/list_updated', $list);
}
$newLists[] = $list;
}
return $newLists;
}
public function __call($method, $params)
{
if (in_array($method, $this->allowedInstanceMethods)) {
return call_user_func_array([$this->instance, $method], $params);
}
/* translators: %s: method name */
throw new \Exception(sprintf('Method %s does not exist.', esc_html($method)));
}
}
@@ -0,0 +1,87 @@
<?php
/**
* Contact Tags Class - PHP APi Wrapper
*
* Contacts Tags API Wrapper Class that can be used as fluentCrmApi('tags') to get the class instance
*
* @package FluentCrm\App\Api\Classes
*
* @version 1.0.0
*/
namespace FluentCrm\App\Api\Classes;
use FluentCrm\App\Models\Tag;
use FluentCrm\Framework\Support\Arr;
class Tags
{
private $instance = null;
private $allowedInstanceMethods = [
'all',
'get',
'find',
'first',
'paginate'
];
public function importBulk($tags)
{
$newTags = [];
foreach ($tags as $tag) {
if (!$tag['title']) {
continue;
}
if (empty($tag['slug'])) {
$tag['slug'] = sanitize_title($tag['title'], 'display');
} else {
$tag['slug'] = sanitize_title($tag['slug'], 'display');
}
$tag['slug'] = sanitize_text_field($tag['slug']);
$tag = \FluentCrm\App\Models\Tag::updateOrCreate(
array_filter([
'slug' => $tag['slug'],
'title' => sanitize_text_field($tag['title']),
'description' => sanitize_textarea_field(Arr::get($tag, 'description'))
]),
['slug' => $tag['slug']]
);
if ($tag->wasRecentlyCreated) {
do_action('fluentcrm_tag_created', $tag->id);
do_action('fluent_crm/tag_created', $tag);
} else {
do_action('fluentcrm_tag_updated', $tag->id);
do_action('fluent_crm/tag_updated', $tag);
}
$newTags[] = $tag;
}
return $newTags;
}
public function __construct(Tag $instance)
{
$this->instance = $instance;
}
public function getInstance()
{
return $this->instance;
}
public function __call($method, $params)
{
if (in_array($method, $this->allowedInstanceMethods)) {
return call_user_func_array([$this->instance, $method], $params);
}
/* translators: %s: method name */
throw new \Exception(sprintf('Method %s does not exist.', esc_html($method)));
}
}
@@ -0,0 +1,128 @@
<?php
namespace FluentCrm\App\Api\Classes;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
defined('ABSPATH') || exit;
/**
* Extend API Wrapper for FluentCRM FluentCrmApi('tracker')
*
* Contacts API Wrapper Class that can be used as <code>FluentCrmApi('tracker')</code> to get the class instance
*
* @package FluentCrm\App\Api\Classes
* @namespace FluentCrm\App\Api\Classes
*
* @version 2.8.4
*/
final class Tracker
{
/*
* Create event for a subscriber
* Example Data:
* [
* 'subscriber_id' => 1, // optional
* 'email' => '', // optional
* 'user_id' => 1, // optional
* 'provider' => 'woocommerce|custom|or_anything', // optional
* 'event_key' => 'checkout',
* 'title' => 'Purchase Done',
* 'value' => 'STRING|Number'
* ];
* @param array $data | \WP_Error
*
* @return \WP_Error|\FluentCrm\App\Models\EventTracker
*/
public function track($data, $repeatable = true)
{
if (!Helper::isExperimentalEnabled('event_tracking')) {
return new \WP_Error('not_enabled', 'Event Tracker is not enabled');
}
// find the subscriber
$subscriber = $this->getSubscriber($data);
if (is_wp_error($subscriber)) {
return $subscriber;
}
// validate the data
if (empty($data['event_key']) || empty($data['title'])) {
return new \WP_Error('invalid_data', 'Invalid data provided. key and event are required');
}
// take only first 200 characters
$data['event_key'] = substr($data['event_key'], 0, 192);
$data['title'] = substr($data['title'], 0, 192);
$eventData = [
'provider' => sanitize_text_field(Arr::get($data, 'provider', 'custom')),
'subscriber_id' => $subscriber->id,
'event_key' => sanitize_text_field($data['event_key']),
'title' => sanitize_text_field($data['title']),
'value' => sanitize_textarea_field(Arr::get($data, 'value', '')),
'counter' => 1 // This is actually the count of the event
];
if ($repeatable) {
// check if exist
$event = \FluentCrm\App\Models\EventTracker::where('subscriber_id', $subscriber->id)
->where('event_key', $eventData['event_key'])
->where('title', $eventData['title'])
->first();
if ($event) {
$event->value = $eventData['value'];
$event->counter++;
$event->save();
do_action('fluent_crm/event_tracked', $event, $subscriber);
return $event;
}
}
$createdEvent = \FluentCrm\App\Models\EventTracker::create($eventData);
do_action('fluent_crm/event_tracked', $createdEvent, $subscriber);
return $createdEvent;
}
private function getSubscriber($data)
{
if (!empty($data['subscriber'])) {
return $data['subscriber'];
}
// check for subscriber
if (empty($data['subscriber_id']) && empty($data['email']) && empty($data['user_id'])) {
$subscriber = fluentcrm_get_current_contact();
if ($subscriber) {
return $subscriber;
}
return new \WP_Error('subscriber_not_found', 'Current Subscriber could not be found');
}
$subscriber = null;
if (!empty($data['subscriber_id'])) {
$subscriber = Subscriber::where('id', $data['subscriber_id'])->first();
} else if (!empty($data['email'])) {
$subscriber = Subscriber::where('email', $data['email'])->first();
} else if (!empty($data['user_id'])) {
$user = get_user_by('ID', $data['user_id']);
if ($user) {
$subscriber = Subscriber::where('email', $user->user_email)->first();
}
}
if (!$subscriber) {
return new \WP_Error('subscriber_not_found', 'Subscriber not found');
}
return $subscriber;
}
}
@@ -0,0 +1,22 @@
<?php
namespace FluentCrm\App\Api;
final class FCApi
{
private $instance = null;
public function __construct($instance)
{
$this->instance = $instance;
}
public function __call($method, $params)
{
try {
return call_user_func_array([$this->instance, $method], $params);
} catch (\Exception $e) {
return null;
}
}
}
@@ -0,0 +1,14 @@
<?php
// Register the classes to make available for the developers
// The key will be used to access the class, for example:
// FluentCrmApi('contacts') or FluentCrmApi->contacts
return [
'contacts' => 'FluentCrm\App\Api\Classes\Contacts',
'tags' => 'FluentCrm\App\Api\Classes\Tags',
'lists' => 'FluentCrm\App\Api\Classes\Lists',
'extender' => 'FluentCrm\App\Api\Classes\Extender',
'companies' => 'FluentCrm\App\Api\Classes\Companies',
'event_tracker' => 'FluentCrm\App\Api\Classes\Tracker'
];
@@ -0,0 +1,8 @@
<?php
namespace FluentCrm\App;
class App extends \FluentCrm\Framework\Foundation\App
{
// ...
}
@@ -0,0 +1,125 @@
<?php
// phpcs:disable
namespace FluentCrm\App;
use Composer\Script\Event;
use InvalidArgumentException;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
class ComposerScript
{
public static function postInstall(Event $event)
{
static::postUpdate($event);
}
public static function postUpdate(Event $event)
{
$vendorDir = $event->getComposer()->getConfig()->get('vendor-dir');
$composerJson = json_decode(file_get_contents($vendorDir . '/../composer.json'), true);
$namespace = $composerJson['extra']['wpfluent']['namespace']['current'];
if (!$namespace) {
throw new InvalidArgumentException("Namespace not set in composer.json file.");
}
$itr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
$vendorDir.'/wpfluent/framework/src/', RecursiveDirectoryIterator::SKIP_DOTS
), RecursiveIteratorIterator::SELF_FIRST);
foreach ($itr as $file) {
if ($file->isDir()) {
continue;
}
$fileName = $file->getPathname();
$content = file_get_contents($fileName);
$content = str_replace(
['WPFluent\\', 'WPFluentPackage\\'],
[$namespace . '\\Framework\\', $namespace . '\\'],
$content
);
file_put_contents($fileName, $content);
}
static::updateVendorComposerFiles($vendorDir, $namespace);
}
protected static function updateVendorComposerFiles($vendorDir, $namespace)
{
$composerInstalledJson = json_decode(file_get_contents(
$installedJsonFile = $vendorDir . '/composer/installed.json'
), true);
foreach ($composerInstalledJson['packages'] as &$package) {
if ($package['name'] == 'wpfluent/framework') {
$package['autoload']['psr-4'] = [
$namespace . "\\Framework\\" => "src/WPFluent"
];
} else {
$packageDir = $vendorDir . "/{$package['name']}/src/";
if(!is_dir($packageDir)) {
continue;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$packageDir, RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
if ($item->isDir()) {
continue;
}
$fileName = $item->getPathname();
$content = file_get_contents($fileName);
$content = str_replace(
['WPFluent\\', 'WPFluentPackage\\'],
[$namespace . '\\Framework\\', $namespace . '\\'],
$content
);
file_put_contents($fileName, $content);
}
$psr4 = array_keys($package['autoload']['psr-4']);
$replaced = str_replace(
'WPFluentPackage', $namespace, $psr4[0]
);
$package['autoload']['psr-4'] = [
$replaced => "src/"
];
$packageComposerJson = json_decode(file_get_contents(
$vendorDir .'/' . $package['name'] . '/composer.json'
), true);
$packageComposerJson['autoload']['psr-4'] = [
$replaced => "src/"
];
file_put_contents(
$vendorDir .'/' . $package['name'] . '/composer.json',
json_encode($packageComposerJson, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES)
);
}
}
file_put_contents(
$installedJsonFile,
json_encode($composerInstalledJson, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)
);
exec('composer dump-autoload');
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,481 @@
<?php
namespace FluentCrm\App\Hooks\CLI;
use FluentCrm\App\Models\Funnel;
use FluentCrm\App\Models\FunnelMetric;
use FluentCrm\App\Models\FunnelSequence;
use FluentCrm\App\Models\FunnelSubscriber;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\Funnel\FunnelProcessor;
class SimulateFunnelCommand
{
/*
* Fast-forward a subscriber through an automation funnel, skipping wait times.
* Real actions will fire (tags applied, emails sent, etc.) — only delays are shortened.
*
* Usage:
* wp fluent_crm simulate_funnel --funnel_id=123 --email=john@example.com
* wp fluent_crm simulate_funnel --funnel_id=123 --subscriber_id=456
* wp fluent_crm simulate_funnel --funnel_id=123 --email=john@example.com --sleep=1 --max_steps=50
* wp fluent_crm simulate_funnel --funnel_id=123 --email=john@example.com --sleep=0
*
* --sleep=0 runs one step at a time (step mode). Run the command again to advance to the next step.
*/
public function handle($args, $assoc_args)
{
$funnelId = \WP_CLI\Utils\get_flag_value($assoc_args, 'funnel_id');
$subscriberId = \WP_CLI\Utils\get_flag_value($assoc_args, 'subscriber_id');
$email = \WP_CLI\Utils\get_flag_value($assoc_args, 'email');
$sleepSeconds = intval(\WP_CLI\Utils\get_flag_value($assoc_args, 'sleep', 2));
$maxSteps = max(1, intval(\WP_CLI\Utils\get_flag_value($assoc_args, 'max_steps', 100)));
$stepMode = $sleepSeconds === 0;
if ($sleepSeconds < 0) {
$sleepSeconds = 0;
}
if (!$funnelId) {
\WP_CLI::error('--funnel_id is required');
}
$funnel = Funnel::find(intval($funnelId));
if (!$funnel) {
\WP_CLI::error('Funnel not found');
}
if ($subscriberId) {
$subscriber = Subscriber::find(intval($subscriberId));
} elseif ($email) {
$subscriber = Subscriber::where('email', sanitize_email($email))->first();
} else {
\WP_CLI::error('--subscriber_id or --email is required');
return;
}
if (!$subscriber) {
\WP_CLI::error('Subscriber not found');
}
\WP_CLI::line('---');
\WP_CLI::line(sprintf('Funnel: %s (#%d) - Status: %s', $funnel->title, $funnel->id, $funnel->status));
\WP_CLI::line(sprintf('Subscriber: %s (#%d) - Status: %s', $subscriber->email, $subscriber->id, $subscriber->status));
if ($stepMode) {
\WP_CLI::line('Mode: step-by-step (--sleep=0)');
} else {
\WP_CLI::line(sprintf('Wait times will be reduced to %d second(s)', $sleepSeconds));
}
\WP_CLI::line('---');
// Print funnel step map
$this->printFunnelSteps($funnel->id);
if ($funnel->status !== 'published') {
\WP_CLI::warning('This funnel is not published. Proceeding anyway...');
}
// Check existing enrollment
$funnelSub = FunnelSubscriber::where('funnel_id', $funnel->id)
->where('subscriber_id', $subscriber->id)
->first();
if ($funnelSub) {
if (in_array($funnelSub->status, ['completed', 'cancelled'])) {
\WP_CLI::line(sprintf('Subscriber already %s this funnel.', $funnelSub->status));
\WP_CLI::confirm('Re-enroll and start fresh?');
$this->resetFunnelEnrollment($funnel->id, $subscriber->id, $funnelSub->id);
$funnelSub = null;
} elseif (in_array($funnelSub->status, ['active', 'waiting'])) {
$nextSeq = $funnelSub->next_sequence_id ? FunnelSequence::find($funnelSub->next_sequence_id) : null;
$nextLabel = $nextSeq ? ($nextSeq->title ?: $nextSeq->action_name) : 'unknown';
\WP_CLI::line(sprintf('Subscriber is already in this funnel (status: %s, next: %s).', $funnelSub->status, $nextLabel));
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
fwrite(STDOUT, 'Resume or Restart? (resume/restart): ');
$choice = strtolower(trim(fgets(STDIN)));
if ($choice === 'restart') {
$this->resetFunnelEnrollment($funnel->id, $subscriber->id, $funnelSub->id);
$funnelSub = null;
\WP_CLI::line('Restarting from the beginning...');
} else {
\WP_CLI::line('Resuming from current position...');
}
} else {
\WP_CLI::line(sprintf('Current enrollment status: %s', $funnelSub->status));
}
}
// In auto-advance mode, minimize wait times so we don't actually wait days
if (!$stepMode) {
$filterDelay = max(1, $sleepSeconds);
add_filter('fluent_crm/funnel_seq_delay_in_seconds', function () use ($filterDelay) {
return $filterDelay;
}, 99999, 4);
}
$processor = new FunnelProcessor();
$firedHooks = [];
// Enroll if not already
if (!$funnelSub) {
\WP_CLI::line('Enrolling subscriber into funnel...');
$hooksBefore = $this->snapshotHooks();
$processor->startSequences($subscriber, $funnel);
$firedHooks = array_merge($firedHooks, $this->diffHooks($hooksBefore));
$funnelSub = FunnelSubscriber::where('funnel_id', $funnel->id)
->where('subscriber_id', $subscriber->id)
->first();
if (!$funnelSub) {
\WP_CLI::error('Failed to enroll — funnel may have no sequences');
}
$this->showExecutedMetrics($funnel->id, $subscriber->id, 'Enrollment');
// In step mode, stop after enrollment — next run will resume
if ($stepMode) {
$this->showStepModeNextUp($funnelSub);
$this->askAndShowFiredHooks($firedHooks);
$this->showFinalStatus($funnel->id, $subscriber->id, $funnelSub->id);
return;
}
}
// In step mode, process exactly one batch then stop
if ($stepMode) {
$lastMetricId = (int) FunnelMetric::where('funnel_id', $funnel->id)
->where('subscriber_id', $subscriber->id)
->max('id');
$hooksBefore = $this->snapshotHooks();
$this->processOneStep($processor, $funnelSub);
$firedHooks = array_merge($firedHooks, $this->diffHooks($hooksBefore));
// Show what was processed in this step
$newMetrics = FunnelMetric::where('funnel_id', $funnel->id)
->where('subscriber_id', $subscriber->id)
->where('id', '>', $lastMetricId)
->orderBy('id', 'ASC')
->get();
if ($newMetrics->count()) {
\WP_CLI::line(sprintf('Processed %d action(s):', $newMetrics->count()));
foreach ($newMetrics as $metric) {
$seq = FunnelSequence::find($metric->sequence_id);
if ($seq) {
\WP_CLI::line(sprintf(' > [%s] %s', $seq->action_name, $seq->title ?: ''));
}
}
}
$funnelSub = FunnelSubscriber::find($funnelSub->id);
$this->showStepModeNextUp($funnelSub);
$this->askAndShowFiredHooks($firedHooks);
$this->showFinalStatus($funnel->id, $subscriber->id, $funnelSub->id);
return;
}
// Fast-forward remaining steps
$step = 0;
while ($step < $maxSteps) {
$shouldBreak = $this->checkTerminalStatus($funnelSub);
if ($shouldBreak) {
break;
}
$step++;
// Show what's about to execute
$nextSeq = $funnelSub->next_sequence_id ? FunnelSequence::find($funnelSub->next_sequence_id) : null;
if ($nextSeq) {
\WP_CLI::line(sprintf('[Step %d] %s: %s', $step, $nextSeq->action_name, $nextSeq->title ?: ''));
}
// Force execution time to now
FunnelSubscriber::where('id', $funnelSub->id)->update([
'next_execution_time' => current_time('mysql'),
]);
$funnelSub->next_execution_time = current_time('mysql');
// Process the next step
$hooksBefore = $this->snapshotHooks();
$processor->processFunnelAction($funnelSub);
$firedHooks = array_merge($firedHooks, $this->diffHooks($hooksBefore));
sleep($sleepSeconds);
// Reload for next iteration
$funnelSub = FunnelSubscriber::find($funnelSub->id);
}
if ($step >= $maxSteps) {
\WP_CLI::warning(sprintf('Reached max steps limit (%d). Use --max_steps to increase.', $maxSteps));
}
$this->askAndShowFiredHooks($firedHooks);
$this->showFinalStatus($funnel->id, $subscriber->id, $funnelSub ? $funnelSub->id : null);
}
private function resetFunnelEnrollment($funnelId, $subscriberId, $funnelSubId)
{
FunnelMetric::where('funnel_id', $funnelId)
->where('subscriber_id', $subscriberId)
->delete();
FunnelSubscriber::where('id', $funnelSubId)->delete();
}
private function showExecutedMetrics($funnelId, $subscriberId, $label)
{
$metrics = FunnelMetric::where('funnel_id', $funnelId)
->where('subscriber_id', $subscriberId)
->orderBy('id', 'ASC')
->get();
if ($metrics->count()) {
\WP_CLI::line(sprintf('%s processed %d step(s):', $label, $metrics->count()));
foreach ($metrics as $metric) {
$seq = FunnelSequence::find($metric->sequence_id);
if ($seq) {
\WP_CLI::line(sprintf(' > [%s] %s', $seq->action_name, $seq->title ?: ''));
}
}
}
}
private function processOneStep($processor, $funnelSub)
{
$funnelSub = FunnelSubscriber::find($funnelSub->id);
$shouldBreak = $this->checkTerminalStatus($funnelSub);
if ($shouldBreak) {
return;
}
// Force execution time to now so processFunnelAction picks it up
FunnelSubscriber::where('id', $funnelSub->id)->update([
'next_execution_time' => current_time('mysql'),
]);
$funnelSub->next_execution_time = current_time('mysql');
// Use the real processor — SequencePoints resolves next batch,
// processSequencePoints executes it
$processor->processFunnelAction($funnelSub);
}
private function showStepModeNextUp($funnelSub)
{
if (!$funnelSub) {
return;
}
if ($funnelSub->status === 'active' && $funnelSub->next_sequence_id) {
$upNext = FunnelSequence::find($funnelSub->next_sequence_id);
\WP_CLI::line(sprintf(
'Up next: [%s] %s',
$upNext ? $upNext->action_name : '?',
$upNext ? ($upNext->title ?: '') : ''
));
\WP_CLI::line('Run the command again to advance.');
}
}
private function checkTerminalStatus($funnelSub)
{
if (!$funnelSub) {
\WP_CLI::error('Funnel subscriber record not found');
return true;
}
if ($funnelSub->status === 'completed') {
\WP_CLI::success('Funnel completed!');
return true;
}
if ($funnelSub->status === 'cancelled') {
\WP_CLI::warning('Funnel cancelled (subscriber may not be in a processable status)');
return true;
}
if ($funnelSub->status === 'waiting') {
$seq = $funnelSub->next_sequence_id ? FunnelSequence::find($funnelSub->next_sequence_id) : null;
\WP_CLI::warning(sprintf(
'Blocked on benchmark: %s — cannot auto-advance past goals.',
$seq ? ($seq->title ?: $seq->action_name) : 'unknown'
));
return true;
}
if ($funnelSub->status === 'pending') {
\WP_CLI::warning('Subscriber is pending (needs double opt-in). Cannot auto-advance.');
return true;
}
if ($funnelSub->status !== 'active' || !$funnelSub->next_execution_time) {
return true;
}
return false;
}
private function snapshotHooks()
{
global $wp_actions;
return $wp_actions ?: [];
}
private function diffHooks($before)
{
global $wp_actions;
$after = $wp_actions ?: [];
$fired = [];
foreach ($after as $hook => $count) {
$prevCount = isset($before[$hook]) ? $before[$hook] : 0;
if ($count > $prevCount) {
// Only include fluentcrm-related hooks
if (strpos($hook, 'fluentcrm') !== false || strpos($hook, 'fluent_crm') !== false) {
$fired[$hook] = $count - $prevCount;
}
}
}
return $fired;
}
private function askAndShowFiredHooks($firedHooks)
{
if (empty($firedHooks)) {
return;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
fwrite(STDOUT, sprintf('Show fired hooks? (%d hooks) (yes/no): ', count($firedHooks)));
$answer = strtolower(trim(fgets(STDIN)));
if ($answer !== 'yes' && $answer !== 'y') {
return;
}
\WP_CLI::line('Fired hooks:');
foreach ($firedHooks as $hook => $count) {
$suffix = $count > 1 ? sprintf(' (x%d)', $count) : '';
\WP_CLI::line(sprintf(' > %s%s', $hook, $suffix));
}
}
private function showFinalStatus($funnelId, $subscriberId, $funnelSubId)
{
$funnelSub = $funnelSubId ? FunnelSubscriber::find($funnelSubId) : null;
$totalMetrics = FunnelMetric::where('funnel_id', $funnelId)
->where('subscriber_id', $subscriberId)
->count();
\WP_CLI::line('---');
\WP_CLI::line(sprintf('Final status: %s', $funnelSub ? $funnelSub->status : 'unknown'));
\WP_CLI::line(sprintf('Total actions executed: %d', $totalMetrics));
}
private function printFunnelSteps($funnelId)
{
$sequences = FunnelSequence::where('funnel_id', $funnelId)
->orderBy('sequence', 'ASC')
->get();
if ($sequences->isEmpty()) {
\WP_CLI::line('No steps in this funnel.');
\WP_CLI::line('---');
return;
}
// Group children by parent_id and condition_type
$topLevel = [];
$children = []; // $children[$parentId][$conditionType][]
foreach ($sequences as $seq) {
if (!$seq->parent_id) {
$topLevel[] = $seq;
} else {
$children[$seq->parent_id][$seq->condition_type][] = $seq;
}
}
\WP_CLI::line('Funnel steps:');
$this->printSequenceList($topLevel, $children, ' ');
\WP_CLI::line('---');
}
private function printSequenceList($sequences, $children, $indent)
{
$count = count($sequences);
foreach ($sequences as $i => $seq) {
$label = $this->formatSequenceLabel($seq);
$isLast = ($i === $count - 1);
$connector = $isLast ? '└─' : '├─';
\WP_CLI::line($indent . $connector . ' ' . $label);
// If conditional/ab-test, print branches
if ($seq->type === 'conditional' && isset($children[$seq->id])) {
$childIndent = $indent . ($isLast ? ' ' : '│ ');
$branches = $children[$seq->id];
if (isset($branches['yes'])) {
\WP_CLI::line($childIndent . '├─ [YES]:');
$this->printSequenceList($branches['yes'], $children, $childIndent . '│ ');
}
if (isset($branches['no'])) {
\WP_CLI::line($childIndent . '└─ [NO]:');
$this->printSequenceList($branches['no'], $children, $childIndent . ' ');
}
}
}
}
private function formatSequenceLabel($seq)
{
$type = $seq->type ?: 'action';
$title = $seq->title ?: $seq->action_name;
if ($seq->action_name === 'fluentcrm_wait_times') {
$wait = $this->formatWaitTime($seq->settings);
return sprintf('(%s) %s — %s', $type, $title, $wait);
}
if ($seq->action_name === 'end_this_funnel') {
return sprintf('(%s) End Funnel', $type);
}
return sprintf('(%s) %s', $type, $title);
}
private function formatWaitTime($settings)
{
if (!is_array($settings)) {
return '';
}
$waitType = $settings['wait_type'] ?? '';
if ($waitType === 'timestamp_wait') {
return 'until ' . ($settings['wait_date_time'] ?? '?');
}
if ($waitType === 'to_day') {
$day = $settings['wait_day_of_week'] ?? '?';
$time = $settings['wait_time_of_day'] ?? '';
return sprintf('next %s%s', $day, $time ? ' at ' . $time : '');
}
if ($waitType === 'by_custom_field') {
return 'until custom field date';
}
$amount = $settings['wait_time_amount'] ?? '?';
$unit = $settings['wait_time_unit'] ?? 'days';
return sprintf('%s %s', $amount, $unit);
}
}
@@ -0,0 +1,87 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
/**
* ActivationHandler Class
*
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class ActivationHandler
{
public function handle($network_wide = false)
{
// Run DB Migrations
require_once(FLUENTCRM_PLUGIN_PATH . 'database/FluentCRMDBMigrator.php');
// Task scheduler for sending emails
$this->registerWpCron();
// Default global settings/options
$this->addDefaultGlobalSettings();
}
public function registerWpCron()
{
add_filter('cron_schedules', function ($schedules) {
$schedules['fluentcrm_every_minute'] = array(
'interval' => 300,
'display' => esc_html__('Every Minute (FluentCRM)', 'fluent-crm'),
);
$schedules['fluentcrm_scheduled_five_minute_tasks'] = array(
'interval' => 300,
'display' => esc_html__('Every 5 Minutes (FluentCRM)', 'fluent-crm'),
);
return $schedules;
}, 10, 1);
if (function_exists('\as_has_scheduled_action')) {
if (!as_has_scheduled_action('fluentcrm_scheduled_every_minute_tasks')) {
as_schedule_recurring_action(time(), 60, 'fluentcrm_scheduled_every_minute_tasks', [], 'fluent-crm');
}
}
$hookName = 'fluentcrm_scheduled_five_minute_tasks';
if (!wp_next_scheduled($hookName)) {
wp_schedule_event(time(), 'fluentcrm_scheduled_five_minute_tasks', $hookName);
}
$hourlyHook = 'fluentcrm_scheduled_hourly_tasks';
if (!wp_next_scheduled($hourlyHook)) {
wp_schedule_event(time(), 'hourly', $hourlyHook);
}
$weeklyHook = 'fluentcrm_scheduled_weekly_tasks';
if (!wp_next_scheduled($weeklyHook)) {
wp_schedule_event(time(), 'weekly', $weeklyHook);
}
}
public function addDefaultGlobalSettings()
{
$key = 'fluentcrm-global-settings';
$defaults = [
'campaign' => [
'from' => [
'name' => '',
'email' => ''
]
],
'email' => [
'emails_per_second' => 4
]
];
$settings = get_option($key) ?: [];
update_option($key, array_merge($defaults, $settings));
}
}
@@ -0,0 +1,201 @@
<?php
// php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\ActivityLog;
use FluentCrm\App\Models\Lists;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Models\Tag;
class ActivityLogHandler
{
protected $objectTypeContact = 'FluentCrm\App\Models\Subscriber';
// Call this once (e.g., on plugins_loaded) to attach the hooks
public function register()
{
return;
// if (!$this->activityLogEnabled()) {
// return;
// }
// Contact created
add_action('fluent_crm/contact_created', [$this, 'onContactCreated'], 10, 2);
// Tags updated
add_action('fluent_crm/contact_added_to_tags', [$this, 'onTagsAdded'], 10, 3);
add_action('fluent_crm/contact_removed_from_tags', [$this, 'onTagsRemoved'], 10, 3);
// Lists updated
add_action('fluent_crm/contact_added_to_lists', [$this, 'onListsAdded'], 10, 3);
add_action('fluent_crm/contact_removed_from_lists', [$this, 'onListsRemoved'], 10, 3);
// Bulk delete subscribers
add_action('fluentcrm_before_subscribers_deleted', [$this, 'onSubscribersDeleted'], 10,2);
}
public function onContactCreated($contact, $source = 'wp-admin')
{
$contactId = $this->contactId($contact);
if (!$contactId) {
return;
}
$email = $this->contactField($contact, 'email');
$name = trim($this->contactField($contact, 'first_name') . ' ' . $this->contactField($contact, 'last_name'));
$description = 'Contact Name: ' . $name . ' | Contact Email: ' . $email;
$this->log([
'object_type' => $this->objectTypeContact,
'object_id' => $contactId,
'action' => 'created contact',
'source' => $source,
'description' => $description
]);
}
public function onSubscribersDeleted($subscriberIds, $source = 'wp-admin')
{
$subscriberIds = array_values(array_filter((array) $subscriberIds));
if (empty($subscriberIds)) {
return;
}
$subscriberIds = array_values(array_filter((array) $subscriberIds));
$emails = Subscriber::whereIn('id', $subscriberIds)->take(10)->pluck('email')->toArray();
$commaSeparatedEmails = implode(',', $emails);
if (count($subscriberIds) > 10) {
$commaSeparatedEmails .= '...' . ' (and ' . (count($subscriberIds) - 10) . ' more)';
}
$description = 'Deleted Contacts Emails: ' . $commaSeparatedEmails;
$this->log([
'object_type' => $this->objectTypeContact,
'object_id' => 0,
'action' => 'deleted contacts',
'source' => $source,
'description' => $description
]);
}
public function onTagsAdded($contact, $tagIds, $source = 'wp-admin')
{
$this->logTags($contact, $tagIds, 'added tag to contact', $source);
}
public function onTagsRemoved($contact, $tagIds, $source = 'wp-admin')
{
$this->logTags($contact, $tagIds, 'removed tag from contact', $source);
}
public function onListsAdded($contact, $listIds, $source = 'wp-admin')
{
$this->logLists($contact, $listIds, 'added list to contact', $source);
}
public function onListsRemoved($contact, $listIds, $source = 'wp-admin')
{
$this->logLists($contact, $listIds, 'removed list from contact', $source);
}
/*
|----------------------------------------------------------------------
| Helpers
|----------------------------------------------------------------------
*/
protected function logTags($contact, $tagIds, $action, $source)
{
$contactId = $this->contactId($contact);
if (!$contactId) {
return;
}
$tagIds = array_values(array_filter((array) $tagIds));
$subscriberEmail = Subscriber::where('id', $contactId)->value('email');
$commaSeparatedTitles = implode(',', Tag::whereIn('id', $tagIds)->pluck('title')->toArray());
$description = 'Tags: ' . $commaSeparatedTitles . ' | Contact: ' . $subscriberEmail;
$this->log([
'object_type' => $this->objectTypeContact,
'object_id' => $contactId,
'action' => $action,
'source' => $source,
'description' => $description
]);
}
protected function logLists($contact, $listIds, $action, $source)
{
$contactId = $this->contactId($contact);
if (!$contactId) {
return;
}
$listIds = array_values(array_filter((array) $listIds));
$subscriberEmail = Subscriber::where('id', $contactId)->value('email');
$commaSeparatedTitles = implode(',', Lists::whereIn('id', $listIds)->pluck('title')->toArray());
$description = 'Lists: ' . $commaSeparatedTitles . ' | Contact: ' . $subscriberEmail;
$this->log([
'object_type' => $this->objectTypeContact,
'object_id' => $contactId,
'action' => $action,
'source' => $source,
'description' => $description
]);
}
protected function log(array $data)
{
ActivityLog::create([
'object_type' => $data['object_type'] ?? 'contact',
'object_id' => $data['object_id'] ?? null,
'action' => $data['action'] ?? 'unknown',
'source' => $data['source'],
'description' => $data['description'] ?? null,
'activity_by' => $this->currentUserId()
]);
}
protected function contactId($contact)
{
if (is_object($contact)) {
// FluentCRM Contact model uses `id`
return isset($contact->id) ? (int) $contact->id : null;
}
if (is_array($contact)) {
return isset($contact['id']) ? (int) $contact['id'] : null;
}
return null;
}
protected function contactField($contact, $key)
{
if (is_object($contact)) {
return isset($contact->{$key}) ? $contact->{$key} : '';
}
if (is_array($contact)) {
return isset($contact[$key]) ? $contact[$key] : '';
}
return '';
}
protected function currentUserId(): int
{
if (function_exists('get_current_user_id')) {
return (int) get_current_user_id();
}
return 0;
}
protected function activityLogEnabled()
{
$settings = get_option('_fluentcrm_experimental_settings', []);
if (isset($settings['activity_log']) && $settings['activity_log'] == 'no') {
return false;
}
return true;
}
}
@@ -0,0 +1,111 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\PermissionManager;
use FluentCrm\App\Services\Stats;
use FluentCrm\Framework\Support\Arr;
/**
* Admin Bar Class
*
* Used for Quick Access to CRM
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class AdminBar
{
public function init()
{
$contactPermission = PermissionManager::currentUserCan('fcrm_read_contacts');
/**
* Determine whether the FluentCRM admin bar search is enabled or not.
*
* @return bool False Default is false or disabled.
*/
if (!is_admin() || !$contactPermission || apply_filters('fluent_crm/disable_adminbar_search', apply_filters('fluent_crm/disable_global_search', false))) {
return;
}
add_action('admin_bar_menu', [$this, 'addAdminBarSearch'], 999);
}
public function addAdminBarSearch($adminBar)
{
wp_enqueue_script(
'fluentcrm_adminbar_search',
fluentCrmMix('/admin/js/adminbar-search.js'),
['jquery']
);
$urlBase = fluentcrm_menu_url_base();
$currentScreen = get_current_screen();
$editingUserVars = null;
if ($currentScreen && $currentScreen->id == 'user-edit') {
$userId = (int) Arr::get($_REQUEST, 'user_id');
$user = get_user_by('ID', $userId);
if ($userId && $user) {
$crmProfile = Subscriber::where('email', $user->user_email)
->orWhere('user_id', $user->ID)
->first();
if ($crmProfile) {
$crmProfileUrl = $urlBase . 'subscribers/' . $crmProfile->id;
$editingUserVars = [
'user_id' => $userId,
'crm_profile_id' => $crmProfile->id,
'crm_profile_url' => $crmProfileUrl
];
}
}
}
wp_localize_script('fluentcrm_adminbar_search', 'fcrm_adminbar_search_vars', [
'rest' => $this->getRestInfo(),
'links' => (new Stats)->getQuickLinks(),
'subscriber_base' => $urlBase . 'subscribers/',
'edit_user_vars' => $editingUserVars,
'trans' => [
'Search Contacts' => __('Search Contacts', 'fluent-crm'),
'Type and press enter' => __('Type and press enter', 'fluent-crm'),
'Type to search contacts' => __('Type to search contacts', 'fluent-crm'),
'Quick Links' => __('Quick Links', 'fluent-crm'),
'Sorry no contact found' => __('Sorry no contact found', 'fluent-crm'),
'Load More' => __('Load More', 'fluent-crm'),
'Close' => __('Close', 'fluent-crm')
]
]);
$args = [
'parent' => 'top-secondary',
'id' => 'fcrm_adminbar_search',
'title' => __('Search Contacts', 'fluent-crm'),
'href' => '#',
'meta' => false
];
$adminBar->add_node($args);
}
protected function getRestInfo()
{
$app = FluentCrm();
$ns = $app->config->get('app.rest_namespace');
$v = $app->config->get('app.rest_version');
return [
'base_url' => esc_url_raw(rest_url()),
'url' => rest_url($ns . '/' . $v),
'nonce' => wp_create_nonce('wp_rest'),
'namespace' => $ns,
'version' => $v
];
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,381 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\AutoSubscribe;
use FluentCrm\App\Services\Funnel\FunnelHelper;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
/**
* AutoSubscribeHandler Class
*
* Used to handle the auto-subscribe functionality for different WordPress Events.
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class AutoSubscribeHandler
{
public function register()
{
add_action('user_register', array($this, 'userRegistrationHandler'), 99, 1);
add_action('comment_post', array($this, 'handleCommentPost'), 99, 3);
add_action('profile_update', array($this, 'syncUserUpdate'), 10, 3);
add_action('delete_user', array($this, 'maybeDeleteContact'), 10, 3);
add_action('woocommerce_customer_save_address', array($this, 'syncWooAddressUpdate'), 10, 2);
add_action('wp_login', array($this, 'maybeAddCountryToProfile'), 99, 2);
}
public function userRegistrationHandler($userId)
{
if (is_multisite()) {
if (is_network_admin()) {
return false;
}
if (function_exists('WP_Ultimo')) {
return false;
}
}
$settings = (new AutoSubscribe())->getRegistrationSettings();
if (Arr::get($settings, 'status') != 'yes') {
$user = get_user_by('ID', $userId);
$contact = Subscriber::where('email', $user->user_email)->first();
if ($contact && $contact->user_id != $user->ID) {
fluentCrmDb()->table('fc_subscribers')
->where('id', $contact->id)
->update([
'user_id' => $user->ID
]);
}
return false;
}
$subscriberData = FunnelHelper::prepareUserData($userId);
if ($listId = Arr::get($settings, 'target_list')) {
$subscriberData['lists'] = [$listId];
}
if ($tags = Arr::get($settings, 'target_tags')) {
$subscriberData['tags'] = $tags;
}
$isDoubleOptin = Arr::get($settings, 'double_optin') == 'yes';
if ($isDoubleOptin) {
$subscriberData['status'] = 'pending';
} else {
$subscriberData['status'] = 'subscribed';
}
$contact = FunnelHelper::createOrUpdateContact($subscriberData);
if (!$contact) {
return false;
}
if ($contact->status == 'pending' && $subscriberData['status'] == 'pending') {
$contact->sendDoubleOptinEmail();
}
add_action('updated_user_meta', function ($meta_id, $userId, $meta_key, $_meta_value) use ($contact) {
if ($userId == $contact->user_id && ($meta_key == 'first_name' || $meta_key == 'last_name') && $_meta_value) {
if ($contact->{$meta_key} != $_meta_value) {
fluentCrmDb()->table('fc_subscribers')
->where('id', $contact->id)
->update([
$meta_key => $_meta_value
]);
}
}
}, 10, 4);
}
public function addSubscribeCheckbox($buttonHtml)
{
$settings = (new AutoSubscribe())->getCommentSettings();
/**
* Determine the settings for the comment form subscribe feature in FluentCRM.
*
* This filter allows modification of the settings used for the comment form subscribe feature in FluentCRM.
*
* @param array $settings The current settings for the comment form subscribe feature.
* @return array The modified settings for the comment form subscribe feature.
* @since 2.7.0
*
*/
$settings = apply_filters('fluent_crm/comment_form_subscribe_settings', $settings);
if (Arr::get($settings, 'status') != 'yes') {
return $buttonHtml;
}
if (Arr::get($settings, 'show_only_new') == 'yes') {
if ($userId = get_current_user_id()) {
$user = get_user_by('ID', $userId);
$contact = Subscriber::where('user_id', $userId)->orWhere('email', $user->user_email)->first();
if ($contact && $contact->status == 'subscribed') {
return $buttonHtml;
}
}
}
$label = Arr::get($settings, 'checkbox_label');
if (!$label) {
$label = __('Subscribe to newsletter', 'fluent-crm');
}
$checkedTag = '';
if (Arr::get($settings, 'auto_checked') == 'yes') {
$checkedTag = 'checked="true"';
}
$html = '<p class="comment-form-fc-consent comment-form-cookies-consent"><input ' . $checkedTag . ' id="wp-comment-fc-consent" name="wp-comment-fc-consent" type="checkbox" value="yes"><label for="wp-comment-fc-consent">' . $label . '</label></p>';
return $html . $buttonHtml;
}
public function handleCommentPost($commentId, $isApproved, $commentData)
{
// is this a spam comment?
if ($isApproved === 'spam') {
return false;
}
if (defined('WC_PLUGIN_FILE') && Arr::get($commentData, 'comment_type') == 'review') {
do_action('fluentcrm_woo_review_comment_post', $commentId, $isApproved, $commentData);
}
$isChecked = Arr::get($_REQUEST, 'wp-comment-fc-consent') == 'yes';
if (!$isChecked) {
return false;
}
$subscriberData = [
'full_name' => Arr::get($commentData, 'comment_author'),
'email' => Arr::get($commentData, 'comment_author_email'),
'ip_address' => Arr::get($commentData, 'comment_author_IP')
];
if ($userId = Arr::get($commentData, 'user_id')) {
$subscriberData['user_id'] = $userId;
}
$subscriberData = array_filter($subscriberData);
$settings = (new AutoSubscribe())->getCommentSettings();
if ($listId = Arr::get($settings, 'target_list')) {
$subscriberData['lists'] = [$listId];
}
if ($tags = Arr::get($settings, 'target_tags')) {
$subscriberData['tags'] = $tags;
}
$isDoubleOptin = Arr::get($settings, 'double_optin') == 'yes';
if ($isDoubleOptin) {
$subscriberData['status'] = 'pending';
}
$contact = FunnelHelper::createOrUpdateContact($subscriberData);
if (!$contact) {
return false;
}
if (!$contact->country) {
// get CF Country from request header: CF-IPCountry
$countryCode = sanitize_text_field($_SERVER['HTTP_CF_IPCOUNTRY'] ?? '');
if ($countryCode && preg_match('/^[A-Z]{2}$/', $countryCode) && $countryCode !== 'XX') {
$contact->country = $countryCode;
$contact->save();
}
}
if ($contact->status == 'pending') {
$contact->sendDoubleOptinEmail();
}
return true;
}
public function syncUserUpdate($userId, $oldData, $newData = [])
{
if (is_multisite() && is_network_admin()) {
return false;
}
if (!empty($newData['user_pass'])) {
$user = get_user_by('ID', $userId);
(new Cleanup())->handleUserPasswordChanged($user);
}
if (!Helper::isUserSyncEnabled()) {
return false;
}
// check if user email has been changed
$user = get_user_by('ID', $userId);
if ($user->user_email != $oldData->user_email) {
// email has been changed
$oldSubscriber = Subscriber::where('email', $oldData->user_email)->first();
// check if a contact is exist with the new email id
$newSubscriber = Subscriber::where('email', $user->user_email)->first();
if ($newSubscriber) {
fluentCrmDb()->table('fc_subscribers')
->where('id', $oldSubscriber->id)
->update([
'user_id' => ''
]);
$oldSubscriber = false;
}
if ($oldSubscriber) {
$updateData = [
'email' => $user->user_email,
'hash' => md5($user->user_email),
'updated_at' => current_time('mysql'),
'user_id' => $user->ID
];
if ($user->first_name) {
$updateData['first_name'] = $user->first_name;
}
if ($user->last_name) {
$updateData['last_name'] = $user->last_name;
}
return fluentCrmDb()->table('fc_subscribers')
->where('id', $oldSubscriber->id)
->update($updateData);
}
}
// we just have to change the first name and lastname
$updateData = Helper::getWPMapUserInfo($user);
unset($updateData['email']);
if (!$updateData) {
return false;
}
$updateData['updated_at'] = current_time('mysql');
return fluentCrmDb()->table('fc_subscribers')
->where('email', $user->user_email)
->update($updateData);
}
public function maybeDeleteContact($userId, $reassignId, $user)
{
if (is_multisite() && is_network_admin()) {
return false;
}
if (!Helper::isContactDeleteOnUserDeleteEnabled()) {
return false;
}
$subscriber = Subscriber::where('user_id', $userId)->first();
if (!$subscriber) {
$subscriber = Subscriber::where('email', $user->user_email)->first();
}
if (!$subscriber) {
return false;
}
return Helper::deleteContacts([$subscriber->id]);
}
public function syncWooAddressUpdate($userId, $addressType)
{
if ($addressType != 'billing') {
return;
}
$customer = new \WC_Customer($userId);
if (!$customer || !$customer->get_id()) {
return;
}
$user = get_user_by('ID', $userId);
$contact = Subscriber::where('email', $user->user_email)->first();
$addressData = $customer->get_billing();
$updateData = [
'user_id' => $userId,
'address_line_1' => $addressData['address_1'],
'address_line_2' => $addressData['address_2'],
'city' => $addressData['city'],
'state' => $addressData['state'],
'country' => $addressData['country'],
'postal_code' => $addressData['postcode']
];
if ($contact) {
$contact->fill($updateData);
$dirty = $contact->getDirty();
if ($dirty) {
fluentCrmDb()->table('fc_subscribers')
->where('id', $contact->id)
->update($dirty);
$contact = Subscriber::find($contact->id);
do_action('fluent_crm/contact_updated', $contact, $dirty);
}
} else {
FluentCrmApi('contacts')->createOrUpdate($updateData);
}
}
public function maybeAddCountryToProfile($userLogin, $wpUser)
{
// get CF Country from request header: CF-IPCountry
$countryCode = sanitize_text_field($_SERVER['HTTP_CF_IPCOUNTRY'] ?? '');
if (!$countryCode || !preg_match('/^[A-Z]{2}$/', $countryCode) || $countryCode === 'XX') {
return;
}
$contact = Subscriber::where('email', $wpUser->user_email)->first();
if (!$contact || $contact->country) {
return;
}
$updateData = [
'country' => $countryCode
];
if (empty($contact->user_id) || (int) $contact->user_id === (int) $wpUser->ID) {
$updateData['user_id'] = $wpUser->ID;
}
fluentCrmDb()->table('fc_subscribers')
->where('id', $contact->id)
->update($updateData);
}
}
@@ -0,0 +1,60 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
/**
* CampaignGuard Class
*
* Used to handle concurrent requests for the same campaign.
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class CampaignGuard
{
const FORBIDDEN_CODE = 403;
public function checkIsActive($campaign)
{
if (!$campaign) {
$this->send('The campaign is not available anymore.');
}
$status = $campaign->status;
if (!in_array($status, ['draft', 'pending', 'incomplete', 'purged', 'scheduled'])) {
$message = __('The campaign has been locked and not modifiable due to it\'s current status', 'fluent-crm');
$message .= ": <strong>{$status}</strong>.";
$this->send($message);
}
return;
}
public function checkIsWorking($campaign)
{
if (!$campaign) {
$this->send('The campaign is not available anymore.');
}
$status = $campaign->status;
if ($status == 'working') {
$message = __("The campaign has been locked and not deletable due to it's current status", "fluent-crm");
$message .= ": <strong>{$status}</strong>.";
$this->send($message);
}
return;
}
protected function send($message)
{
FluentCrm('response')->sendError([
'status' => self::FORBIDDEN_CODE,
'message' => "<p style='font-weight:500;color:#606266;'>{$message}</p>"
], self::FORBIDDEN_CODE);
}
}
@@ -0,0 +1,373 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\CampaignEmail;
use FluentCrm\App\Models\CampaignUrlMetric;
use FluentCrm\App\Models\Company;
use FluentCrm\App\Models\CompanyNote;
use FluentCrm\App\Models\FunnelMetric;
use FluentCrm\App\Models\FunnelSubscriber;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Models\SubscriberMeta;
use FluentCrm\App\Models\SubscriberNote;
use FluentCrm\App\Models\SubscriberPivot;
use FluentCrm\App\Services\BlockParser;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Models\Meta;
/**
* Cleanup Class
*
* Used to handle cleanup related assets for subscribers, campaigns and automations.
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class Cleanup
{
/**
* Cleanup related data of a subscriber.
*
* @param array $subscriberIds
*/
public function deleteSubscribersAssets($subscriberIds)
{
CampaignEmail::whereIn('subscriber_id', $subscriberIds)->delete();
CampaignUrlMetric::whereIn('subscriber_id', $subscriberIds)->delete();
SubscriberMeta::whereIn('subscriber_id', $subscriberIds)->delete();
SubscriberNote::whereIn('subscriber_id', $subscriberIds)->delete();
SubscriberPivot::whereIn('subscriber_id', $subscriberIds)->delete();
FunnelMetric::whereIn('subscriber_id', $subscriberIds)->delete();
FunnelSubscriber::whereIn('subscriber_id', $subscriberIds)->delete();
if (defined('FLUENTCAMPAIGN_DIR_FILE')) {
\FluentCampaign\App\Models\SequenceTracker::whereIn('subscriber_id', $subscriberIds)->delete();
}
if (Helper::isExperimentalEnabled('company_module')) {
Company::whereIn('owner_id', $subscriberIds)
->update([
'owner_id' => NULL
]);
}
}
/**
* Cleanup related data of a campaign.
*
* @param int $campaignId
*/
public function deleteCampaignAssets($campaignId)
{
// Idempotent backstop — Campaign::deleteCampaignData() already removes
// these in the normal delete flow, but we keep this here so any
// future caller that fires fluent_crm/campaign_deleted without
// running deleteCampaignData() first still gets a clean teardown.
CampaignEmail::where('campaign_id', $campaignId)->delete();
CampaignUrlMetric::where('campaign_id', $campaignId)->delete();
}
/**
* Cleanup related data of a list.
*
* @param int $listId
*/
public function deleteListAssets($listId)
{
SubscriberPivot::where('object_type', 'FluentCrm\App\Models\Lists')->where('object_id', $listId)->delete();
}
/**
* Cleanup related data of a tag.
*
* @param int $listId
*/
public function deleteTagAssets($listId)
{
SubscriberPivot::where('object_type', 'FluentCrm\App\Models\Tag')->where('object_id', $listId)->delete();
}
/**
* Cancel Future Emails.
*
* @param \FluentCrm\App\Models\Subscriber $subscriber
*/
public function handleUnsubscribe($subscriber)
{
// Per-statement try/catch: a row-lock deadlock against the mailer
// workers on the CampaignEmail update should not also block the
// FunnelSubscriber / SequenceTracker cancellations. The next status
// transition (or a manual retry) will reconcile any rows we miss.
try {
CampaignEmail::where('subscriber_id', $subscriber->id)
->whereIn('status', ['pending', 'scheduled', 'draft', 'processing', 'scheduling'])
->update([
'status' => 'cancelled'
]);
} catch (\Exception $e) {
Helper::debugLog('handleUnsubscribe', 'CampaignEmail cancel deferred: ' . $e->getMessage(), 'extended');
}
try {
FunnelSubscriber::where('subscriber_id', $subscriber->id)
->where('status', 'active')
->whereDoesntHave('funnel', function ($query) {
$query->where('trigger_name', 'fluent_crm/subscriber_status_changed');
})
->update([
'status' => 'cancelled'
]);
} catch (\Exception $e) {
Helper::debugLog('handleUnsubscribe', 'FunnelSubscriber cancel deferred: ' . $e->getMessage(), 'extended');
}
if (defined('FLUENTCAMPAIGN')) {
try {
\FluentCampaign\App\Models\SequenceTracker::where('subscriber_id', $subscriber->id)
->where('status', 'active')
->update([
'status' => 'cancelled'
]);
} catch (\Exception $e) {
Helper::debugLog('handleUnsubscribe', 'SequenceTracker cancel deferred: ' . $e->getMessage(), 'extended');
}
}
}
/**
* Change the future emails email_address of a provided contact.
*
* @param \FluentCrm\App\Models\Subscriber $subscriber
*/
public function handleContactEmailChanged($subscriber)
{
CampaignEmail::where('subscriber_id', $subscriber->id)
->whereIn('status', ['draft', 'scheduled'])
->update([
'email_address' => $subscriber->email
]);
}
/**
* @param $userId int
* @param $resign int|null
* @param $deletedUser \WP_User
* @return bool
*/
public function handleUserDelete($userId, $resign, $deletedUser)
{
$settings = Helper::getComplianceSettings();
if ($settings['delete_contact_on_user'] !== 'yes') {
return false;
}
$subscriber = Subscriber::where('user_id', $userId)->first();
if (!$subscriber && $deletedUser) {
$subscriber = Subscriber::where('email', $deletedUser->user_email)->first();
}
if (!$subscriber) {
return false;
}
// delete the subscriber now;
Helper::deleteContacts([$subscriber->id]);
return true;
}
public function attachCrmExporter($exporters)
{
$settings = Helper::getComplianceSettings();
if ($settings['personal_data_export'] !== 'yes') {
return $exporters;
}
$exporters['fluent-crm'] = [
'exporter_friendly_name' => __('FluentCRM Data', 'fluent-crm'),
'callback' => [$this, 'exportPersonalDataWP'],
];
return $exporters;
}
public function exportPersonalDataWP($user_email, $page = 1)
{
$subscriber = Subscriber::where('email', $user_email)->first();
if (!$subscriber) {
return [
'data' => [],
'done' => true
];
}
$customerFields = $subscriber->custom_fields();
$mainFields = $subscriber->toArray();
$data = [
'group_id' => 'fluent-crm-contact',
'group_label' => __('FluentCRM Data', 'fluent-crm'),
'item_id' => 'crm-contact',
'data' => []
];
foreach ($mainFields as $fieldKey => $fieldValue) {
if ($fieldValue) {
$data['data'][] = [
'name' => $fieldKey,
'value' => $fieldValue
];
}
}
foreach ($customerFields as $fieldKey => $customerField) {
$data['data'][] = [
'name' => $fieldKey,
'value' => $customerField
];
}
return [
'data' => [$data],
'done' => true,
];
}
public function handleCompanyDelete($id)
{
/*
* Remove Company ID from all connected subscribers
*/
Subscriber::where('company_id', $id)->update([
'company_id' => NULL
]);
fluentCrmDb()->table('fc_subscriber_pivot')
->where('object_id', $id)
->where('object_type', 'FluentCrm\App\Models\Company')
->delete();
// Delete company notes
CompanyNote::where('subscriber_id', $id)->delete();
}
public function handleUserPasswordChanged($user)
{
$contact = Subscriber::where('email', $user->user_email)
->first();
if (!$contact) {
return false;
}
$exist = SubscriberMeta::where('subscriber_id', $contact->id)
->where('key', '_secure_managed_hash')
->first();
if (!$exist) {
return false;
}
$hash = md5(wp_generate_uuid4() . '_' . $contact->id . '_' . '_' . time() . '__' . $contact->id);
$exist->value = $hash;
$exist->updated_at = current_time('mysql');
$exist->save();
return true;
}
public function archiveCampaignAssets($campaign)
{
if ($campaign->type != 'campaign' || fluentcrm_get_campaign_meta($campaign->id, '_cached_email_body', true)) {
return;
}
// We will create email body and then cache it for future use
$rawTemplates = [
'raw_html',
'visual_builder',
'raw_classic'
];
if (in_array($campaign->design_template, $rawTemplates)) {
$emailBody = $campaign->email_body;
} else {
$emailBody = (new BlockParser())->parse($campaign->email_body);
}
fluentcrm_update_campaign_meta($campaign->id, '_cached_email_body', $emailBody);
return true;
}
public static function maybeRemoveOldScheuledActionLogs()
{
$group_slug = 'fluent-crm';
$days_old = 7;
global $wpdb;
// Get the timestamp for 7 days ago
$cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$days_old} days"));
// Get the group ID
$group_id = $wpdb->get_var($wpdb->prepare(
"SELECT group_id FROM {$wpdb->prefix}actionscheduler_groups WHERE slug = %s",
$group_slug
));
if (!$group_id) {
return false; // Group not found
}
// Delete old actions and their associated logs
$deleted = $wpdb->query($wpdb->prepare("
DELETE a, l
FROM {$wpdb->prefix}actionscheduler_actions a
LEFT JOIN {$wpdb->prefix}actionscheduler_logs l ON a.action_id = l.action_id
WHERE a.group_id = %d
AND a.status IN ('complete', 'failed')
AND a.scheduled_date_gmt < %s", $group_id, $cutoff_date));
// Clean up orphaned claims
$wpdb->query("
DELETE c
FROM {$wpdb->prefix}actionscheduler_claims c
LEFT JOIN {$wpdb->prefix}actionscheduler_actions a ON c.claim_id = a.claim_id
WHERE a.action_id IS NULL");
return $deleted;
}
public function SyncSubscriberDeleteSettings($fromKey, $value)
{
if ($fromKey == 'compliance_settings') {
$option = Meta::where('key', 'user_syncing_settings')
->where('object_type', 'option')
->first();
if ($option) {
$settings = $option->value;
if ($settings['delete_contact_on_user_delete'] != $value) {
$settings['delete_contact_on_user_delete'] = $value;
$option->value = $settings;
$option->save();
}
}
} else {
$complianceSettings = get_option('_fluentcrm_compliance_settings');
if ($complianceSettings) {
$complianceSettings['delete_contact_on_user'] = $value;
update_option('_fluentcrm_compliance_settings', $complianceSettings, 'no');
}
}
}
}
@@ -0,0 +1,169 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Meta;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
/**
* ContactActivityLogger Class
*
* Logs Contact's activity based on different WordPress Events.
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class ContactActivityLogger
{
public function register()
{
// Login Tracker
add_action('wp_login', array($this, 'trackLogin'), 10, 2);
// Global Tracker
add_action('fluent_crm/track_activity_by_subscriber', array($this, 'trackActivityBySubscriber'));
add_action('fluent_crm/email_opened_anonymously', [$this, 'trackEmailOpenAnonymously'], 10, 1);
add_action('fluent_crm/anonymous_email_url_clicked', [$this, 'trackEmailClickAnonymously'], 10, 2);
}
public function trackLogin($username, $user)
{
update_user_meta($user->ID, '_last_login', current_time('mysql'));
$this->trackActivityByUser($user, 'login');
}
public function trackActivityByUser($user, $type = '')
{
if (is_numeric($user)) {
$user = get_user_by('ID', $user);
}
if (!$user || empty($user->user_email)) {
return;
}
$subscriber = Subscriber::where('email', $user->user_email)->first();
if (!$subscriber) {
return;
}
$this->trackActivityBySubscriber($subscriber);
if ($type == 'login') {
fluentcrm_update_subscriber_meta($subscriber->id, '_last_login', current_time('mysql'));
}
return true;
}
public function trackActivityBySubscriber($subscriber)
{
if (!$subscriber) {
return;
}
if (is_numeric($subscriber)) {
$subscriber = Subscriber::where('id', $subscriber)->first();
}
if (!$subscriber) {
return;
}
if ($subscriber->last_activity && strtotime($subscriber->last_activity) > (current_time('timestamp') - 3600)) {
return;
}
$data = [
'last_activity' => current_time('mysql')
];
if (!$subscriber->ip && fluentCrmWillTrackIp()) {
$ip = FluentCrm('request')->getIp(fluentCrmWillAnonymizeIp());
if ($ip != '127.0.0.1') {
$data['ip'] = $ip;
}
}
return fluentCrmDb()->table('fc_subscribers')
->where('id', $subscriber->id)
->update($data);
}
public function trackEmailOpenAnonymously($campaignEmaillModel)
{
if (!$campaignEmaillModel->campaign_id) {
return;
}
// check if the campaign exist
global $wpdb;
$exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT 1 FROM {$wpdb->prefix}fc_campaigns WHERE id = %d LIMIT 1",
$campaignEmaillModel->campaign_id
)
);
if (!$exists) {
return;
}
$existingMetaModel = fluentcrm_get_campaign_meta($campaignEmaillModel->campaign_id, '_ano_open_count', false);
if ($existingMetaModel) {
global $wpdb;
$wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->prefix}fc_meta SET value = value + 1 WHERE id = %d",
$existingMetaModel->id
));
} else {
// we creating new one
Meta::create([
'key' => '_ano_open_count',
'value' => 1,
'object_id' => $campaignEmaillModel->campaign_id,
'object_type' => 'FluentCrm\App\Models\Campaign'
]);
}
return true;
}
public function trackEmailClickAnonymously($url, $campaign)
{
$existingMetaModel = fluentcrm_get_campaign_meta($campaign->id, '_ano_url_clicks', false);
$url = (string)$url;
if ($existingMetaModel) {
$urls = is_array($existingMetaModel->value) ? $existingMetaModel->value : [];
if (isset($urls[$url])) {
$urls[$url] = (int)$urls[$url] + 1;
} else {
$urls[$url] = 1;
}
$existingMetaModel->value = $urls;
$existingMetaModel->save();
} else {
Meta::create([
'key' => '_ano_url_clicks',
'value' => [
$url => 1
],
'object_id' => $campaign->id,
'object_type' => 'FluentCrm\App\Models\Campaign'
]);
}
return true;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
/**
* DeactivationHandler Class
*
* FluentCRM Deactivation Handler Class.
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class DeactivationHandler
{
public function handle()
{
if (function_exists('\as_unschedule_all_actions')) {
as_unschedule_all_actions('fluentcrm_scheduled_every_minute_tasks');
as_unschedule_all_actions('fluent_crm_ascheduler_runs_daily');
}
wp_clear_scheduled_hook('fluentcrm_scheduled_minute_tasks');
wp_clear_scheduled_hook('fluentcrm_scheduled_hourly_tasks');
wp_clear_scheduled_hook('fluentcrm_scheduled_weekly_tasks');
wp_clear_scheduled_hook('fluentcrm_scheduled_five_minute_tasks');
wp_clear_scheduled_hook('fluentcrm_scheduled_daily_tasks');
}
}
@@ -0,0 +1,226 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Services\Sanitize;
use FluentCrm\App\Services\Libs\Emogrifier\Emogrifier;
use FluentCrm\Framework\Support\Arr;
/**
* EmailDesignTemplates Class
*
* For handling email design templates
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class EmailDesignTemplates
{
public function register()
{
add_filter('fluent_crm/email-design-template-block_editor', [$this, 'addBlockEditorTemplate'], 10, 3);
add_filter('fluent_crm/email-design-template-simple', [$this, 'addBlockEditorTemplate'], 10, 3);
add_filter('fluent_crm/email-design-template-plain', [$this, 'addBlockEditorTemplate'], 10, 3);
add_filter('fluent_crm/email-design-template-classic', [$this, 'addBlockEditorTemplate'], 10, 3);
add_filter('fluent_crm/email-design-template-raw_classic', [$this, 'addRawClassicTemplate'], 10, 3);
add_filter('fluent_crm/email-design-template-web_preview', [$this, 'addWebPreviewTemplate'], 10, 3);
}
public function addBlockEditorTemplate($emailBody, $templateData, $campaign)
{
$templateData = $this->filterTemplateData($templateData);
$templateData['email_body'] = $emailBody;
$view = FluentCrm('view');
$emailBody = $view->make('emails.block_editor.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
/**
* @param string $emailBody
* @param array $templateData
* @param \FluentCrm\App\Models\Campaign $campaign
* @return string
*/
public function addPlainTemplate($emailBody, $templateData, $campaign)
{
$templateData = $this->filterTemplateData($templateData);
$view = FluentCrm('view');
$emailBody = $view->make('emails.plain.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
/**
* @param string $emailBody
* @param array $templateData
* @param \FluentCrm\App\Models\Campaign $campaign
* @return string
*/
public function addSimpleTemplate($emailBody, $templateData, $campaign)
{
if (empty($templateData['config']['body_bg_color'])) {
$templateData['config']['body_bg_color'] = '#FAFAFA';
}
if (empty($templateData['config']['content_bg_color'])) {
$templateData['config']['content_bg_color'] = '#ffffff';
}
$templateData = $this->filterTemplateData($templateData);
$view = FluentCrm('view');
$emailBody = $view->make('emails.simple.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
/**
* @param string $emailBody
* @param array $templateData
* @param \FluentCrm\App\Models\Campaign $campaign
* @return string
*/
public function addClassicTemplate($emailBody, $templateData, $campaign)
{
if (empty($templateData['config']['content_bg_color'])) {
$templateData['config']['content_bg_color'] = '#ffffff';
}
$templateData = $this->filterTemplateData($templateData);
$view = FluentCrm('view');
$emailBody = $view->make('emails.classic.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
/**
* @param string $emailBody
* @param array $templateData
* @param \FluentCrm\App\Models\Campaign $campaign
* @return string
*/
public function addRawClassicTemplate($emailBody, $templateData, $campaign)
{
$templateData = $this->filterTemplateData($templateData);
$configDefault = [
'content_width' => '',
'content_padding' => '',
'headings_font_family' => '',
'text_color' => '',
'link_color' => '',
'body_bg_color' => '',
'content_bg_color' => '',
'footer_text_color' => '',
'content_font_family' => "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'",
'paragraph_color' => '',
'paragraph_font_size' => '',
'paragraph_font_family' => '',
'paragraph_line_height' => '',
'headings_color' => ''
];
$templateData['config'] = wp_parse_args($templateData['config'], $configDefault);
$view = FluentCrm('view');
$emailBody = $view->make('emails.raw_classic.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
public function addWebPreviewTemplate($emailBody, $templateData, $campaign)
{
$templateData = $this->filterTemplateData($templateData);
$configDefault = [
'content_width' => '',
'content_padding' => '',
'headings_font_family' => '',
'text_color' => '',
'link_color' => '',
'body_bg_color' => '',
'content_bg_color' => '',
'footer_text_color' => '',
'content_font_family' => "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'",
'paragraph_color' => '',
'paragraph_font_size' => '',
'paragraph_font_family' => '',
'paragraph_line_height' => '',
'headings_color' => ''
];
$templateData['config'] = wp_parse_args($templateData['config'], $configDefault);
$view = FluentCrm('view');
$emailBody = $view->make('emails.web_preview.Template', $templateData);
$emailBody = $emailBody->__toString();
$emogrifier = new Emogrifier($emailBody);
$emogrifier->disableInvisibleNodeRemoval();
return $emogrifier->emogrify();
}
private function filterTemplateData($templateData)
{
$footerConfig = Arr::get($templateData, 'footer_config', []);
$disableFooter = Arr::get($footerConfig, 'disable_footer');
if ($disableFooter !== 'yes' && $disableFooter !== 'no') {
$disableFooter = Arr::get($templateData, 'config.disable_footer');
}
if ($disableFooter == 'yes') {
$templateData['footer_text'] = '';
} else {
$style = 'font-size: 13px; color: #202020;';
if ($footerConfig) {
$fontSize = Arr::get($footerConfig, 'font_size', 13) . 'px';
$color = sanitize_hex_color(Arr::get($footerConfig, 'font_color', '#202020')) ?: '#202020';
$backgroundColor = Arr::get($footerConfig, 'background_color', 'transparent');
$paddingRaw = Arr::get($footerConfig, 'footer_padding');
$safeBackgroundColor = sanitize_hex_color($backgroundColor);
if ($backgroundColor === 'transparent') {
$safeBackgroundColor = 'transparent';
}
$safePadding = 20;
if ($paddingRaw !== null && $paddingRaw !== '') {
$safePadding = min(80, max(0, intval($paddingRaw)));
}
$style = "font-size: {$fontSize}; color: {$color};";
if ($safeBackgroundColor) {
$style .= " background-color: {$safeBackgroundColor};";
}
$style .= " padding: {$safePadding}px;";
$templateData['footer_text'] = Sanitize::sanitizeFooterHtml($footerConfig['footer_content'] ?? '');
}
if($templateData['footer_text']) {
$templateData['footer_text'] = "<div style='{$style}'>{$templateData['footer_text']}</div>";
}
}
return $templateData;
}
}
@@ -0,0 +1,369 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\EventTracker;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
class EventTrackingHandler
{
public function register()
{
add_filter('fluentcrm_ajax_options_event_tracking_keys', [$this, 'getEventTrackingKeyOptions'], 10, 1);
add_action('fluentcrm_contacts_filter_event_tracking', [$this, 'applyEventTrackingFilter'], 10, 2);
add_action('fluent_crm/track_event_activity', [$this, 'trackEventActivity'], 10, 2);
add_filter('fluent_crm/subscriber_info_widgets', [$this, 'addSubscriberInfoWidgets'], 10, 2);
add_filter('fluent_crm/subscriber_info_widget_event_tracking', [$this, 'addSubscriberInfoWidgets'], 10, 2);
add_filter('fluentcrm_advanced_filter_options', [$this, 'addEventTrackingFilterOptions'], 10, 1);
add_filter('fluent_crm/event_tracking_condition_groups', [$this, 'addEventTrackingConditionOptions'], 10, 1);
add_filter('fluentcrm_automation_condition_groups', function ($groups) {
if (!Helper::isExperimentalEnabled('event_tracking')) {
return $groups;
}
$groups['event_tracking'] = [
'label' => __('Event Tracking', 'fluent-crm'),
'value' => 'event_tracking',
'children' => $this->getConditionItems()
];
return $groups;
});
}
public function getEventTrackingKeyOptions($options = [])
{
$items = EventTracker::select(['event_key'])
->groupBy('event_key')
->orderBy('event_key', 'ASC')
->get();
$formattedItems = [];
foreach ($items as $item) {
$formattedItems[] = [
'id' => $item->event_key,
'title' => $item->event_key
];
}
return $formattedItems;
}
public function applyEventTrackingFilter($query, $filters)
{
if (!Helper::isExperimentalEnabled('event_tracking')) {
return $query;
}
foreach ($filters as $filter) {
if (!array_key_exists('value', $filter) || $filter['value'] === '') {
continue;
}
$relation = 'trackingEvents';
$filterProp = $filter['property'];
if ($filterProp == 'event_tracking_key') {
$operator = $filter['operator'];
$values = $filter['value'];
if ($operator == 'not_in') {
$query->whereDoesntHave($relation, function ($q) use ($values) {
$q->whereIn('event_key', $values);
});
} else {
$query->whereHas($relation, function ($q) use ($values) {
$q->whereIn('event_key', $values);
});
}
continue;
}
if ($filterProp == 'event_tracking_title') {
$operator = $filter['operator'];
if ($operator == '=') {
$query->whereHas($relation, function ($q) use ($filter) {
$q->where('title', $filter['value']);
});
} else if ($operator == '!=') {
$query->whereDoesntHave($relation, function ($q) use ($filter) {
$q->where('title', $filter['value']);
});
} else if ($operator == 'contains') {
$query->whereHas($relation, function ($q) use ($filter) {
$q->where('title', 'LIKE', '%' . $filter['value'] . '%');
});
} else if ($operator == 'not_contains') {
$query->whereDoesntHave($relation, function ($q) use ($filter) {
$q->where('title', 'LIKE', '%' . $filter['value'] . '%');
});
}
continue;
}
if ($filterProp == 'event_tracking_value') {
$eventKey = Arr::get($filter, 'extra_value');
if (!$eventKey) {
continue;
}
$operator = $filter['operator'];
if ($operator == '=') {
$query->whereHas($relation, function ($q) use ($filter, $eventKey) {
$q->where('value', $filter['value'])
->where('event_key', $eventKey);
});
} else if ($operator == '!=') {
$query->whereDoesntHave($relation, function ($q) use ($filter, $eventKey) {
$q->where('value', $filter['value'])
->where('event_key', $eventKey);
});
} else if (in_array($operator, ['<', '>'])) {
$query->whereHas($relation, function ($q) use ($filter, $eventKey, $operator) {
$q->where('value', $operator, (int)$filter['value'])
->where('event_key', $eventKey);
});
} else if ($operator == 'contains') {
$query->whereHas($relation, function ($q) use ($filter, $eventKey) {
$q->where('value', 'LIKE', '%' . $filter['value'] . '%')
->where('event_key', $eventKey);
});
} else if ($operator == 'not_contains') {
$query->whereDoesntHave($relation, function ($q) use ($filter, $eventKey) {
$q->where('value', 'LIKE', '%' . $filter['value'] . '%')
->where('event_key', $eventKey);
});
}
continue;
}
if ($filterProp == 'event_tracking_key_count') {
$eventKey = Arr::get($filter, 'extra_value');
if (!$eventKey) {
continue;
}
$operator = $filter['operator'];
if ($operator == '=') {
$query->whereHas($relation, function ($q) use ($filter, $eventKey) {
$q->where('counter', $filter['value'])
->where('event_key', $eventKey);
});
} else if ($operator == '!=') {
$query->whereDoesntHave($relation, function ($q) use ($filter, $eventKey) {
$q->where('counter', $filter['value'])
->where('event_key', $eventKey);
});
} else if (in_array($operator, ['<', '>'])) {
$query->whereHas($relation, function ($q) use ($filter, $eventKey, $operator) {
$q->where('counter', $operator, (int)$filter['value'])
->where('event_key', $eventKey);
});
}
continue;
}
}
return $query;
}
public function trackEventActivity($data, $repeatable = true)
{
return FluentCrmApi('event_tracker')->track($data, $repeatable);
}
public function addSubscriberInfoWidgets($widgets, $subscriber)
{
if (!Helper::isExperimentalEnabled('event_tracking')) {
return $widgets;
}
$events = EventTracker::where('subscriber_id', $subscriber->id)
->orderBy('updated_at', 'DESC')
->paginate();
if ($events->isEmpty()) {
return $widgets;
}
$html = '<div class="fc_scrolled_lists"><ul class="fcrm_event_tracking_lists">';
foreach ($events as $event) {
$html .= '<li>';
$html .= '<p class="fcrm_event_tracking_title">' . esc_html($event->title) . '</p>';
if ($event->value) {
$html .= '<p class="fcrm_event_tracking_value">' . wp_kses_post($event->value) . '</p>';
}
$html .= '<div class="fcrm_event_tracking_footer">';
$html .= '<div class="fcrm_event_tracking_badge">' . esc_attr($event->event_key) . '<span class="fcrm_event_tracking_count">(' . esc_html($event->counter) . ')</span></div>';
$html .= '<span class="fcrm_event_tracking_date">' . $event->updated_at . '</span>';
$html .= '</div>';
$html .= '</li>';
}
$html .= '</ul></div>';
$widgets['event_tracking'] = [
'title' => __('Event Tracking', 'fluent-crm'),
'content' => $html,
'has_pagination' => $events->total() > $events->perPage(),
'total' => $events->total(),
'per_page' => $events->perPage(),
'current_page' => $events->currentPage()
];
return $widgets;
}
public function addEventTrackingFilterOptions($groups)
{
if (!Helper::isExperimentalEnabled('event_tracking')) {
return $groups;
}
$groups['event_tracking'] = [
'label' => __('Event Tracking', 'fluent-crm'),
'value' => 'event_tracking',
'children' => $this->getConditionItems()
];
return $groups;
}
public function addEventTrackingConditionOptions($items)
{
if (!Helper::isExperimentalEnabled('event_tracking')) {
return $items;
}
return [
[
'label' => __('Event Tracking', 'fluent-crm'),
'value' => 'event_tracking',
'children' => $this->getConditionItems()
],
[
'label' => __('Contact Segment', 'fluent-crm'),
'value' => 'segment',
'children' => [
[
'label' => __('Type', 'fluent-crm'),
'value' => 'contact_type',
'type' => 'selections',
'component' => 'options_selector',
'option_key' => 'contact_types',
'is_multiple' => false,
'is_singular_value' => true
],
[
'label' => __('Tags', 'fluent-crm'),
'value' => 'tags',
'type' => 'selections',
'component' => 'options_selector',
'option_key' => 'tags',
'is_multiple' => true,
],
[
'label' => __('Lists', 'fluent-crm'),
'value' => 'lists',
'type' => 'selections',
'component' => 'options_selector',
'option_key' => 'lists',
'is_multiple' => true,
]
],
]
];
}
private function getConditionItems()
{
return [
[
'label' => __('Event Key', 'fluent-crm'),
'value' => 'event_tracking_key',
'type' => 'selections',
'component' => 'ajax_selector',
'option_key' => 'event_tracking_keys',
'is_multiple' => true,
'custom_operators' => [
'in' => 'in',
'not_in' => 'not in'
],
'creatable' => true,
'experimental_cache' => true,
'help' => __('Match one or more tracking events for your contacts.', 'fluent-crm')
],
[
'label' => __('Event Occurrence Count', 'fluent-crm'),
'value' => 'event_tracking_key_count',
'type' => 'composite_optioned_compare',
'help' => __('The provided value for your selected event will be matched with the event occurrence count', 'fluent-crm'),
'ajax_selector' => [
'label' => __('For Event Key', 'fluent-crm'),
'option_key' => 'event_tracking_keys',
'experimental_cache' => true,
'is_multiple' => false,
'placeholder' => __('Select Event Key', 'fluent-crm')
],
'value_config' => [
'label' => __('Event Count', 'fluent-crm'),
'type' => 'input_text',
'data_type' => 'number',
'placeholder' => __('Event Value', 'fluent-crm')
],
'custom_operators' => [
'=' => 'equal',
'!=' => 'not equal',
'>' => 'greater than',
'<' => 'less than'
],
],
[
'label' => __('Event Value', 'fluent-crm'),
'value' => 'event_tracking_value',
'type' => 'composite_optioned_compare',
'help' => __('The compare value will be matched with selected event & last recorded value of the selected event key', 'fluent-crm'),
'ajax_selector' => [
'label' => __('For Event Key', 'fluent-crm'),
'option_key' => 'event_tracking_keys',
'experimental_cache' => true,
'is_multiple' => false,
'placeholder' => __('Select Event Key', 'fluent-crm')
],
'value_config' => [
'label' => __('Compare Value', 'fluent-crm'),
'type' => 'input_text',
'placeholder' => __('Event Value', 'fluent-crm'),
'data_type' => 'number',
],
'custom_operators' => [
'=' => 'equal',
'!=' => 'not equal',
'contains' => 'includes',
'not_contains' => 'does not include',
'>' => 'greater than',
'<' => 'less than'
],
],
[
'label' => __('Event Title', 'fluent-crm'),
'value' => 'event_tracking_title',
'type' => 'text',
'help' => __('Match by tracking event title', 'fluent-crm')
],
];
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,68 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
class FluentBlockPatternHandler
{
public function shouldUnregisterAllPatterns($shouldUnregister, $context = '', $data = [])
{
return true;
}
public function addCustomPatternCategories($categories)
{
$categories[] = [
'name' => 'fcrm-email',
'label' => __('FluentCRM Email', 'fluent-crm'),
'description' => __('Reusable email sections for FluentCRM editor.', 'fluent-crm')
];
return $categories;
}
public function addCustomPatterns($patterns)
{
$patterns[] = [
'name' => 'fcrm/intro-cta',
'title' => __('Intro + CTA', 'fluent-crm'),
'categories' => ['fcrm-email'],
'keywords' => ['intro', 'cta'],
'content' => '<!-- wp:group {"style":{"spacing":{"padding":{"top":"24px","right":"24px","bottom":"24px","left":"24px"}}},"layout":{"type":"constrained"}} --><div class="wp-block-group has-theme-palette-color-8-background-color has-background" style="padding-top:24px;padding-right:24px;padding-bottom:24px;padding-left:24px"><!-- wp:heading {"level":3} --><h3>' . esc_html__('Welcome to our newsletter', 'fluent-crm') . '</h3><!-- /wp:heading --><!-- wp:paragraph --><p>' . esc_html__('Share your main message here in one short paragraph.', 'fluent-crm') . '</p><!-- /wp:paragraph --><!-- wp:buttons --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="#">' . esc_html__('Get Started', 'fluent-crm') . '</a></div><!-- /wp:button --></div><!-- /wp:buttons --></div><!-- /wp:group -->'
];
$patterns[] = [
'name' => 'fcrm/two-button-row',
'title' => __('Two Button Row', 'fluent-crm'),
'categories' => ['fcrm-email'],
'keywords' => ['buttons', 'actions'],
'content' => '<!-- wp:paragraph {"align":"center"} --><p class="has-text-align-center">' . esc_html__('Choose an action:', 'fluent-crm') . '</p><!-- /wp:paragraph --><!-- wp:buttons {"layout":{"type":"flex","justifyContent":"center"}} --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="#">' . esc_html__('Primary Action', 'fluent-crm') . '</a></div><!-- /wp:button --><!-- wp:button {"className":"is-style-outline"} --><div class="wp-block-button is-style-outline"><a class="wp-block-button__link wp-element-button" href="#">' . esc_html__('Secondary Action', 'fluent-crm') . '</a></div><!-- /wp:button --></div><!-- /wp:buttons -->'
];
$patterns[] = [
'name' => 'fcrm/feature-list',
'title' => __('Feature List', 'fluent-crm'),
'categories' => ['fcrm-email'],
'keywords' => ['list', 'features'],
'content' => '<!-- wp:heading {"level":4} --><h4>' . esc_html__('Why people choose us', 'fluent-crm') . '</h4><!-- /wp:heading --><!-- wp:list --><ul class="wp-block-list"><!-- wp:list-item --><li>' . esc_html__('Fast setup', 'fluent-crm') . '</li><!-- /wp:list-item --><!-- wp:list-item --><li>' . esc_html__('Simple workflow', 'fluent-crm') . '</li><!-- /wp:list-item --><!-- wp:list-item --><li>' . esc_html__('Better conversion', 'fluent-crm') . '</li><!-- /wp:list-item --></ul><!-- /wp:list -->'
];
$patterns[] = [
'name' => 'fcrm/event-reminder',
'title' => __('Event Reminder', 'fluent-crm'),
'categories' => ['fcrm-email'],
'keywords' => ['event', 'reminder'],
'content' => '<!-- wp:group {"style":{"spacing":{"padding":{"top":"20px","right":"20px","bottom":"20px","left":"20px"}}},"layout":{"type":"constrained"}} --><div class="wp-block-group" style="padding-top:20px;padding-right:20px;padding-bottom:20px;padding-left:20px"><!-- wp:heading {"level":4} --><h4>' . esc_html__('Reminder: Upcoming Event', 'fluent-crm') . '</h4><!-- /wp:heading --><!-- wp:paragraph --><p>' . esc_html__('Date: Monday, 10:00 AM', 'fluent-crm') . '<br>' . esc_html__('Location: Online', 'fluent-crm') . '</p><!-- /wp:paragraph --><!-- wp:buttons --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="#">' . esc_html__('Add to Calendar', 'fluent-crm') . '</a></div><!-- /wp:button --></div><!-- /wp:buttons --></div><!-- /wp:group -->'
];
$patterns[] = [
'name' => 'fcrm/simple-footer-note',
'title' => __('Simple Footer Note', 'fluent-crm'),
'categories' => ['fcrm-email'],
'keywords' => ['footer', 'note'],
'content' => '<!-- wp:separator --><hr class="wp-block-separator has-alpha-channel-opacity"/><!-- /wp:separator --><!-- wp:paragraph {"align":"center","fontSize":"small"} --><p class="has-text-align-center has-small-font-size">' . esc_html__('Need help? Reply to this email and our team will assist you.', 'fluent-crm') . '</p><!-- /wp:paragraph -->'
];
return $patterns;
}
}
@@ -0,0 +1,223 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Tag;
class FluentConditionalContentBlockHandler
{
const BLOCK_NAME = 'fluent-crm/conditional-content';
const DEFAULT_CONDITION = 'show_if_tag_exist';
/**
* Legacy condition keys kept for backward compatibility.
*/
private $legacyMap = [
'show_if_logged_in' => 'show_if_user_logged_in',
'show_if_public_users' => 'show_if_user_not_logged_in',
'show_if_tag_exists' => 'show_if_tag_exist',
'show_if_tag_not_exists' => 'show_if_tag_not_exist',
];
public function register()
{
add_action('init', [$this, 'registerBlock']);
add_action('enqueue_block_editor_assets', [$this, 'enqueueEditorAssets']);
}
/**
* Register the block with a render callback.
* The JS save() still writes HTML into post_content for storage,
* but the render_callback fully controls frontend output.
*/
public function registerBlock()
{
if (!function_exists('register_block_type')) {
return;
}
register_block_type(self::BLOCK_NAME, [
'api_version' => 3,
'editor_script' => 'fluent-crm-conditional-content-block',
'attributes' => [
'condition_type' => [
'type' => 'string',
'default' => self::DEFAULT_CONDITION,
],
'tag_ids' => [
'type' => 'array',
'default' => [],
],
],
'supports' => [
'align' => ['wide', 'full'],
'anchor' => true,
'html' => false,
],
'render_callback' => [$this, 'renderBlock'],
]);
}
public function enqueueEditorAssets()
{
// The iframe editor already registers its own conditional block implementation.
if (isset($_REQUEST['fluent_crm_block_editor'])) {
return;
}
$handle = 'fluent-crm-conditional-content-block';
wp_register_script(
$handle,
fluentCrmMix('public/conditional-content-block.js'),
['wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-i18n'],
FLUENTCRM_PLUGIN_VERSION,
true
);
$tags = Tag::select(['id', 'title'])->orderBy('title', 'ASC')->get();
wp_localize_script($handle, 'fcrmConditionalContentConfig', [
'hasPro' => defined('FLUENTCAMPAIGN'),
'tags' => $tags
]);
wp_set_script_translations($handle, 'fluent-crm');
}
/**
* Render callback. Receives block attributes, the rendered inner blocks
* as $content, and the WP_Block instance.
*
* @param array $attributes
* @param string $content Inner blocks already rendered.
* @param \WP_Block $block
* @return string
*/
public function renderBlock($attributes, $content, $block)
{
if (!$this->passesCondition($attributes)) {
return '';
}
// no inner blocks placed at all — nothing to render.
// Checking $block->inner_blocks (parsed block data) is the authoritative source of truth
// and avoids inspecting the rendered HTML string, which loses semantic information.
if (count($block->inner_blocks) === 0) {
return '';
}
// inner blocks exist but all rendered to nothing — for example a Query Loop
// with no results, a dynamic block gated by its own conditions, or a plugin-restricted
// block. Avoids outputting an empty wrapper div in those cases.
// trim() on the raw HTML string is intentional: any real element (iframe, video, image,
// paragraph, etc.) produces a non-empty string. wp_strip_all_tags() is deliberately
// avoided here because it removes HTML tags and would incorrectly treat media-only
// content (iframes, videos, images) as empty.
if (trim($content) === '') {
return '';
}
$wrapperAttributes = get_block_wrapper_attributes([
'class' => 'fc-cond-section',
]);
return sprintf(
'<div %1$s><div class="fc-cond-blocks">%2$s</div></div>',
$wrapperAttributes,
$content
);
}
/**
* Decide whether the current visitor passes the condition.
*/
private function passesCondition($attrs)
{
$condition = $this->normalizeConditionType(
isset($attrs['condition_type']) ? $attrs['condition_type'] : self::DEFAULT_CONDITION
);
$tagIds = isset($attrs['tag_ids']) && is_array($attrs['tag_ids'])
? array_values(array_filter(array_map('intval', $attrs['tag_ids'])))
: [];
switch ($condition) {
case 'show_if_user_logged_in':
return is_user_logged_in();
case 'show_if_user_not_logged_in':
return !is_user_logged_in();
case 'show_if_tag_exist':
if (empty($tagIds)) {
return false;
}
return $this->contactHasAnyTag($tagIds);
case 'show_if_tag_not_exist':
if (empty($tagIds)) {
return true;
}
return !$this->contactHasAnyTag($tagIds);
}
return false;
}
/**
* Check if the current contact has any of the given tag IDs.
*/
private function contactHasAnyTag(array $tagIds)
{
$contact = $this->getCurrentContact();
if (!$contact) {
return false;
}
return $contact->hasAnyTagId($tagIds);
}
/**
* Resolve the current contact once per request.
*/
private function getCurrentContact()
{
static $resolved = null;
static $cached = false;
if ($cached) {
return $resolved;
}
$cached = true;
$contact = fluentcrm_get_current_contact();
if ($contact) {
$resolved = $contact->load('tags');
}
return $resolved;
}
/**
* Map legacy keys to current condition keys, mirroring the JS side.
*/
private function normalizeConditionType($value)
{
$value = trim((string)$value);
if (!$value) {
return self::DEFAULT_CONDITION;
}
return isset($this->legacyMap[$value]) ? $this->legacyMap[$value] : $value;
}
}
@@ -0,0 +1,266 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\Framework\Support\Arr;
use FluentForm\App\Models\Submission;
use FluentForm\App\Modules\Acl\Acl;
use FluentForm\App\Services\FormBuilder\ShortCodeParser;
/**
* FormSubmissions Class
*
* Fluent Forms Integration Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class FormSubmissions
{
public function register()
{
if (defined('FLUENTFORM')) {
add_filter('fluent_crm/form_submission_providers', [$this, 'pushDefaultFormProviders']);
add_filter('fluentcrm_get_form_submissions_fluentform', [$this, 'getFluentFormSubmissions'], 10, 2);
add_filter('fluent_crm/dynamic_contact_item_view_fluentform', [$this, 'getFluentFormSubmissionDetails'], 10, 2);
// Smartcodes
add_filter('fluentform/editor_shortcodes', function ($smartCodes) {
$smartCodes[0]['shortcodes']['{fluentcrm.CONTACT_DATA_KEY}'] = 'FluentCRM Data';
return $smartCodes;
}, 100, 1);
add_filter('fluentform/editor_shortcode_callback_group_fluentcrm', [$this, 'parseEditorCodes'], 10, 3);
}
}
public function pushDefaultFormProviders($providers)
{
if (defined('FLUENTFORM')) {
$providers['fluentform'] = [
'title' => __('Form Submissions (Fluent Forms)', 'fluent-crm'),
'name' => __('Fluent Forms', 'fluent-crm')
];
}
return $providers;
}
public function getFluentFormSubmissions($data, $subscriber)
{
if (!defined('FLUENTFORM')) {
return $data;
}
$app = fluentCrm();
$page = intval($app->request->get('page', 1));
$per_page = intval($app->request->get('per_page', 10));
$query = fluentCrmDb()->table('fluentform_submissions')
->select([
'fluentform_submissions.id',
'fluentform_submissions.form_id',
'fluentform_forms.title',
'fluentform_submissions.status',
'fluentform_submissions.created_at'
])
->join('fluentform_forms', 'fluentform_forms.id', '=', 'fluentform_submissions.form_id')
->where(function ($query) use ($subscriber) {
$query->where('fluentform_submissions.response', 'LIKE', '%' . $subscriber->email . '%');
if ($subscriber->user_id) {
$query->orWhere('fluentform_submissions.user_id', $subscriber->user_id);
}
});
$total = $query->count();
$submissions = $query
->limit($per_page)
->offset($per_page * ($page - 1))
->orderBy('fluentform_submissions.id', 'desc')
->get();
$formattedSubmissions = [];
foreach ($submissions as $submission) {
$submissionUrl = admin_url('admin.php?page=fluent_forms&route=entries&form_id=' . $submission->form_id . '#/entries/' . $submission->id);
$actionUrl = '<a target="_blank" rel="noopener" href="' . $submissionUrl . '">#' . $submission->id . '</a>';
$badgeClass = 'fcrm_badge';
if ($submission->status === 'read') {
$badgeClass .= ' fcrm_badge_success';
} else if ($submission->status === 'unread') {
$badgeClass .= ' fcrm_badge_warning';
}
$formattedSubmissions[] = [
'__id' => $submission->id,
'id' => $actionUrl,
'title' => $submission->title,
'Status' => '<span class="' . $badgeClass . '">' . $submission->status . '</span>',
'Submitted At' => '<a target="_blank" rel="noopener" href="' . $submissionUrl . '">' . $submission->created_at . '</a>',
'action' => 'view'
];
}
return [
'total' => $total,
'data' => $formattedSubmissions,
'columns_config' => [
'id' => [
'label' => __('ID', 'fluent-crm'),
'width' => '100px'
],
'title' => [
'label' => __('Form Title', 'fluent-crm')
],
'Status' => [
'label' => __('Status', 'fluent-crm'),
'width' => '100px'
],
'Submitted At' => [
'label' => __('Submitted At', 'fluent-crm'),
'width' => '180px'
],
'action' => [
'quick_action' => true,
'label' => __('Action', 'fluent-crm'),
'width' => '100px'
]
]
];
}
public function getFluentFormSubmissionDetails($dataView, $params)
{
$submissionId = (int)Arr::get($params, '__id');
if (!$submissionId) {
$dataView['content_html'] = '<div class="fc-crm-no-data-view"><p>' . __('No submission found', 'fluent-crm') . '</p></div>';
return $dataView;
}
$submission = Submission::with(['form'])->find($submissionId);
if (!$submission || !$submission->form) {
$dataView['content_html'] = '<div class="fc-crm-no-data-view"><p>' . __('No submission found', 'fluent-crm') . '</p></div>';
return $dataView;
}
$form = $submission->form;
if (!Acl::hasPermission('fluentform_entries_viewer', $form->id)) {
$dataView['title'] = __('Permission Denied', 'fluent-crm');
$dataView['content_html'] = '<div class="fc-crm-no-data-view"><p>' . __('You do not have permission to view this submission.', 'fluent-crm') . '</p></div>';
return $dataView;
}
$submittedData = json_decode($submission->response, true);
$html = '<b>Submission Details</b><br/><br/><div>{all_data}</div>';
if ($submission->payment_status) {
$html .= '<h2>Payment Details</h2>';
$html .= '{payment.receipt}';
}
$html .= '<h4>Additional Details:</h4>';
$html .= '<ul>';
$html .= '<li><strong>Source URL:</strong> {submission.source_url}</li>';
$html .= '<li><strong>Serial #:</strong> {submission.serial_number}</li>';
$html .= '<li><strong>Browser:</strong> {submission.browser} / {submission.device}</li>';
$html .= '<li><strong>Date:</strong> {submission.created_at}</li>';
$html .= '</ul>';
$body = ShortCodeParser::parse(
$html,
$submission->id,
$submittedData,
$form,
false,
true
);
$dataView['title'] = sprintf(__('Submission #%d - %s', 'fluent-crm'), $submission->id, $form->title);
$dataView['content_html'] = '<style>.fc-crm-form-submission-view table { width: 100% !important; }</style><div class="fc-crm-form-submission-view">' . $body . '</div>';
$dataView['footer_content'] = '<a class="el-button fcrm_primary_btn" target="_blank" rel="noopener" href="' . admin_url('admin.php?page=fluent_forms&route=entries&form_id=' . $form->id . '#/entries/' . $submission->id) . '">View in FluentForms</a>';
return $dataView;
}
public function parseEditorCodes($code, $form, $keys)
{
$contact = FluentCrmApi('contacts')->getCurrentContact(true, true);
$providedKey = $keys[0];
// maybe has fallback value
$dynamicKey = explode('|', $providedKey);
$fallBack = '';
if (count($dynamicKey) > 1) {
$fallBack = $dynamicKey[1];
}
$ref = $dynamicKey[0];
if (!$contact) {
return $fallBack;
}
$validMainProps = (new Subscriber)->getFillable();
$validMainProps[] = 'id';
if (in_array($ref, $validMainProps)) {
if ($contact->{$ref}) {
return $contact->{$ref};
}
return $fallBack;
}
// Maybe it's a custom field
$customData = $contact->custom_fields();
if ($customData && !empty($customData[$ref])) {
$value = $customData[$ref];
if (is_array($value)) {
return implode(',', $value);
}
return $customData[$ref];
}
$listMaps = [
'list_ids' => 'id',
'list_titles' => 'title',
'list_slugs' => 'slug'
];
$tagMaps = [
'tag_ids' => 'id',
'tag_titles' => 'title',
'tag_slugs' => 'slug'
];
if (isset($listMaps[$ref])) {
$listProps = [];
foreach ($contact->lists as $list) {
$listProps[] = $list->{$listMaps[$ref]};
}
if ($listProps) {
return trim(implode(', ', $listProps));
}
} else if (isset($tagMaps[$ref])) {
$tagProps = [];
foreach ($contact->tags as $tag) {
$tagProps[] = $tag->{$tagMaps[$ref]};
}
if ($tagProps) {
return trim(implode(', ', $tagProps));
}
}
return $fallBack;
}
}
@@ -0,0 +1,530 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Campaign;
use FluentCrm\App\Models\Funnel;
use FluentCrm\App\Models\FunnelCampaign;
use FluentCrm\App\Models\FunnelSequence;
use FluentCrm\App\Models\FunnelSubscriber;
use FluentCrm\App\Services\Funnel\Actions\ApplyCompanyAction;
use FluentCrm\App\Services\Funnel\Actions\ApplyListAction;
use FluentCrm\App\Services\Funnel\Actions\ApplyTagAction;
use FluentCrm\App\Services\Funnel\Actions\DetachCompanyAction;
use FluentCrm\App\Services\Funnel\Actions\DetachListAction;
use FluentCrm\App\Services\Funnel\Actions\DetachTagAction;
use FluentCrm\App\Services\Funnel\Actions\SendEmailAction;
use FluentCrm\App\Services\Funnel\Actions\WaitTimeAction;
use FluentCrm\App\Services\Funnel\Benchmarks\ListAppliedBenchmark;
use FluentCrm\App\Services\Funnel\Benchmarks\RemoveFromListBenchmark;
use FluentCrm\App\Services\Funnel\Benchmarks\RemoveFromTagBenchmark;
use FluentCrm\App\Services\Funnel\Benchmarks\TagAppliedBenchmark;
use FluentCrm\App\Services\Funnel\FunnelHelper;
use FluentCrm\App\Services\Funnel\FunnelProcessor;
use FluentCrm\App\Services\Funnel\SequencePoints;
use FluentCrm\App\Services\Funnel\Triggers\FluentFormSubmissionTrigger;
use FluentCrm\App\Services\Funnel\Triggers\FluentFormSubscriptionCancelledTrigger;
use FluentCrm\App\Services\Funnel\Triggers\FluentFormSubscriptionPaymentReceivedTrigger;
use FluentCrm\App\Services\Funnel\Triggers\UserRegistrationTrigger;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Services\PermissionManager;
use FluentCrm\App\Services\Sanitize;
use FluentCrm\Framework\Support\Arr;
/**
* FunnelHandler Class - Automation Funnel Handler
*
* Automation Funnel Handler Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class FunnelHandler
{
private $settingsKey = 'fluentcrm_funnel_settings';
private $lockKey = '_fc_funnel_processor_lock';
private $lockTimeout = 90;
protected $funnelFired = false;
private $registeredFunnelTriggers = [];
private $registeredTriggerFallbacks = [];
private $funnelItemsRegistered = false;
public function register()
{
/*
* Core funnel items must register before the early active-trigger pass
* so their fluentcrm_funnel_arg_num_* filters are available at init
* priority 2. This lets core events fired by other init priority 10
* callbacks, such as LifterLMS user registration, enter funnels.
*
* Pro integrations can register trigger arg-count filters before init priority 2.
* Register those ready triggers early so events fired during init priority 10,
* such as EDD manual order status updates, are not missed.
*
* The fallback pass at priority 20 preserves the existing behavior for triggers
* whose arg-count filters are not available during the early pass.
*/
add_action('init', [$this, 'registerFunnelItems'], 1);
add_action('init', [$this, 'registerEarlyActiveTriggers'], 2);
add_action('init', [$this, 'handle'], 10);
add_action('init', [$this, 'registerActiveTriggers'], 20);
}
/**
* Register core funnel actions, benchmarks, triggers, and free Pro placeholders once.
*
* This runs before registerEarlyActiveTriggers() so core trigger arg-count filters
* are present when active funnel listeners are attached before other init@10 callbacks.
*
* @return void
*/
public function registerFunnelItems()
{
if ($this->funnelItemsRegistered) {
return;
}
$this->funnelItemsRegistered = true;
$this->initBlockActions();
$this->initBenchMarkBlocks();
$this->initTriggers();
if (!defined('FLUENTCAMPAIGN_DIR_FILE')) {
new \FluentCrm\App\Services\Funnel\ProFunnelItems();
}
}
public function registerEarlyActiveTriggers()
{
$this->registerActiveTriggers(true);
}
public function registerActiveTriggers($onlyRegisteredArgFilters = false)
{
$triggers = get_option($this->settingsKey, []);
$triggers = array_unique($triggers);
if (!$triggers) {
return;
}
foreach ($triggers as $triggerName) {
if ($this->shouldSkipEddTriggerRegistration($triggerName)) {
continue;
}
if (isset($this->registeredFunnelTriggers[$triggerName])) {
continue;
}
/*
* Early registration is only safe when the trigger's arg-count filter is
* already registered. Otherwise the priority 20 pass will register it
* after handle() has initialized the core trigger filters.
*/
$argNumFilterName = 'fluentcrm_funnel_arg_num_' . $triggerName;
if ($onlyRegisteredArgFilters && !has_filter($argNumFilterName)) {
continue;
}
$argNum = apply_filters($argNumFilterName, 1);
add_action($triggerName, function () use ($triggerName, $argNum) {
$this->mapTriggers($triggerName, func_get_args(), $argNum);
}, 10, $argNum);
$this->registeredFunnelTriggers[$triggerName] = true;
}
/*
* EDD also exposes edd_complete_purchase after a successful payment.
* Keep the existing fallback, but attach it only once and only after the
* main EDD payment-status trigger has been registered.
*/
if (
isset($this->registeredFunnelTriggers['edd_update_payment_status']) &&
empty($this->registeredTriggerFallbacks['edd_complete_purchase'])
) {
add_action('edd_complete_purchase', function ($paymentId) {
$this->mapTriggers('edd_update_payment_status', [$paymentId, 'complete', 'pending'], 3);
});
$this->registeredTriggerFallbacks['edd_complete_purchase'] = true;
}
}
/**
* Skip stored EDD automation hooks when the active EDD install is unsupported.
*
* Existing EDD funnel data should remain stored, but EDD runtime dispatch must
* not be registered unless the site is running EDD 3 or newer.
*
* @param string $triggerName
* @return bool
*/
private function shouldSkipEddTriggerRegistration($triggerName)
{
if (Helper::isEdd3()) {
return false;
}
return in_array($triggerName, [
'edd_update_payment_status',
'edd_sl_post_set_status',
'edd_recurring_add_subscription_payment',
'edd_subscription_status_change',
'edd_fc_order_refunded_simulation'
], true);
}
public function handle()
{
$this->registerFunnelItems();
add_action('fluent_crm_process_automation', function () {
if ($this->funnelFired) {
return;
}
$this->funnelFired = true;
if (!$this->acquireFunnelProcessorLock()) {
return;
}
try {
(new FunnelProcessor())->followUpSequenceActions();
} finally {
$this->releaseFunnelProcessorLock();
}
});
}
private function mapTriggers($triggerName, $originalArgs, $argNumber)
{
$triggerNameBase = $triggerName;
$funnels = Funnel::where('status', 'published')
->where('trigger_name', $triggerNameBase)
->get();
foreach ($funnels as $funnel) {
ob_start();
/**
* Automation Funnel Start Trigger from specific action
* @param Funnel $funnel
* @param array $originalArgs Original Arguments from the trigger
*/
do_action("fluentcrm_funnel_start_{$triggerName}", $funnel, $originalArgs);
$maybeErrors = ob_get_clean();
}
$benchMarks = FunnelSequence::where('type', 'benchmark')
->where('action_name', $triggerNameBase)
->whereHas('funnel', function ($q) {
return $q->where('status', 'published');
})
->orderBy('id', 'ASC')
->get();
foreach ($benchMarks as $benchMark) {
ob_start();
/**
* Automation Funnel's Benchmark Start Trigger from specific action trigger
* @param Funnel $funnel
* @param array $originalArgs Original Arguments from the trigger
*/
do_action("fluentcrm_funnel_benchmark_start_{$triggerName}", $benchMark, $originalArgs);
$maybeErrors = ob_get_clean();
}
}
/**
* Claim the funnel-processor lock so two runners can't process the same
* queue concurrently. Backed by an atomic conditional UPDATE on wp_options
* (Helper::acquireDbLock) on every environment — not wp_cache_add(), which
* is not atomic under all object-cache drop-ins (e.g. LiteSpeed) and would
* let concurrent runners all acquire the lock. See Helper::acquireDbLock().
*/
private function acquireFunnelProcessorLock()
{
return Helper::acquireDbLock($this->lockKey, $this->lockTimeout);
}
private function releaseFunnelProcessorLock()
{
Helper::releaseDbLock($this->lockKey);
}
public function resetFunnelIndexes()
{
$funnels = Funnel::select('trigger_name')
->where('status', 'published')
->groupBy('trigger_name')
->get();
$funnelArrays = [];
foreach ($funnels as $funnel) {
$funnelArrays[] = $funnel->trigger_name;
}
$sequenceMetrics = FunnelSequence::select('action_name')
->where('status', 'published')
->where('type', 'benchmark')
->whereHas('funnel', function ($q) {
return $q->where('status', 'published');
})
->groupBy('action_name')
->get();
foreach ($sequenceMetrics as $sequenceMetric) {
$funnelArrays[] = $sequenceMetric->action_name;
}
update_option($this->settingsKey, array_unique($funnelArrays), 'yes');
}
private function initTriggers()
{
new UserRegistrationTrigger();
new FluentFormSubmissionTrigger();
if (defined('FLUENTFORMPRO')) {
new FluentFormSubscriptionPaymentReceivedTrigger();
new FluentFormSubscriptionCancelledTrigger();
}
}
private function initBlockActions()
{
if (Helper::isCompanyEnabled()) {
new ApplyCompanyAction();
new DetachCompanyAction();
}
new ApplyListAction();
new ApplyTagAction();
new DetachListAction();
new DetachTagAction();
new WaitTimeAction();
new SendEmailAction();
}
private function initBenchMarkBlocks()
{
new ListAppliedBenchmark();
new TagAppliedBenchmark();
new RemoveFromListBenchmark();
new RemoveFromTagBenchmark();
}
public function resumeSubscriberFunnels($subscriber, $oldStatus)
{
$funnelSubscribers = FunnelSubscriber::where('status', 'pending')
->with(['funnel'])
->where('subscriber_id', $subscriber->id)
->whereHas('funnel', function ($query) {
return $query->where('status', 'published');
})
->get();
$funnelProcessorClass = new FunnelProcessor();
foreach ($funnelSubscribers as $funnelSubscriber) {
$funnel = $funnelSubscriber->funnel;
if (!$funnel || $funnel->status != 'published') {
continue;
}
$funnelProcessorClass->resumeFunnelSubscriber($funnel, $subscriber, $funnelSubscriber);
}
}
public function saveSequences()
{
check_ajax_referer('fluentcrm_ajax_nonce', '_nonce');
$hasPermission = PermissionManager::currentUserCan('fcrm_write_funnels');
if (!$hasPermission) {
wp_send_json([
'message' => __('Sorry, You do not have permission to do this action', 'fluent-crm')
], 422);
}
$request = FluentCrm('request');
$data = $request->all();
$data['sequences'] = wp_unslash(Arr::get($data, 'sequences'));
$funnel = FunnelHelper::saveFunnelSequence($data['funnel_id'], $data);
wp_send_json([
'sequences' => FunnelHelper::getFunnelSequences($funnel, true),
'message' => __('Sequence successfully updated', 'fluent-crm')
]);
}
public function exportFunnel()
{
check_ajax_referer('fluentcrm_ajax_nonce', '_nonce');
$permission = 'manage_options';
if (!current_user_can($permission)) {
die('You do not have permission');
}
$funnelId = intval($_REQUEST['funnel_id']);
$funnel = Funnel::findOrFail($funnelId);
/**
* Determine the funnel editor details based on the funnel's trigger name.
*
* The dynamic portion of the hook name, `$funnel->trigger_name`, refers to the trigger name of the funnel.
*
* @param object $funnel The funnel object containing the editor details.
* @since 2.0.0
*
*/
$funnel = apply_filters('fluentcrm_funnel_editor_details_' . $funnel->trigger_name, $funnel);
$funnel->labels = $funnel->getFormattedLabels();
$funnel->sequences = FunnelHelper::getFunnelSequences($funnel, true);
$funnel->site_hash = md5(site_url());
$funnel->export_date = gmdate('Y-m-d H:i:s');
header('Content-disposition: attachment; filename=' . sanitize_title($funnel->title, 'funnel', 'display') . '-' . $funnelId . '.json');
header('Content-type: application/json');
echo json_encode($funnel); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
exit();
}
public function saveEmailAction()
{
check_ajax_referer('fluentcrm_ajax_nonce', '_nonce');
$hasPermission = PermissionManager::currentUserCan('fcrm_write_funnels');
if (!$hasPermission) {
wp_send_json([
'message' => __('Sorry, You do not have permission to do this action', 'fluent-crm')
], 422);
}
$request = FluentCrm('request');
$funnelId = $request->get('funnel_id');
$funnel = Funnel::findOrFail($funnelId);
$settings = Helper::parseArrayOrJson($request->get('action_data'));
$settings['action_name'] = 'send_custom_email';
$funnelCampaign = Arr::get($settings, 'campaign', []);
$funnelCampaignId = Arr::get($funnelCampaign, 'id');
$data = Arr::only($funnelCampaign, array_keys(FunnelCampaign::getMock()));
$data['settings']['mailer_settings'] = Arr::get($settings, 'mailer_settings', []);
$type = 'created';
if ($funnelCampaignId && $funnel->id == Arr::get($data, 'parent_id')) {
// We have this campaign
$data['settings'] = \maybe_serialize($data['settings']);
$data['type'] = 'funnel_email_campaign';
$data['title'] = $funnel->title . ' (' . $funnel->id . ')';
FunnelCampaign::where('id', $funnelCampaignId)->update($data);
$type = 'updated';
} else {
$data['parent_id'] = $funnel->id;
$data['type'] = 'funnel_email_campaign';
$data['title'] = $funnel->title . ' (' . $funnel->id . ')';
$campaign = FunnelCampaign::create($data);
$funnelCampaignId = $campaign->id;
}
if (Arr::get($funnelCampaign, 'design_template') == 'visual_builder') {
$design = Arr::get($funnelCampaign, '_visual_builder_design', []);
fluentcrm_update_campaign_meta($funnelCampaignId, '_visual_builder_design', $design);
} else {
fluentcrm_delete_campaign_meta($funnelCampaignId, '_visual_builder_design');
}
$refCampaign = FunnelCampaign::find($funnelCampaignId);
wp_send_json([
'type' => $type,
'reference_campaign' => $funnelCampaignId,
'campaign' => Arr::only($refCampaign->toArray(), array_keys(FunnelCampaign::getMock()))
], 200);
}
public function saveCampaignEmail()
{
check_ajax_referer('fluentcrm_ajax_nonce', '_nonce');
$hasPermission = PermissionManager::currentUserCan('fcrm_manage_emails');
if (!$hasPermission) {
wp_send_json([
'message' => __('Sorry, You do not have permission to do this action', 'fluent-crm')
], 422);
}
$request = FluentCrm('request');
$id = $request->get('campaign_id');
$data = Helper::parseArrayOrJson($request->get('action_data'));
if (empty($data)) {
wp_send_json([
'message' => __('Invalid Data', 'fluent-crm')
], 422);
}
$updateData = Arr::only($data, [
'title',
'slug',
'template_id',
'email_subject',
'email_pre_header',
'email_body',
'utm_status',
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content',
'scheduled_at',
'design_template'
]);
if (!empty($data['settings'])) {
$updateData['settings'] = $data['settings'];
}
$updateData = Sanitize::campaign($updateData);
$campaign = Campaign::findOrFail($id);
$campaign->fill($updateData)->save();
$nextStep = Arr::get($data, 'next_step');
if ($nextStep) {
do_action('fluent_crm/update_campaign_compose', $data, $campaign);
fluentcrm_update_campaign_meta($id, '_next_config_step', $nextStep);
}
wp_send_json([
'campaign' => $campaign
], 200);
}
}
@@ -0,0 +1,40 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Services\ExternalIntegrations\BricksBuilderIntegration;
/**
* Integrations Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class Integrations
{
public function register()
{
// Full-featured integrations with functionality
if (defined('FLUENTFORM')) {
(new \FluentCrm\App\Services\ExternalIntegrations\FluentForm\FluentFormInit())->init();
}
if(defined('FLUENTCART_VERSION')) {
(new \FluentCrm\App\Services\ExternalIntegrations\FluentCart\FluentCart())->init();
}
/*
* Oxygen Editor Integration
*/
if (defined('CT_VERSION')) {
require_once FLUENTCRM_PLUGIN_PATH . 'app/Services/ExternalIntegrations/Oxygen/oxy_init.php';
}
(new EventTrackingHandler())->register();
if(defined('BRICKS_VERSION')) {
(new BricksBuilderIntegration())->register();
}
}
}
@@ -0,0 +1,821 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Support\Arr;
use FluentCrm\App\Models\CustomContactField as CustomFields;
/**
* Integrations Class
*
* @package FluentCrm\App\Hooks
*
* @version 2.5.94
*/
class PrefFormHandler
{
public function handleShortCode($atts, $noContactContent = '')
{
if (isset($_REQUEST['_fc_secure_hash'])) {
$hash = sanitize_text_field($_REQUEST['_fc_secure_hash']);
if ($hash) {
$_COOKIE['fc_hash_secure'] = $hash;
}
}
$settings = Helper::getGlobalEmailSettings();
if (Arr::get($settings, 'pref_form') != 'yes' || empty(Arr::get($settings, 'pref_general'))) {
return '';
}
do_action('fluent_crm/rendering_pref_form_shortcode');
$subscriber = FluentCrmApi('contacts')->getCurrentContact(true, true);
if (!$subscriber) {
return $noContactContent;
}
/**
* Determine the preference form labels in FluentCRM.
*
* This filter allows modification of the labels used in the preference form.
*
* @since 2.5.95
*
* @param array {
* An associative array of labels.
*
* @type string $first_name Label for the first name field.
* @type string $last_name Label for the last name field.
* @type string $prefix Label for the title field.
* @type string $email Label for the email field.
* @type string $phone Label for the phone/mobile field.
* @type string $dob Label for the date of birth field.
* @type string $address_line_1 Label for the address line 1 field.
* @type string $address_line_2 Label for the address line 2 field.
* @type string $city Label for the city field.
* @type string $state Label for the state field.
* @type string $postal_code Label for the ZIP code field.
* @type string $country Label for the country field.
* @type string $update Label for the update info button.
* @type string $address_heading Label for the address information section.
* @type string $list_label Label for the mailing list groups section.
* }
*/
$labels = apply_filters('fluent_crm/pref_labels', [
'first_name' => __('First Name', 'fluent-crm'),
'last_name' => __('Last Name', 'fluent-crm'),
'prefix' => __('Title', 'fluent-crm'),
'email' => __('Email', 'fluent-crm'),
'phone' => __('Phone/Mobile', 'fluent-crm'),
'dob' => __('Date of Birth', 'fluent-crm'),
'address_line_1' => __('Address Line 1', 'fluent-crm'),
'address_line_2' => __('Address Line 2', 'fluent-crm'),
'city' => __('City', 'fluent-crm'),
'state' => __('State', 'fluent-crm'),
'postal_code' => __('ZIP Code', 'fluent-crm'),
'country' => __('Country', 'fluent-crm'),
'update' => __('Update info', 'fluent-crm'),
'address_heading' => __('Address Information', 'fluent-crm'),
'list_label' => __('Mailing List Groups', 'fluent-crm'),
'custom_fields' => __('Custom Fields', 'fluent-crm')
]);
$formFields = $this->getFormFields($settings, $subscriber, $labels, false);
$listOptions = [];
$lists = Helper::getPublicLists();
if ($lists) {
foreach ($lists as $list) {
$listOptions[strval($list->id)] = $list->title;
}
$formattedLists = [];
foreach ($subscriber->lists as $list) {
$formattedLists[] = $list->id;
}
$formFields['lists'] = [
'type' => 'checkboxes',
'name' => 'lists',
'container_class' => 'fc_inline_checkboxes',
'options' => $listOptions,
'value' => $formattedLists,
'id' => 'mailing_lists',
'label' => Arr::get($labels, 'list_label', 'Mailing List Groups'),
];
}
/**
* Determine the preference form fields against a subscriber or contact data in FluentCRM.
*
* This filter allows modification of the preference form fields before they are displayed.
*
* @since 2.5.95
*
* @param array $formFields The current form fields.
* @param object $subscriber The subscriber object.
* @return array Modified form fields.
*/
$formFields = apply_filters('fluent_crm/pref_form_fields', $formFields, $subscriber);
$formFields[] = [
'type' => 'hidden',
'atts' => [
'name' => 'action',
'value' => 'fluent_crm_account_form'
]
];
if (isset($_REQUEST['_fc_secure_hash'])) {
$hash = sanitize_text_field($_REQUEST['_fc_secure_hash']);
if($hash) {
$formFields[] = [
'type' => 'hidden',
'atts' => [
'name' => '_fc_hash_secure',
'value' => $hash
]
];
}
}
wp_enqueue_style(
'fluentcrm_public_pref',
fluentCrmMix('public/public_pref.css'),
[],
FLUENTCRM_PLUGIN_VERSION
);
wp_enqueue_script('fluentcrm_public_pref', fluentCrmMix('public/public_pref.js'), ['jquery'], FLUENTCRM_PLUGIN_VERSION, true);
wp_localize_script('fluentcrm_public_pref', 'fluentcrm_sub_pref', [
'ajaxurl' => admin_url('admin-ajax.php')
]);
return (string) fluentCrm('view')->make('external.pref_form', [
'fields' => $formFields,
'submitBtn' => [
'container_class' => 'fc_pref_submit',
'btn_text' => __('Update info', 'fluent-crm'),
'atts' => [
'type' => 'submit',
'id' => 'fluentcrm_preferences_submit',
'class' => 'btn fc_pref_submit'
]
],
'subscriber' => $subscriber
]);
}
public function handleDynamicContentShortCode($atts, $text = '')
{
if(!$text) {
return '';
}
$defaults = [
'hide_for_guest' => 'no'
];
$atts = shortcode_atts($defaults, $atts, 'fluentcrm_content');
$subscriber = FluentCrmApi('contacts')->getCurrentContact(true, true);
if(!$subscriber) {
if($atts['hide_for_guest'] == 'yes') {
return '';
}
return preg_replace_callback('/({{|##)+(.*?)(}}|##)/', function ($matches) {
if(isset($matches[2])) {
$token = $matches[2];
$tokens = explode('|', $token);
if(isset($tokens[1])) {
return $tokens[1];
}
}
return '';
}, $text);
}
return \FluentCrm\App\Services\Libs\Parser\Parser::parse($text, $subscriber);
}
public function handleAjax()
{
if (!isset($_POST['_fc_nonce']) || !wp_verify_nonce($_POST['_fc_nonce'], 'fluent_crm_account_form_fields')) {
wp_send_json_error([
'message' => __('Sorry, your nonce did not verify.', 'fluent-crm')
], 422);
}
$settings = Helper::getGlobalEmailSettings();
if (Arr::get($settings, 'pref_form') != 'yes' || empty(Arr::get($settings, 'pref_general'))) {
wp_send_json_error([
'message' => __('Sorry! You cannot update your profile.', 'fluent-crm')
], 422);
}
if (isset($_REQUEST['_fc_hash_secure']) && !is_user_logged_in()) {
$hash = sanitize_text_field($_REQUEST['_fc_hash_secure']);
if ($hash) {
$_COOKIE['fc_hash_secure'] = $hash;
}
}
$subscriber = FluentCrmApi('contacts')->getCurrentContact(false, true);
if (!$subscriber) {
wp_send_json_error([
'message' => __('Sorry! You cannot update your profile.', 'fluent-crm')
], 422);
}
$validInputs = $this->getFormFields($settings, $subscriber, [], true);
$validKeys = array_keys($validInputs);
$validData = Arr::only($_REQUEST, $validKeys);
if (empty($validData['email'])) {
$validData['email'] = $subscriber->email;
}
$errors = [];
foreach ($validInputs as $key => $input) {
if (Arr::get($input, 'required') && empty($validData[$key])) {
$errors[] = $key . ' is required';
}
// Handle array values for multi-select and checkboxes
if (isset($validData[$key]) && is_array($validData[$key])) {
$validData[$key] = array_map('sanitize_text_field', $validData[$key]);
} else {
$validData[$key] = sanitize_text_field(Arr::get($validData, $key, ''));
}
}
if (!empty($validData['date_of_birth']) && !$this->isValidDate($validData['date_of_birth'])) {
$errors[] = 'date_of_birth';
}
if ($errors) {
wp_send_json_error([
'message' => __('Please fill up all required fields', 'fluent-crm'),
'errors' => $errors,
'inputs' => $validData
], 422);
}
// Handle custom fields
$enabledCustomFieldSlugs = Arr::get($settings, 'pref_custom', []);
$allCustomFields = (new CustomFields)->getGlobalFields()['fields'];
if (!empty($allCustomFields) && !empty($enabledCustomFieldSlugs)) {
foreach ($allCustomFields as $field) {
$fieldKey = $field['slug'];
// Only process fields that are enabled in pref_custom
if (!in_array($fieldKey, $enabledCustomFieldSlugs)) {
continue;
}
if (isset($validData[$fieldKey])) {
$value = $validData[$fieldKey];
// Handle different field types
switch ($field['type']) {
case 'checkbox':
if (is_array($value)) {
$value = array_map('sanitize_text_field', $value);
}
break;
case 'select-multi':
if (is_array($value)) {
$value = array_map('sanitize_text_field', $value);
} else {
$value = [];
}
break;
case 'number':
$value = floatval($value);
break;
case 'textarea':
$value = isset($_POST[$fieldKey]) ? sanitize_textarea_field($_POST[$fieldKey]) : '';
break;
case 'date':
$value = sanitize_text_field($value);
break;
default:
$value = sanitize_text_field($value);
}
// Update the meta with proper type
$subscriber->updateMeta($field['slug'], $value, 'custom_field');
unset($validData[$fieldKey]); // Remove from main data
}
}
}
$subscriber->fill($validData);
$updateData = $subscriber->getDirty();
if($updateData) {
$subscriber->save();
}
if (isset($_REQUEST['lists'])) {
$publicLists = Helper::getPublicLists();
$publicListIds = [];
foreach ($publicLists as $publicList) {
$publicListIds[] = $publicList->id;
}
$selectedListIds = map_deep($_REQUEST['lists'], 'intval');
$attachLists = [];
$detachLists = [];
foreach ($subscriber->lists as $list) {
if (!in_array($list->id, $publicListIds)) {
continue;
}
if (!in_array($list->id, $selectedListIds)) {
$detachLists[] = $list->id;
}
}
foreach ($selectedListIds as $selectedListId) {
if (in_array($selectedListId, $publicListIds)) {
$attachLists[] = $selectedListId;
}
}
if ($attachLists) {
$subscriber->attachLists($attachLists);
}
if ($detachLists) {
$subscriber->detachLists($detachLists);
}
} else {
$listIds = $subscriber->lists()->get()->pluck('id')->toArray();
$subscriber->detachLists($listIds);
}
do_action('fluent_crm/pref_form_self_contact_updated', $subscriber, $_REQUEST);
if ($updateData) {
do_action('fluentcrm_contact_updated', $subscriber, $updateData);
do_action('fluent_crm/contact_updated', $subscriber, $updateData);
}
wp_send_json_success([
'message' => __('Your information has been updated', 'fluent-crm'),
'data' => $validData
], 200);
}
private function getFormFields($settings, $subscriber, $labels, $inputOnly = false)
{
$generalFields = Arr::get($settings, 'pref_general');
$customFields = Arr::get($settings, 'pref_custom');
$formFields = [];
if (array_intersect($generalFields, ['first_name', 'last_name'])) {
$nameFields = [];
if (in_array('prefix', $generalFields)) {
$nameFields['prefix'] = [
'type' => 'select',
'name' => 'prefix',
'container_class' => 'fc_name_prefix',
'id' => 'fc_name_prefix',
'label' => Arr::get($labels, 'prefix', 'Prefix'),
'placeholder' => '--',
'options' => Helper::getContactPrefixes(true),
'value' => $subscriber->prefix
];
}
if (in_array('first_name', $generalFields)) {
$nameFields['first_name'] = [
'type' => 'input',
'name' => 'first_name',
'id' => 'fc_first_name',
'atts' => [
'type' => 'text',
'placeholder' => __('First Name', 'fluent-crm')
],
'required' => true,
'label' => Arr::get($labels, 'first_name', 'First Name'),
'value' => $subscriber->first_name
];
}
if (in_array('last_name', $generalFields)) {
$nameFields['last_name'] = [
'type' => 'input',
'name' => 'last_name',
'id' => 'fc_last_name',
'atts' => [
'type' => 'text',
'placeholder' => __('Last Name', 'fluent-crm')
],
'required' => true,
'label' => Arr::get($labels, 'last_name', 'Last Name'),
'value' => $subscriber->last_name
];
}
$formFields['name'] = [
'type' => 'container',
'container_class' => 'fc_names fc_' . count($nameFields) . '_col',
'fields' => $nameFields
];
}
$formFields[] = [
'type' => 'raw_html',
'html' => '<div class="fc_2_col fc_email_phone_date">'
];
$formFields['email'] = [
'type' => 'input',
'name' => 'email',
'id' => 'fc_email',
'atts' => [
'type' => 'email',
'placeholder' => __('Email', 'fluent-crm'),
'disabled' => true
],
'required' => true,
'label' => Arr::get($labels, 'email', 'Email'),
'value' => $subscriber->email
];
if (in_array('phone', $generalFields)) {
$formFields['phone'] = [
'type' => 'input',
'name' => 'phone',
'id' => 'fc_phone',
'atts' => [
'type' => 'tel',
'placeholder' => __('Phone', 'fluent-crm')
],
'required' => false,
'label' => Arr::get($labels, 'phone', 'Phone/Mobile'),
'value' => $subscriber->phone
];
}
$formFields[] = [
'type' => 'raw_html',
'html' => '</div>'
];
if (in_array('date_of_birth', $generalFields)) {
$formFields['date_of_birth'] = [
'type' => 'date_dropdowns',
'name' => 'date_of_birth',
'id' => 'fc_date_of_birth',
'required' => false,
'label' => Arr::get($labels, 'dob', 'Date of Birth'),
'value' => $subscriber->date_of_birth
];
}
if (in_array('address_fields', $generalFields)) {
$formFields[] = [
'type' => 'raw_html',
'html' => '<h4 class="fc_address_info_heading">' . Arr::get($labels, 'address_heading', 'Address Information') . '</h4>'
];
/**
* Filter to modify the list of country names for the Preference Form Field in FluentCRM.
*
* This filter allows you to modify the list of country names used in FluentCRM.
*
* @since 2.7.0
*
* @param array An array of country names.
*/
$countryNames = apply_filters('fluent_crm/countries', []);
$formattedCountries = [];
foreach ($countryNames as $country) {
$formattedCountries[$country['code']] = $country['title'];
}
$formFields['address'] = [
'type' => 'container',
'container_class' => 'fc_addresses fc_2_col',
'fields' => [
'address_line_1' => [
'type' => 'input',
'name' => 'address_line_1',
'id' => 'fc_address_line_1',
'atts' => [
'type' => 'text',
'placeholder' => __('Address Line 1', 'fluent-crm')
],
'label' => Arr::get($labels, 'address_line_1', 'Address Line 1'),
'value' => $subscriber->address_line_1
],
'address_line_2' => [
'type' => 'input',
'name' => 'address_line_2',
'id' => 'fc_address_line_2',
'atts' => [
'type' => 'text',
'placeholder' => __('Address Line 2', 'fluent-crm')
],
'label' => Arr::get($labels, 'address_line_2', 'Address Line 2'),
'value' => $subscriber->address_line_2
],
'city' => [
'type' => 'input',
'name' => 'city',
'id' => 'fc_address_city',
'atts' => [
'type' => 'text',
'placeholder' => __('City', 'fluent-crm')
],
'label' => Arr::get($labels, 'city', 'City'),
'value' => $subscriber->city
],
'state' => [
'type' => 'input',
'name' => 'state',
'id' => 'fc_address_state',
'atts' => [
'type' => 'text',
'placeholder' => __('State', 'fluent-crm')
],
'label' => Arr::get($labels, 'state', 'State'),
'value' => $subscriber->state
],
'postal_code' => [
'type' => 'input',
'name' => 'postal_code',
'id' => 'fc_address_postal_code',
'atts' => [
'type' => 'text',
'placeholder' => __('Zip Code', 'fluent-crm')
],
'label' => Arr::get($labels, 'postal_code', 'Zip Code'),
'value' => $subscriber->postal_code
],
'country' => [
'type' => 'select',
'name' => 'country',
'id' => 'fc_address_country',
'placeholder' => __('Select Country', 'fluent-crm'),
'label' => Arr::get($labels, 'country', 'Country'),
'value' => $subscriber->country,
'options' => $formattedCountries
],
]
];
}
// Add custom fields section
if (!empty($customFields)) {
$allCustomFields = (new CustomFields)->getGlobalFields()['fields'];
$enabledCustomFields = [];
// Filter custom fields based on pref_custom settings
foreach ($allCustomFields as $field) {
if (in_array($field['slug'], $customFields)) {
$enabledCustomFields[] = $field;
}
}
if (!empty($enabledCustomFields)) {
$formFields[] = [
'type' => 'raw_html',
'html' => '<p class="fc_custom_fields_heading"></p>'
];
// Group fields by their group attribute
$groupedFields = [];
$ungroupedFields = [];
foreach ($enabledCustomFields as $field) {
if (!empty($field['group'])) {
$group = $field['group'];
if (!isset($groupedFields[$group])) {
$groupedFields[$group] = [];
}
$groupedFields[$group][] = $field;
} else {
$ungroupedFields[] = $field;
}
}
// Add ungrouped fields first
if (!empty($ungroupedFields)) {
$ungroupedContainer = [
'type' => 'container',
'container_class' => 'fc_custom_fields fc_2_col',
'fields' => []
];
foreach ($ungroupedFields as $field) {
$fieldType = $field['type'];
$fieldKey = $field['slug'];
$fieldConfig = $this->getCustomFieldConfig($field, $subscriber);
$ungroupedContainer['fields'][$fieldKey] = $fieldConfig;
}
$formFields['custom_fields_ungrouped'] = $ungroupedContainer;
}
// Create containers for each group
foreach ($groupedFields as $groupName => $fields) {
$customFieldsContainer = [
'type' => 'container',
'container_class' => 'fc_custom_fields fc_2_col fc_custom_field_group_box',
'fields' => []
];
$customFieldsContainer['fields']['group_heading'] = [
'type' => 'raw_html',
'html' => '<h5 class="fc_custom_field_group_heading">' . esc_html($groupName) . '</h5>'
];
foreach ($fields as $field) {
$fieldType = $field['type'];
$fieldKey = $field['slug'];
$fieldConfig = $this->getCustomFieldConfig($field, $subscriber);
$customFieldsContainer['fields'][$fieldKey] = $fieldConfig;
}
$formFields['custom_fields_' . sanitize_title($groupName)] = $customFieldsContainer;
}
}
}
if (!$inputOnly) {
return $formFields;
}
return $this->parseInputs($formFields);
}
private function parseInputs($fields)
{
$inputFields = [];
$inputTypes = ['hidden', 'input', 'checkboxes', 'select', 'radio', 'date', 'date_dropdowns', 'textarea', 'select-multi', 'custom_date', 'custom_date_time'];
foreach ($fields as $inputKey => $field) {
$type = Arr::get($field, 'type');
if ($type == 'container') {
$inputFields = array_merge($this->parseInputs($field['fields']), $inputFields);
} else if (in_array($type, $inputTypes)) {
$inputFields[$inputKey] = $field;
}
}
return $inputFields;
}
private function getCustomFieldConfig($field, $subscriber)
{
$fieldType = $field['type'];
$fieldKey = $field['slug'];
$fieldConfig = [
'type' => 'input',
'name' => $fieldKey,
'id' => 'fc_' . $fieldKey,
'label' => $field['label'],
'required' => !empty($field['required']),
'value' => $subscriber->getMeta($field['slug'], 'custom_field')
];
// Add field-specific configurations
switch ($fieldType) {
case 'text':
$fieldConfig['type'] = 'input';
$fieldConfig['atts'] = [
'type' => 'text',
'placeholder' => $field['label'],
'class' => 'fc_input_control'
];
break;
case 'textarea':
$fieldConfig['type'] = 'textarea';
$fieldConfig['atts'] = [
'placeholder' => $field['label'],
'class' => 'fc_input_control',
'name' => $fieldKey
];
break;
case 'number':
$fieldConfig['type'] = 'input';
$fieldConfig['atts'] = [
'type' => 'number',
'placeholder' => $field['label'],
'class' => 'fc_input_control'
];
break;
case 'select-one':
$fieldConfig['type'] = 'select';
$fieldConfig['options'] = array_combine($field['options'], $field['options']);
$fieldConfig['placeholder'] = $field['label'];
$fieldConfig['atts'] = [
'class' => 'fc_input_control select-one'
];
break;
case 'select-multi':
$fieldConfig['type'] = 'select-multi';
$fieldConfig['options'] = array_combine($field['options'], $field['options']);
$fieldConfig['value'] = is_array($fieldConfig['value']) ? $fieldConfig['value'] : [];
$fieldConfig['name'] = $fieldKey . '[]';
$fieldConfig['atts'] = [
'class' => 'fc_input_control select-multi',
'multiple' => 'multiple'
];
break;
case 'radio':
$fieldConfig['type'] = 'radio';
$fieldConfig['options'] = array_combine($field['options'], $field['options']);
$fieldConfig['atts'] = [
'class' => 'fc_input_control'
];
break;
case 'checkbox':
$fieldConfig['type'] = 'checkboxes';
$fieldConfig['options'] = is_array($field['options']) ? $field['options'] : [];
$fieldConfig['value'] = is_array($fieldConfig['value']) ? $fieldConfig['value'] : [];
$fieldConfig['atts'] = [
'class' => 'fc_input_control'
];
break;
case 'date':
$fieldConfig['type'] = 'custom_date';
$fieldConfig['atts'] = [
'type' => 'date',
'class' => 'fc_date_item fc_input_control',
'data-format' => 'YYYY-MM-DD',
'placeholder' => $field['label'],
'data-template' => 'DD - MM - YYYY'
];
break;
case 'date_time':
$fieldConfig['type'] = 'custom_date_time';
$fieldConfig['atts'] = [
'type' => 'text',
'class' => 'fc_date_item fc_input_control',
'data-format' => 'YYYY-MM-DD HH:mm:ss',
'placeholder' => $field['label'],
'data-template' => 'DD - MM - YYYY HH:mm'
];
break;
}
return $fieldConfig;
}
/**
* Check if a string is a valid calendar date in Y-m-d format.
*
* @param string $ymd Date string (e.g. 2024-02-31).
* @return bool
*/
private function isValidDate($ymd)
{
if (!is_string($ymd) || !preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $ymd, $parts)) {
return false;
}
return checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1]);
}
}
@@ -0,0 +1,795 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Services\Helper;
/**
* PurchaseHistory Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class PurchaseHistory
{
/**
* Build the commerce summary widget for supported commerce providers.
*/
public function getCommerceStatWidget($subscriber)
{
/**
* Determine the commerce provider for the purchase history in FluentCRM.
*
* This filter allows you to modify the commerce provider used in FluentCRM.
*
* @since 2.8.0
*
* @param string $commerceProvider The current commerce provider.
* @return string The modified commerce provider.
*/
$commerceProvider = apply_filters('fluentcrm_commerce_provider', '');
if ($commerceProvider) {
/**
* Determine the purchase statistics for a specific commerce provider for a specific subscriber in FluentCRM.
*
* The dynamic portion of the hook name, `$commerceProvider`, refers to the specific commerce provider.
*
* @since 2.8.0
*
* @param array $stats An array of purchase statistics.
* @param int $subscriber->id The ID of the subscriber.
*/
$stats = apply_filters('fluent_crm/contact_purchase_stat_' . $commerceProvider, [], $subscriber->id);
if (!$stats) {
return false;
}
$html = '<ul class="fc_full_listed fcrm_customer_summary_list">';
foreach ($stats as $stat) {
$html .= '<li><span class="fc_list_sub">' . $stat['title'] . '</span> <span class="fc_list_value">' . $stat['value'] . '</span></li>';
}
$html .= '</ul>';
return [
'title' => __('Customer Summary', 'fluent-crm'),
'content' => $html
];
}
if (defined('WC_PLUGIN_FILE')) {
$summary = $this->getWooCustomerSummary($subscriber);
if ($summary) {
return [
'title' => __('Customer Summary', 'fluent-crm'),
'content' => $summary
];
}
return false;
}
if (Helper::isEdd3()) {
$customer = fluentCrmDb()->table('edd_customers')
->where('email', $subscriber->email);
if ($subscriber->user_id) {
$customer = $customer->orWhere('user_id', $subscriber->user_id);
}
$customer = $customer->first();
if (!$customer) {
return false;
}
$summaryData = [
'order_count' => $customer->purchase_count,
'lifetime_value' => number_format($customer->purchase_value, 2),
'avg_value' => ($customer->purchase_count) ? round($customer->purchase_value / $customer->purchase_count, 2) : 'n/a',
'stat_avg_count' => 0,
'stat_avg_spend' => 0,
'stat_avg_value' => 0,
'currency_sign' => edd_currency_symbol(),
'first_order_date' => $customer->date_created
];
$html = $this->formatSummaryData($summaryData, true);
return [
'title' => __('Customer Summary', 'fluent-crm'),
'content' => $html
];
}
return false;
}
public function wooOrders($data, $subscriber)
{
if (!defined('WC_PLUGIN_FILE')) {
return $data;
}
$hasRecount = defined('FLUENTCAMPAIGN') && \FluentCampaign\App\Services\Commerce\Commerce::isEnabled('woo');
$app = fluentCrm();
if ($hasRecount && $app->request->get('will_recount') == 'yes') {
(new \FluentCampaign\App\Services\Integrations\WooCommerce\DeepIntegration)->syncCustomerBySubscriber($subscriber);
}
$page = (int)$app->request->get('page', 1);
$per_page = (int)$app->request->get('per_page', 10);
$sort_by = sanitize_sql_orderby($app->request->get('sort_by', 'id'));
$sort_type = sanitize_sql_orderby($app->request->get('sort_type', 'DESC'));
$valid_columns = ['id', 'date_created', 'total_amount'];
$valid_directions = ['ASC', 'DESC'];
if (!in_array($sort_by, $valid_columns)) {
$sort_by = 'id';
}
if (!in_array(strtoupper($sort_type), $valid_directions)) {
$sort_type = 'DESC';
}
$orders = $this->getWooOrders($subscriber, $sort_by, $sort_type);
$totalOrders = count($orders);
$orders = array_slice($orders, ($page - 1) * $per_page, $per_page);
$formattedOrders = [];
foreach ($orders as $order) {
$item_count = $order->get_item_count() - $order->get_item_count_refunded();
$actionsHtml = '<a target="_blank" href="' . $order->get_edit_order_url() . '">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 5.5V7H4.75V15.25H13V11.5H14.5V16C14.5 16.1989 14.421 16.3897 14.2803 16.5303C14.1397 16.671 13.9489 16.75 13.75 16.75H4C3.80109 16.75 3.61032 16.671 3.46967 16.5303C3.32902 16.3897 3.25 16.1989 3.25 16V6.25C3.25 6.05109 3.32902 5.86032 3.46967 5.71967C3.61032 5.57902 3.80109 5.5 4 5.5H8.5ZM16.75 3.25V9.25H15.25V5.80975L9.40525 11.6553L8.34475 10.5948L14.1888 4.75H10.75V3.25H16.75Z" fill="#525866"/>
</svg>
</a>';
$date = '<span class="order_id">'.'#' . $order->get_order_number().'</span><span class="order_date">'.wc_format_datetime($order->get_date_created()).'</span>';
$status = '<span class="fcrm_badge fcrm_badge_'.esc_attr($order->get_status()).'">'. Helper::getStatusText($order->get_status()) .'</span>';
$formattedOrders[] = [
'date' => wp_kses_post($date),
'status' => wp_kses_post($status),
/* translators: 1: formatted order total (with currency), 2: number of items */
'total' => wp_kses_post(sprintf(_n('%1$s for %2$s item', '%1$s for %2$s items', $item_count, 'fluent-crm'), $order->get_formatted_order_total(), $item_count)),
'action' => $actionsHtml,
];
}
/**
* Determine the WooCommerce purchase history sidebar HTML in FluentCRM.
*
* This filter allows customization of the HTML content displayed in the WooCommerce purchase sidebar.
*
* @since 2.7.0
*
* @param string The current HTML content of the sidebar.
* @param object $subscriber The subscriber object containing subscriber data.
* @param int $page The current page identifier as an integer.
*/
$sidebarHtml = apply_filters('fluent_crm/woo_purchase_sidebar_html', '', $subscriber, $page);
return [
'data' => $formattedOrders,
'sidebar_html' => $sidebarHtml,
'total' => $totalOrders,
'has_recount' => $hasRecount,
'columns_config' => [
'date' => [
'label' => __('Date', 'fluent-crm'),
'sortable' => true,
'key' => 'date_created_gmt'
],
'status' => [
'label' => __('Status', 'fluent-crm'),
],
'total' => [
'label' => __('Total', 'fluent-crm'),
'width' => '160px',
'sortable' => true,
'key' => 'total_amount'
],
'actions' => [
'label' => __('', 'fluent-crm'),
'width' => '50px'
]
]
];
}
public function getWooCustomerSummary($subscriber)
{
$customerQuery = fluentCrmDb()->table('wc_customer_lookup')
->where('email', $subscriber->email);
if ($subscriber->user_id) {
$customerQuery = $customerQuery->orWhere('user_id', $subscriber->user_id);
}
$customer = $customerQuery->first();
if ($customer) {
$statuses = wc_get_is_paid_statuses();
$statuses = array_map(function ($status) {
return 'wc-' . $status;
}, $statuses);
$orderStats = fluentCrmDb()->table('wc_order_stats')
->where('customer_id', $customer->customer_id)
->whereIn('status', $statuses)
->get();
if ($orderStats->isEmpty()) {
return false;
}
$lifetimeValue = 0;
$orderIds = [];
$firstOrderDate = null;
$lastOrderDate = null;
foreach ($orderStats as $order) {
if (!$firstOrderDate) {
$firstOrderDate = $order->date_created;
}
if (!$lastOrderDate) {
$lastOrderDate = $order->date_created;
}
if (strtotime($order->date_created) < strtotime($firstOrderDate)) {
$firstOrderDate = $order->date_created;
}
if (strtotime($order->date_created) > strtotime($lastOrderDate)) {
$lastOrderDate = $order->date_created;
}
$lifetimeValue += $order->total_sales;
$orderIds[] = $order->order_id;
}
$orderIds = array_unique($orderIds);
$orderCount = count($orderIds);
$data_store = \WC_Data_Store::load('report-customers-stats');
$stat = $data_store->get_data();
$avg_value = $orderCount > 0 ? round($lifetimeValue / $orderCount, 2) : 0;
$summaryData = [
'order_count' => $orderCount,
'lifetime_value' => $lifetimeValue,
'avg_value' => $avg_value,
'stat_avg_count' => $stat->avg_orders_count,
'stat_avg_spend' => $stat->avg_total_spend,
'stat_avg_value' => $stat->avg_avg_order_value,
'currency_sign' => get_woocommerce_currency_symbol(),
'last_order_date' => $lastOrderDate,
'first_order_date' => $firstOrderDate,
];
return $this->formatSummaryData($summaryData, true);
}
return false;
}
/**
* Return EDD 3 order history for the subscriber purchase-history panel.
*/
public function eddOrders($data, $subscriber)
{
if (!Helper::isEdd3()) {
return $data;
}
$app = fluentCrm();
$page = (int)$app->request->get('page', 1);
set_query_var('paged', $page);
$hasRecount = defined('FLUENTCAMPAIGN') && \FluentCampaign\App\Services\Commerce\Commerce::isEnabled('edd');
if ($hasRecount && $app->request->get('will_recount') == 'yes') {
(new \FluentCampaign\App\Services\Integrations\Edd\DeepIntegration)->syncCustomerBySubscriber($subscriber);
}
$sort_by = sanitize_sql_orderby($app->request->get('sort_by', 'id'));
$sort_type = sanitize_sql_orderby($app->request->get('sort_type', 'DESC'));
$per_page = (int)$app->request->get('per_page', 10);
$customer = new \EDD_Customer($subscriber->email);
if (!$customer || !$customer->id) {
return $data;
}
$lasOrderData = '';
/*
* EDD 3 stores orders in the edd_orders table. Legacy edd_payment posts
* are intentionally not queried because EDD 2 is no longer supported.
*/
$totalCount = fluentCrmDb()->table('edd_orders')
->where('customer_id', $customer->id)
->count();
if (!$totalCount) {
return $data;
}
$valid_columns = ['id', 'date_created', 'total'];
$valid_directions = ['ASC', 'DESC'];
if (!in_array($sort_by, $valid_columns)) {
$sort_by = 'id';
}
if (!in_array(strtoupper($sort_type), $valid_directions)) {
$sort_type = 'DESC';
}
$orders = fluentCrmDb()->table('edd_orders')
->where('customer_id', $customer->id)
->orderBy($sort_by, $sort_type)
->limit($per_page)
->offset(($page - 1) * $per_page)
->get();
$formattedOrders = [];
foreach ($orders as $order) {
$orderActionHtml = '<a target="_blank" href="' . add_query_arg('id', $order->id, admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details')) . '">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 5.5V7H4.75V15.25H13V11.5H14.5V16C14.5 16.1989 14.421 16.3897 14.2803 16.5303C14.1397 16.671 13.9489 16.75 13.75 16.75H4C3.80109 16.75 3.61032 16.671 3.46967 16.5303C3.32902 16.3897 3.25 16.1989 3.25 16V6.25C3.25 6.05109 3.32902 5.86032 3.46967 5.71967C3.61032 5.57902 3.80109 5.5 4 5.5H8.5ZM16.75 3.25V9.25H15.25V5.80975L9.40525 11.6553L8.34475 10.5948L14.1888 4.75H10.75V3.25H16.75Z" fill="#525866"/>
</svg>
</a>';
$date = '<span class="order_id">'.'#' . $order->id .'</span><span class="order_date">'.date_i18n(get_option('date_format'), strtotime($order->date_created)).'</span>';
$status = '<span class="fcrm_badge fcrm_badge_'.esc_attr($order->status).'">'. Helper::getStatusText($order->status) .'</span>';
$formattedOrders[] = [
'date' => $date,
'status' => $status,
'total' => edd_currency_filter(edd_format_amount($order->total)),
'action' => $orderActionHtml
];
}
if (!$orders->isEmpty()) {
$lasOrderData = date_i18n(get_option('date_format'), strtotime($orders[0]->date_created));
}
/**
* Determine the HTML content displayed in the EDD purchase history sidebar for a subscriber in FluentCRM.
*
* This filter allows customization of the HTML content that appears in the EDD purchase
* history sidebar for a given subscriber on a specific page.
*
* @since 2.7.0
*
* @param string $beforeHtml The HTML content to be displayed before the purchase history.
* @param object $subscriber The subscriber object.
* @param int $page The current page identifier as an integer.
*/
$beforeHtml = apply_filters('fluent_crm/edd_purchase_sidebar_html', '', $subscriber, $page);
// if (!$beforeHtml && $subscriber->user_id && $page == 1 && $formattedOrders) {
// $summaryData = [
// 'order_count' => $customer->purchase_count,
// 'lifetime_value' => $customer->purchase_value,
// 'avg_value' => ($customer->purchase_count) ? round($customer->purchase_value / $customer->purchase_count, 2) : 'n/a',
// 'stat_avg_count' => 0,
// 'stat_avg_spend' => 0,
// 'stat_avg_value' => 0,
// 'currency_sign' => edd_currency_symbol(),
// 'last_order_date' => $lasOrderData
// ];
// $beforeHtml = $this->formatSummaryData($summaryData);
// }
return [
'data' => $formattedOrders,
'total' => $totalCount,
'sidebar_html' => $beforeHtml,
'after_html' => '<p><a target="_blank" rel="noopener" href="'.admin_url('edit.php?post_type=download&page=edd-customers&view=overview&id='.$customer->id).'">' . esc_html__('View Customer Profile', 'fluent-crm') . '</a></p>',
'has_recount' => $hasRecount,
'columns_config' => [
'order' => [
'label' => __('Order', 'fluent-crm'),
'width' => '100px',
'sortable' => true,
'key' => 'id'
],
'date' => [
'label' => __('Date', 'fluent-crm'),
'sortable' => true,
'key' => 'edd_orders'
],
'status' => [
'label' => __('Status', 'fluent-crm'),
'width' => '140px',
'sortable' => false
],
'total' => [
'label' => __('Total', 'fluent-crm'),
'width' => '120px',
'sortable' => true,
'key' => 'total'
],
'action' => [
'label' => __('Actions', 'fluent-crm'),
'width' => '100px',
'sortable' => false
]
]
];
}
public function payformSubmissions($data, $subscriber)
{
if (!defined('WPPAYFORM_VERSION')) {
return $data;
}
$app = fluentCrm();
$page = intval($app->request->get('page', 1));
$per_page = intval($app->request->get('per_page', 10));
$query = fluentCrmDb()->table('wpf_submissions')
->select([
'wpf_submissions.id',
'wpf_submissions.form_id',
'wpf_submissions.currency',
'wpf_submissions.payment_status',
'wpf_submissions.payment_total',
'wpf_submissions.payment_method',
'wpf_submissions.created_at',
'posts.post_title',
'wpf_subscriptions.recurring_amount',
])
->join('posts', 'posts.ID', '=', 'wpf_submissions.form_id')
->leftJoin('wpf_subscriptions', 'wpf_subscriptions.submission_id', '=', 'wpf_submissions.id')
->where(function ($query) use ($subscriber) {
$query->where('wpf_submissions.customer_email', '=', $subscriber->email);
if ($subscriber->user_id) {
$query->orWhere('wpf_submissions.user_id', '=', $subscriber->user_id);
}
})
// ->where('wpf_submissions.payment_total', '>', 0)
->limit($per_page)
->offset($per_page * ($page - 1))
->orderBy('wpf_submissions.id', 'desc');
$total = $query->count();
$submissions = $query->get();
$formattedSubmissions = [];
foreach ($submissions as $submission) {
$submissionUrl = admin_url('admin.php?page=wppayform.php#/edit-form/' . $submission->form_id . '/entries/' . $submission->id . '/view');
$actionUrl = '<a target="_blank" href="' . $submissionUrl . '">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 5.5V7H4.75V15.25H13V11.5H14.5V16C14.5 16.1989 14.421 16.3897 14.2803 16.5303C14.1397 16.671 13.9489 16.75 13.75 16.75H4C3.80109 16.75 3.61032 16.671 3.46967 16.5303C3.32902 16.3897 3.25 16.1989 3.25 16V6.25C3.25 6.05109 3.32902 5.86032 3.46967 5.71967C3.61032 5.57902 3.80109 5.5 4 5.5H8.5ZM16.75 3.25V9.25H15.25V5.80975L9.40525 11.6553L8.34475 10.5948L14.1888 4.75H10.75V3.25H16.75Z" fill="#525866"/>
</svg>
</a>';
$paymentStatus = '<span class="fcrm_badge fcrm_badge_'.esc_attr($submission->payment_status).'">'. \FluentCrm\App\Services\Helper::getStatusText($submission->payment_status) .'</span>';
$formattedSubmissions[] = [
'id' => '#' . $submission->id,
'post_title' => $submission->post_title,
'recurring_amount' => $submission->recurring_amount ? wpPayFormFormatMoney($submission->recurring_amount, $subscriber->form_id) : wpPayFormFormatMoney($submission->payment_total, $subscriber->form_id),
'payment_status' => $paymentStatus,
'payment_method' => $submission->payment_method,
'created_at' => $submission->created_at,
'action' => $actionUrl
];
}
return [
'total' => $total,
'data' => $formattedSubmissions,
'columns_config' => [
'id' => [ 'label' => __('ID', 'fluent-crm'), 'width' => '100px', 'sortable' => false, 'key' => 'id'],
'post_title' => [ 'label' => __('Form Title', 'fluent-crm'), 'sortable' => false, 'key' => 'post_title'],
'recurring_amount' => [ 'label' => __('Payment Total', 'fluent-crm'), 'sortable' => false, 'key' => 'recurring_amount'],
'payment_status' => [ 'label' => __('Payment Status', 'fluent-crm'), 'sortable' => false, 'key' => 'payment_status'],
'payment_method' => [ 'label' => __('Payment Method', 'fluent-crm'), 'sortable' => false, 'key' => 'payment_method'],
'created_at' => [ 'label' => __('Submitted At', 'fluent-crm'), 'sortable' => false, 'key' => 'created_at']
]
];
}
public function formatSummaryData($data, $bodyOnly = false)
{
$blocks = [];
if (!empty($data['first_order_date'])) {
$blocks['Customer Since'] = gmdate(get_option('date_format'), strtotime($data['first_order_date']));
}
if (!empty($data['last_order_date'])) {
$blocks['Last Order'] = gmdate(get_option('date_format'), strtotime($data['last_order_date']));
}
$blocks['Order Count (paid)'] = $data['order_count'] . $this->getPercentChangeHtml($data['order_count'], $data['stat_avg_count']);
$blocks['Lifetime Value'] = $data['currency_sign'] . $data['lifetime_value'];
$blocks['AOV'] = $data['currency_sign'] . $data['avg_value'] . $this->getPercentChangeHtml($data['avg_value'], $data['stat_avg_value']);
$html = '<div class="fc_payment_summary"><h3 class="history_title">' . esc_html__("Customer Summary", "fluent-crm") . '</h3><div class="fc_history_widget">';
$body = '';
$body .= '<ul class="fc_full_listed">';
foreach ($blocks as $title => $block) {
$body .= '<li><span class="fc_list_sub">' . $title . '</span><span class="fc_list_value">' . $block . '</span></li>';
}
if (!empty($data['purchased_products'])) {
$body .= '<li><b>' . esc_html__("Purchased Products", "fluent-crm") . '</b><hr /><ul class="fc_list">';
foreach ($data['purchased_products'] as $product) {
$body .= '<li><a target="_blank" rel="nofollow" href="' . esc_url($product->guid) . '">' . esc_html($product->post_title) . '</a></li>';
}
$body .= '</ul></li>';
}
$body .= '</ul>';
if ($bodyOnly) {
return $body;
}
return $body . '</div></div>';
}
private function getPercentChangeHtml($value, $refValue)
{
if (!$refValue || !$value) {
return '';
}
$change = $value - $refValue;
$percentChange = absint(ceil($change / $refValue * 100));
if ($change >= 0) {
return '<span class="el-icon-caret-top fc_positive fc_change_ref">' . $percentChange . '%' . '</span>';
} else {
return '<span class="el-icon-caret-bottom fc_negative fc_change_ref">' . $percentChange . '%' . '</span>';
}
}
private function getWooOrders($subscriber, $sort_by, $sort_type)
{
$email = $subscriber->email;
$user = get_user_by('email', $email);
// check HPOS is enabled or not
if (get_option('woocommerce_custom_orders_table_enabled') === 'yes') {
// high performance order is enabled
if ($user) {
$hposOrders = fluentCrmDb()->table('wc_orders')
->where('status', '!=', 'trash')
->select(['id'])
->where(function ($query) use ($user) {
$query->where('customer_id', $user->ID)
->orWhere(function ($query) use ($user) {
$query->where('billing_email', $user->user_email)
->where('customer_id', 0);
});
})
->orderBy($sort_by, $sort_type)
->get();
} else {
$hposOrders = fluentCrmDb()->table('wc_orders')
->select(['id'])
->where('billing_email', $email)
->where('customer_id', 0)
->orderBy($sort_by, $sort_type)
->get();
}
if ($hposOrders->isEmpty()) {
return [];
}
$orders = [];
foreach ($hposOrders as $hposOrder) {
$order = wc_get_order($hposOrder->id);
if ($order) {
$orders[$hposOrder->id] = $order;
}
}
return array_values($orders);
}
$orders = [];
// Get all orders by user id
$storeUseId = $user ? $user->ID : false;
if ($storeUseId) {
$userOrders = wc_get_orders([
'customer_id' => $storeUseId,
'limit' => -1,
'orderby' => $sort_by,
'order' => $sort_type,
]);
// Sort orders by total amount manually
if ($sort_by === 'total_amount') {
$this->wooSortOrdersByTotalAmount($userOrders, $sort_type);
}
foreach ($userOrders as $order) {
$orders[$order->get_id()] = $order;
}
}
// get orders by billing email
$guestOrders = wc_get_orders([
'customer' => $email,
'limit' => -1,
'orderby' => $sort_by,
'order' => $sort_type,
]);
if ($sort_by === 'total_amount') {
$this->wooSortOrdersByTotalAmount($userOrders, $sort_type);
}
foreach ($guestOrders as $order) {
$userId = $order->get_user_id();
if ($userId && $storeUseId != $userId) {
continue;
}
$orders[$order->get_id()] = $order;
}
return array_values($orders);
}
/**
* Sorts an array of WooCommerce orders by their total amount.
*
* This method sorts an array of WooCommerce order objects based on the total order amount.
* The sorting can be done in either ascending ('ASC') or descending ('DESC') order,
* as specified by the $sort_type parameter.
*
* @param array $orders Array of WooCommerce order objects to be sorted.
* @param string $sort_type Specifies the sorting order.
* Accepts 'ASC' for ascending or 'DESC' for descending.
*
* @return void The $orders array is sorted in place.
*/
public function wooSortOrdersByTotalAmount(&$orders, $sort_type) {
usort($orders, function ($a, $b) use ($sort_type) {
$a_total = (float)$a->get_total();
$b_total = (float)$b->get_total();
return $sort_type === 'ASC' ? $a_total <=> $b_total : $b_total <=> $a_total;
});
}
public function pmproOrders($data, $subscriber)
{
if (!defined('PMPRO_VERSION')) {
return $data;
}
if (!defined('FLUENTCAMPAIGN')) {
return $data;
}
$customer = fluentCrmDb()->table('users')->where('user_email', $subscriber->email)->first();
if (!$customer) {
return false;
}
if (!$subscriber->user_id || $subscriber->user_id != $customer->ID) {
$subscriber->user_id = $customer->ID;
$subscriber->save();
}
$app = fluentCrm();
$page = (int)$app->request->get('page', 1);
$per_page = (int)$app->request->get('per_page', 10);
$sort_by = sanitize_sql_orderby($app->request->get('sort_by', 'ID'));
$sort_type = sanitize_sql_orderby($app->request->get('sort_type', 'DESC'));
$valid_columns = ['ID', 'date', 'modified'];
$valid_directions = ['ASC', 'DESC'];
if (!in_array($sort_by, $valid_columns)) {
$sort_by = 'ID';
}
if (!in_array(strtoupper($sort_type), $valid_directions)) {
$sort_type = 'DESC';
}
// Fetch the array of MemberOrder OBJECTS
$user_order_objects = \MemberOrder::get_orders([
'user_id' => $subscriber->user_id,
'status' => 'success',
'orderby' => $sort_by,
'order' => $sort_type
]);
// Create a new, simple array to hold the data for JSON conversion
$formattedOrders = [];
$totalOrders = count($user_order_objects);
$orders = array_slice($user_order_objects, ($page - 1) * $per_page, $per_page);
if (!empty($orders)) {
// Loop through each PHP object and extract its data into a simple array
foreach ($orders as $order) {
// Construct the URL using WordPress's admin_url() function
$order_page_url = admin_url('admin.php?page=pmpro-orders&order=' . $order->id);
$level = pmpro_getLevel($order->membership_id);
$actionsHtml = '<td><a href="' . esc_url($order_page_url) . '" target="_blank">View Order</a></td>';
$status = '<span class="fcrm_badge fcrm_badge_'.esc_attr($order->status).'">'. \FluentCrm\App\Services\Helper::getStatusText($order->status) .'</span>';
$formattedOrders[] = [
'order_code' => '#' . $order->code,
'membership_level_name' => $level ? $level->name : null,
'status' => $status,
'total' => $order->total,
'date' => gmdate('j F, Y', $order->timestamp),
'gateway' => $order->gateway,
'actions' => $actionsHtml
];
}
}
return [
'data' => $formattedOrders,
'sidebar_html' => '',
'total' => $totalOrders,
'has_recount' => false,
'columns_config' => [
'order_code' => [
'label' => __('Order Code', 'fluent-crm'),
'width' => '120px',
'sortable' => false,
'key' => 'id'
],
'membership_level_name' => [
'label' => __('Membership Level', 'fluent-crm'),
'sortable' => false,
],
'date' => [
'label' => __('Date', 'fluent-crm'),
'sortable' => false,
'key' => 'date_created_gmt'
],
'status' => [
'label' => __('Status', 'fluent-crm'),
'width' => '100px'
],
'total' => [
'label' => __('Total', 'fluent-crm'),
'width' => '130px',
'sortable' => false,
'key' => 'total_amount'
],
'gateway' => [
'label' => __('Gateway', 'fluent-crm'),
'width' => '120px',
'sortable' => false,
],
'actions' => [
'label' => __('Actions', 'fluent-crm'),
'width' => '100px'
]
]
];
}
}
@@ -0,0 +1,184 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Campaign;
use FluentCrm\App\Models\CampaignEmail;
use FluentCrm\App\Models\CampaignUrlMetric;
use FluentCrm\App\Models\UrlStores;
use FluentCrm\Framework\Support\Arr;
/**
* RedirectionHandler Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class RedirectionHandler
{
public function redirect($data)
{
nocache_headers();
$mailId = false;
$urlSlug = sanitize_text_field($data['ns_url']);
if (isset($data['mid'])) {
$mailId = intval($data['mid']);
}
$urlData = fluentCrmGetFromCache('url_' . $urlSlug, function () use ($urlSlug) {
return UrlStores::getRowByShort($urlSlug);
});
if (!$urlData) {
return;
}
if (isset($data['fch'])) {
$urlData->url_token = $data['fch'];
}
$isAnonymousClick = isset($data['ano']);
$redirectUrl = trim($this->trackUrlClick($mailId, $urlData, $isAnonymousClick));
$redirectUrl = htmlspecialchars_decode($redirectUrl);
if (!$redirectUrl) {
wp_redirect(home_url(), 307);
exit;
}
// remove zero width space
$redirectUrl = str_replace(["\xE2\x80\x8B", '%E2%80%8B'], '', $redirectUrl);
do_action('fluentcrm_email_url_click', $redirectUrl, $mailId, $urlData);
wp_redirect($redirectUrl, 307);
exit;
}
public function trackUrlClick($mailId, $urlData, $isAnonymousClick = false)
{
if (!$mailId) {
return $urlData->url;
}
$campaignEmail = CampaignEmail::with(['subscriber'])->find($mailId);
if (!$campaignEmail || !$campaignEmail->subscriber) {
return $urlData->url;
}
$campaign = fluentCrmGetFromCache('campaign_' . $campaignEmail->campaign_id, function () use ($campaignEmail) {
return Campaign::withoutGlobalScopes()->find($campaignEmail->campaign_id);
});
if (!$campaign) {
return $urlData->url;
}
// Require valid fch token before recording any tracking data.
// Missing or invalid token = redirect but don't record metrics.
// This prevents analytics poisoning via forged or guessed mid values.
if (empty($urlData->url_token) || substr($campaignEmail->email_hash, 0, 8) !== $urlData->url_token) {
return $urlData->url;
}
if (!$campaignEmail->is_open && !$isAnonymousClick) {
do_action('fluent_crm/email_opened', $campaignEmail);
}
if (!$isAnonymousClick) {
CampaignUrlMetric::maybeInsert([
'url_id' => $urlData->id,
'campaign_id' => $campaignEmail->campaign_id,
'subscriber_id' => $campaignEmail->subscriber_id,
'type' => 'click',
'ip_address' => FluentCrm('request')->getIp(fluentCrmWillAnonymizeIp())
]);
}
$url = $urlData->url;
$url = str_replace('&amp;', '&', $url);
$url = esc_url_raw($url);
$isSmartUrl = strpos($url, 'route=smart_url');
$tokenVerified = false;
/**
* Filter whether to use cookies for FluentCRM redirection.
*
* This filter allows you to control whether cookies should be used for tracking
* FluentCRM redirection. By default, it is set to true.
*
* @param bool Whether to use cookies for redirection. Default true.
* @since 2.8.44
*
*/
if (apply_filters('fluent_crm/will_use_cookie', true) && !empty($urlData->url_token)) {
// validate the URL token here
if (substr($campaignEmail->email_hash, 0, 8) === $urlData->url_token) {
$tokenVerified = true;
$secureHash = fluentCrmGetContactSecureHash($campaignEmail->subscriber_id);
setcookie("fc_hash_secure", $secureHash, time() + 7776000, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); /* expire in 90 days */
$_COOKIE['fc_hash_secure'] = $secureHash;
}
if ($campaignEmail->campaign_id) {
setcookie("fc_cid", $campaignEmail->campaign_id, time() + 2419200, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); /* expire in 28 days */
}
}
do_action('fluent_crm/email_url_clicked', $campaignEmail, $urlData);
$args = $campaign->getUtmParams();
if (!$isAnonymousClick) {
$campaignEmail->click_counter += 1;
$campaignEmail->is_open = 1;
$campaignEmail->save();
} else {
do_action('fluent_crm/anonymous_email_url_clicked', $url, $campaign, $campaignEmail);
}
do_action('fluent_crm/track_activity_by_subscriber', $campaignEmail->subscriber);
if ($isSmartUrl) {
// this is a smart URL
$url_components = wp_parse_url($url);
parse_str($url_components['query'], $params);
if (!empty($params['slug'])) {
$subscriber = $campaignEmail->subscriber;
$signedHash = Arr::get($_REQUEST, 'signed_hash');
$isSecure = $tokenVerified && $signedHash && \FluentCrm\App\Services\Helper::verifySmartUrlHash($campaignEmail->email_hash, $signedHash);
if ($isSecure) {
do_action('fluent_crm/smart_link_verified', $subscriber);
}
do_action('fluentcrm_smartlink_clicked_direct', sanitize_text_field($params['slug']), $subscriber, $campaignEmail);
}
}
if (strpos($urlData->url, 'route=bnu') !== false) {
$url_components = wp_parse_url($url);
parse_str($url_components['query'], $params);
if (!empty($params['aid'])) {
$benchmarkActionId = intval($params['aid']);
// Note: hook name has a known typo (missing 't' in 'fluent') — kept for backward compatibility with Pro
do_action('fluencrm_benchmark_link_clicked', $benchmarkActionId, $campaignEmail->subscriber);
}
$args['bnu_timer_' . time()] = time();
}
if ($args) {
$url = add_query_arg($args, $url);
}
return $url;
}
}
@@ -0,0 +1,594 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Models\Campaign;
use FluentCrm\App\Models\CampaignEmail;
use FluentCrm\App\Services\CampaignProcessor;
use FluentCrm\App\Services\ExternalIntegrations\Maintenance;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Services\Libs\FileSystem;
use FluentCrm\App\Services\Libs\Mailer\Handler;
use FluentCrm\App\Services\Libs\Mailer\MultiThreadHandler;
/**
* Scheduler Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class Scheduler
{
public static function register()
{
/*
* Migrating from CRON to Action Scheduler for Every Minutes Tasks
*/
add_action('fluentcrm_scheduled_minute_tasks', function () {
// Auto-migration: ensure the Action Scheduler recurring action exists.
if (!as_has_scheduled_action('fluentcrm_scheduled_every_minute_tasks', [], 'fluent-crm')) {
Helper::debugLog('Migrating Every Minute CRON to Action Scheduler for FluentCRM');
as_schedule_recurring_action(time(), 60, 'fluentcrm_scheduled_every_minute_tasks', [], 'fluent-crm');
return;
}
// WP-Cron is a TRUE fallback: only take over when Action Scheduler
// has actually stalled. _fcrm_last_scheduler is written by
// Scheduler::process() on every successful AS-driven minute tick;
// if it's fresh, AS owns this minute and we no-op here.
$lastScheduler = fluentCrmGetOptionCache('_fcrm_last_scheduler');
if ($lastScheduler && (time() - $lastScheduler) <= 70) {
return;
}
// AS appears stalled (or has never run on this site yet) — take
// over via the same locked entry point AS uses. The atomic lock
// inside process() prevents two concurrent WP-Cron runners both
// deciding to take over from racing each other.
self::process();
});
// This is required to instantly send emails for regular email handler.
// The atomic lock inside Handler::isSystemOk() (acquired before any
// expensive work) is the authoritative guard against concurrent and
// duplicate sends, so we invoke the sender directly — a losing racer
// bails cheaply at the lock. No cron-timing pre-check is needed here.
add_action('wp_ajax_nopriv_fluentcrm-post-campaigns-send-now', function () {
(new \FluentCrm\App\Services\Libs\Mailer\Handler())->handle();
nocache_headers();
wp_send_json_success([
'message' => 'success',
'timestamp' => time()
]);
});
// For Multi Threaded Emails Internal Ajax. Same as above — the atomic
// lock inside MultiThreadHandler::isSystemOk() guards against concurrent
// runners, so we call the handler directly and let the loser bail at the
// lock. The experimental-flag check stays here to avoid constructing the
// handler at all when multi-threading is disabled.
add_action('wp_ajax_nopriv_fluentcrm-post-multi-thread-send-now', function () {
if (Helper::isExperimentalEnabled('multi_threading_emails')) {
(new MultiThreadHandler())->handle();
}
nocache_headers();
wp_send_json_success([
'message' => 'success',
'timestamp' => time()
]);
});
add_action('fluentcrm_scheduled_every_minute_tasks', array(__CLASS__, 'process'));
add_action('fluentcrm_scheduled_hourly_tasks', array(__CLASS__, 'processHourly'));
add_action('fluentcrm_scheduled_five_minute_tasks', array(__CLASS__, 'processFiveMinutes'));
add_action('fluentcrm_process_contact_jobs', array(__CLASS__, 'processForSubscriber'), 999, 1);
add_action('fluentcrm_scheduled_weekly_tasks', array(__CLASS__, 'processWeekly'));
add_action('fluent_crm_send_multi_thread_emails', array(__CLASS__, 'processMultiThreadEmails'), 10);
add_action('fluent_crm_cancel_multi_thread_mailing', function () {
as_unschedule_all_actions('fluent_crm_send_multi_thread_emails');
return true;
});
/*
* Clean up schedule that means removing from database- tasks by action scheduler
* Clean up before last 7 days logs generated by action scheduler
* this action will be triggered daily and will remove all the logs generated before 7 days
*/
add_action('fluent_crm_ascheduler_runs_daily', function () {
Cleanup::maybeRemoveOldScheuledActionLogs();
});
}
public static function process()
{
wp_raise_memory_limit('admin');
// In-process re-entrance guard (cheap; complements the cross-process lock below).
if (did_action('fluentcrm_process_scheduled_tasks_init')) {
return false;
}
// Atomic cross-process mutex. Prevents concurrent AS + WP-Cron + AJAX
// runners from all reaching Handler->handle() at the same time. The
// downstream BaseHandler also has its own lock — this outer guard
// avoids wasted PHP bootstraps for the loser of the race.
if (!self::acquireLock('minute_scheduler', 90)) {
return false;
}
try {
// _fcrm_last_scheduler stays as the success-timestamp signal used
// by the WP-Cron fallback in register() to detect a stalled Action
// Scheduler. It is no longer the gate that prevents re-entry —
// that role belongs to the atomic lock above.
fluentCrmSetOptionCache('_fcrm_last_scheduler', time(), 50);
do_action('fluentcrm_process_scheduled_tasks_init');
(new Handler)->handle();
} finally {
self::releaseLock('minute_scheduler');
}
return true;
}
/**
* Browser-ping fallback for the every-minute task.
*
* Triggered from the admin app's periodic ping (ReportingController::ping,
* fired ~every 50s while any CRM page is open). It is a TRUE last-resort
* fallback: it only takes over when Action Scheduler (and the WP-Cron
* fallback) have stalled, detected by the same _fcrm_last_scheduler
* freshness signal the WP-Cron fallback in register() uses. When AS is
* healthy this returns after a single option read, so it is safe to call on
* every ping and for every admin who has the dashboard open — it does NOT
* run cron more often than once per minute on a healthy site.
*
* All concurrency safety lives in process(): its atomic cross-process lock
* means that even with many tabs/users pinging at once, at most one runner
* sends emails, and the _fcrm_last_scheduler stamp written there throttles
* takeovers to roughly once per minute. This only advances the minute task
* (the email-sending pipeline); the heavier hourly/five-minute tasks keep
* their own WP-Cron/AS schedules.
*
* @return bool True if it took over and ran the minute task, false otherwise.
*/
public static function maybeProcessFromBrowserPing()
{
// Action Scheduler owns this task; only step in when it has actually
// stalled. Same 70s threshold as the WP-Cron fallback in register().
$lastScheduler = fluentCrmGetOptionCache('_fcrm_last_scheduler');
if ($lastScheduler && (time() - $lastScheduler) <= 70) {
return false;
}
return self::process();
}
public static function processForSubscriber($subscriber)
{
if (!is_object($subscriber) || empty($subscriber->id)) {
return false;
}
if (!defined('FLUENTCRM_DOING_BULK_IMPORT')) {
// @todo: Implement this immediately
(new Handler)->processSubscriberEmail($subscriber->id);
}
return true;
}
public static function processHourly()
{
// Atomic mutex. Closes the duplicate-event leak in markArchiveCampaigns():
// without this, two concurrent hourly runners both pass the SELECT,
// both UPDATE rows to 'archived' (idempotent), and both fire
// fluent_crm/campaign_archived for the same campaign — causing
// listeners (webhooks, metrics, notifications) to fire twice.
if (!self::acquireLock('hourly_scheduler', 300)) {
return;
}
try {
self::markArchiveCampaigns();
self::maybeCleanupCsvFiles();
do_action('fluent_crm_process_automation');
} finally {
self::releaseLock('hourly_scheduler');
}
}
public static function markArchiveCampaigns()
{
// get the scheduled or working campaigns where scheduled_at is five minutes ago
$campaigns = Campaign::whereIn('status', ['working', 'scheduled'])
->whereDoesntHave('emails', function ($query) {
$query->whereIn('status', ['scheduling', 'pending', 'scheduled', 'processing', 'draft']);
return $query;
})
->withoutGlobalScope('type')
->whereIn('type', fluentCrmAutoProcessCampaignTypes())
->where('scheduled_at', '<', gmdate('Y-m-d H:i:s', current_time('timestamp') - 300))
->get();
if (!$campaigns->isEmpty()) {
Campaign::whereIn('id', array_unique($campaigns->pluck('id')->toArray()))
->withoutGlobalScope('type')
->update([
'status' => 'archived'
]);
foreach ($campaigns as $campaign) {
do_action('fluent_crm/campaign_archived', $campaign);
}
return true;
}
return false;
}
/**
* @return void
*/
public static function processWeekly()
{
(new Maintenance())->maybeProcessData();
// Clear email_body from historical 'sent' rows to reclaim disk space.
// Loop a LIMIT-bounded UPDATE so each statement's row-lock footprint
// stays small (an unbounded UPDATE on a multi-million-row table holds
// locks for minutes and stalls report/dashboard SELECTs) while still
// draining the full backlog in this tick. Going direct to $wpdb skips
// ORM overhead on what is effectively the same repeated statement.
try {
global $wpdb;
$table = $wpdb->prefix . 'fc_campaign_emails';
$chunkSize = 50000;
$maxIterations = 100; // safety cap — up to ~5M rows per weekly tick
for ($i = 0; $i < $maxIterations; $i++) {
$affected = (int) $wpdb->query(
"UPDATE {$table} SET email_body = '' WHERE status = 'sent' AND email_body != '' LIMIT {$chunkSize}"
);
if ($affected < $chunkSize || fluentCrmIsMemoryExceeded()) {
break;
}
}
} catch (\Exception $e) {
Helper::debugLog('processWeekly', 'email_body cleanup deferred: ' . $e->getMessage(), 'extended');
}
}
/**
* Discover and process pending campaigns.
*
* Called by cron/Action Scheduler. Handles housekeeping (stale email reset),
* finds campaigns ready to process, and kicks off processing. For continuous
* processing, use processCampaignById() via the AJAX handler.
*
* @return bool
*/
public static function processFiveMinutes()
{
// Cheap time-based pre-check — skips the lock-acquire round trip when
// the function is called more frequently than the work needs to run.
$lastRun = fluentCrmGetOptionCache('_fcrm_last_five_minutes_run', 30);
if ($lastRun && (time() - $lastRun) < 60) {
return false;
}
// Atomic mutex. The throttle above is non-atomic so two near-simultaneous
// callers can both pass it; the lock guarantees that only one actually
// proceeds into discovery + processing.
if (!self::acquireLock('five_minute_scheduler', 180)) {
return false;
}
try {
fluentCrmSetOptionCache('_fcrm_last_five_minutes_run', time(), 60);
self::resetStaleProcessingEmails(100, 'processFiveMinutes');
$cutOutTime = gmdate('Y-m-d H:i:s', current_time('timestamp') + 360);
$campaigns = Campaign::whereIn('status', ['pending-scheduled', 'processing'])
->withoutGlobalScope('type')
->whereIn('type', fluentCrmAutoProcessCampaignTypes())
->orderBy('scheduled_at', 'ASC')
->where('scheduled_at', '<=', $cutOutTime)
->limit(2)
->get();
if ($campaigns->isEmpty()) {
do_action('fluent_crm_process_automation');
do_action('fluentcrm_scheduled_hourly_tasks');
return false;
}
$firstCampaign = $campaigns->first();
if ($firstCampaign->status == 'pending-scheduled') {
$firstCampaign->status = 'processing';
$firstCampaign->save();
}
$result = self::processCampaignById($firstCampaign->id);
// If first campaign is done and there are more queued, chain the next one.
// Skip if memory is low (aborted) to avoid cascading failures.
if (!$result && count($campaigns) > 1 && !fluentCrmIsMemoryExceeded()) {
// Verify first campaign actually finished (not just aborted)
$firstCampaign = Campaign::withoutGlobalScope('type')->find($firstCampaign->id);
if ($firstCampaign && $firstCampaign->status != 'processing') {
$nextCampaign = $campaigns->last();
if ($nextCampaign->status == 'pending-scheduled') {
$nextCampaign->status = 'processing';
$nextCampaign->save();
}
self::fireCampaignProcessingChain($nextCampaign->id);
}
}
return $result;
} finally {
self::releaseLock('five_minute_scheduler');
}
}
/**
* Reset rows stuck in 'processing' back to 'pending' so they get re-claimed.
*
* An unbounded mass UPDATE on (status='processing' AND updated_at < cutoff)
* locks a wide range and deadlocks against the row-level SELECT ... FOR
* UPDATE claims that the mailer Handler / MultiThreadHandler hold while
* sending. We instead drain in bounded chunks by primary key.
*
* We deliberately do NOT order the SELECT: ORDER BY id would push MySQL
* onto PRIMARY (full id-walk looking for sparse matches on a multi-million
* row table) instead of the (status, scheduled_at) index, which contains
* only the small currently-'processing' slice. Each chunk drains rows out
* of the predicate, so the next iteration naturally finds different rows
* without an explicit order.
*
* Any deadlock that still slips through is harmless — remaining rows will
* be picked up on the next caller's tick.
*
* @param int $maxAgeSeconds Rows older than this (in 'processing') get reset.
* @param string $callerContext Used in the deferred-log message.
* @return int Number of rows reset back to pending.
*/
public static function resetStaleProcessingEmails($maxAgeSeconds = 100, $callerContext = '')
{
try {
// If a sender lock is still fresh, a batch is likely active or just
// yielded. Resetting 'processing' rows during that window risks
// requeueing work owned by the live sender and increases row-lock
// contention with SELECT ... FOR UPDATE / sent-status updates.
if (self::hasFreshEmailSenderLock($maxAgeSeconds)) {
return 0;
}
$staleCutoff = gmdate('Y-m-d H:i:s', current_time('timestamp') - (int) $maxAgeSeconds);
$chunkSize = 200;
$maxChunks = 50; // up to 10k rows per call; subsequent calls drain the rest
$recovered = 0;
for ($i = 0; $i < $maxChunks; $i++) {
$staleIds = CampaignEmail::where('status', 'processing')
->where('updated_at', '<', $staleCutoff)
->limit($chunkSize)
->pluck('id')
->toArray();
if (empty($staleIds)) {
break;
}
$updated = CampaignEmail::whereIn('id', $staleIds)
->where('status', 'processing')
->update([
'status' => 'pending'
]);
if ($updated === false) {
global $wpdb;
Helper::debugLog($callerContext ?: 'resetStaleProcessingEmails', 'Stale email reset deferred: ' . $wpdb->last_error, 'extended');
break;
}
$recovered += (int) $updated;
if (count($staleIds) < $chunkSize || fluentCrmIsMemoryExceeded()) {
break;
}
}
if ($recovered) {
Helper::debugLog($callerContext ?: 'resetStaleProcessingEmails', 'Recovered ' . $recovered . ' stale processing emails older than ' . (int) $maxAgeSeconds . ' seconds', 'extended');
}
return $recovered;
} catch (\Exception $e) {
Helper::debugLog($callerContext ?: 'resetStaleProcessingEmails', 'Stale email reset deferred: ' . $e->getMessage(), 'extended');
return 0;
}
}
/**
* Avoid stale-row recovery while a sender still appears active.
*
* Sender locks are refreshed by BaseHandler::refreshLock() between claimed
* batches. We check all sender lock keys because regular, multi-threaded,
* and CLI senders can all own rows in fc_campaign_emails.
*
* @param int $maxAgeSeconds
* @return bool
*/
private static function hasFreshEmailSenderLock($maxAgeSeconds)
{
// Use at least 60 seconds so a very small caller-provided stale window
// does not make recovery race an otherwise healthy sender.
$freshWindow = max(60, (int) $maxAgeSeconds);
// Compare everything against one timestamp for consistent decisions
// across all sender lock keys checked below.
$now = time();
foreach (['fluentcrm_is_sending_emails', 'fluentcrm_is_sending_multi_emails', 'fluentcrm_is_sending_cli_emails'] as $lockKey) {
// Read the lock straight from its wp_options row. BaseHandler's
// acquireLock()/refreshLock() store the timestamp there via
// Helper::acquireDbLock()/refreshDbLock() on every environment, so we
// must NOT use getInstantOption() here: on object-cache sites it reads
// the fc_instant_options group, which the DB lock never writes to, and
// would miss a live sender — letting recovery reset its rows.
$lockedAt = Helper::getDbLockTimestamp($lockKey);
// A non-empty timestamp inside the freshness window means a sender
// appears active, so stale recovery should defer to the next tick.
if ($lockedAt && ($now - $lockedAt) <= $freshWindow) {
return true;
}
}
// No fresh sender lock was found. Recovery may safely inspect stale rows.
return false;
}
/**
* Process a specific campaign by ID.
*
* Can be called directly from the AJAX handler for continuous chaining
* without re-discovering campaigns or running housekeeping.
*
* @param int $campaignId
* @return bool True if more processing is needed, false if done.
*/
public static function processCampaignById($campaignId)
{
// Per-campaign scheduler lock. processCampaignById has two entry points
// — the AJAX self-trigger fluentcrm-post-campaigns-emails-processing
// (which bypasses processFiveMinutes' scheduler-level lock entirely)
// and processFiveMinutes itself (which holds five_minute_scheduler).
// Without this guard, fireCampaignProcessingChain could pile up
// overlapping AJAX requests for the same campaign that all reach
// CampaignProcessor and bail at its per-campaign lock — wasted PHP
// bootstraps. Lock name is per-campaign so different campaigns still
// process in parallel. TTL matches the set_time_limit(120) below.
$lockName = 'campaign_chain_' . (int)$campaignId;
if (!self::acquireLock($lockName, 120)) {
return false;
}
try {
if (function_exists('set_time_limit')) {
@set_time_limit(120);
}
$campaign = Campaign::withoutGlobalScope('type')->find($campaignId);
if (!$campaign) {
return false;
}
$campaignProcessingChunk = (int)apply_filters('fluent_crm/five_minute_campaign_processing_chunk', 20, $campaign);
if ($campaignProcessingChunk < 1) {
$campaignProcessingChunk = 1;
}
$runTime = fluentCrmMaxRunTime() - 5;
$campaign = (new CampaignProcessor($campaignId))->processEmails($campaignProcessingChunk, $runTime);
if (fluentCrmIsMemoryExceeded()) {
return false;
}
if ($campaign && $campaign->status == 'processing') {
self::fireCampaignProcessingChain($campaignId);
return true;
}
return false;
} finally {
self::releaseLock($lockName);
}
}
/**
* Fire a background AJAX request to continue processing a specific campaign.
*
* @param int $campaignId
*/
private static function fireCampaignProcessingChain($campaignId)
{
$url = add_query_arg([
'action' => 'fluentcrm-post-campaigns-emails-processing',
'campaign_id' => $campaignId,
'time' => time()
], admin_url('admin-ajax.php'));
\FluentCrm\App\Services\Libs\Mailer\Handler::fireNonBlockingRequest($url, [
'retry' => 1
]);
}
public static function maybeCleanupCsvFiles()
{
$dir = FileSystem::getDir();
// loop through files in directory
foreach (glob($dir . '/fluentcrm-*.csv') as $filename) {
// check if file was created before last 30 minutes
if (time() - filectime($filename) >= 1800) {
wp_delete_file($filename); // delete file
}
}
}
public static function processMultiThreadEmails()
{
(new MultiThreadHandler())->handle();
return true;
}
/**
* Atomically claim a scheduler-level lock so two runners can't enter the
* same critical section concurrently (e.g. Action Scheduler + WP-Cron
* minute ticks landing in the same second).
*
* Backed by a conditional UPDATE on wp_options keyed off a timestamp
* (Helper::acquireDbLock). The UPDATE succeeds only if the row is unclaimed
* or its stored timestamp is older than $ttl, so a crashed runner's lock
* self-recovers after the TTL. This is used on every environment — we no
* longer take a wp_cache_add() fast path, because that primitive is not
* atomic under all object-cache drop-ins (e.g. LiteSpeed), which let
* concurrent runners all acquire the same lock. See Helper::acquireDbLock().
*
* @param string $name Lock identifier appended to the option key.
* @param int $ttl Seconds before a held lock is considered abandoned.
* @return bool True if the lock was acquired by this process.
*/
private static function acquireLock($name, $ttl)
{
return Helper::acquireDbLock('_fluentcrm_lock_' . $name, $ttl);
}
/**
* Release a scheduler-level lock previously acquired by acquireLock().
* Safe to call even if the lock was not held by this process — the worst
* case is freeing the slot a tick early.
*/
private static function releaseLock($name)
{
Helper::releaseDbLock('_fluentcrm_lock_' . $name);
}
}
@@ -0,0 +1,161 @@
<?php
/**
* Setup wizard class
*
* Intial Setup Wizard for FluentCRM
*
*/
namespace FluentCrm\App\Hooks\Handlers;
use FluentCrm\App\Services\PermissionManager;
use FluentCrm\App\Services\TransStrings;
use FluentCrm\App\Vite;
use FluentCrm\Framework\Support\Arr;
/**
* SetupWizard Class
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class SetupWizard
{
/**
* Hook in tabs.
*/
public function __construct()
{
/**
* Determine whether to enable the FluentCRM setup wizard.
*
* This filter allows you to enable or disable the setup wizard for FluentCRM.
*
* @since 1.0.0
*
* @param bool Whether to enable the setup wizard. Default true.
*/
if (apply_filters('fluentcrm_setup_wizard', true) && current_user_can('manage_options')) {
if(fluentcrm_get_option('fluentcrm_setup_wizard_ran') == 'yes') {
wp_redirect(admin_url('admin.php?page=fluentcrm-admin&setup_complete=' . time()));
exit();
}
fluentcrm_update_option('fluentcrm_setup_wizard_ran', 'yes');
$this->setup_wizard();
}
}
/**
* Show the setup wizard
*/
public function setup_wizard()
{
add_filter('user_can_richedit', '__return_true');
if (!function_exists('media_handle_upload')) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
}
if (current_user_can('upload_files')) {
wp_enqueue_script('media-upload');
}
add_thickbox();
wp_enqueue_editor();
if (function_exists('wp_enqueue_media')) {
wp_enqueue_media();
}
// Inject Vite HMR client — mirrors AdminMenu::loadCssJs().
// Without this, Vue <style> blocks are not applied in dev mode.
add_action('admin_head', function () {
Vite::injectViteClient();
}, 1);
// style.css is the merged bundle of all Vue component CSS + Element Plus CSS,
// produced by vite.config.mjs's mergeCssChunksPlugin. The manifest is
// stripped of references to the merged files at build time
// (moveManifestPlugin), so Vite::enqueueScript's auto-enqueue won't
// pick it up — load it explicitly here. In dev mode, Vite HMR
// injects the styles via the client above.
if (!Vite::underDevelopment()) {
wp_enqueue_style(
'fluentcrm_vendor',
fluentCrmMix('admin/css/style.css'),
[],
FLUENTCRM_PLUGIN_VERSION
);
}
wp_enqueue_style(
'fluentcrm-setup',
fluentCrmMix('admin/css/setup-wizard.css'),
['dashicons']
);
// Use Vite::enqueueScript so handles are added to $moduleScripts,
// ensuring type="module" is applied correctly in both dev and production.
Vite::enqueueScript('fluentcrm-boot', 'admin/boot.js', ['jquery'], FLUENTCRM_PLUGIN_VERSION, true);
Vite::enqueueScript('fluentcrm-setup', 'admin/setup-wizard.js', ['fluentcrm-boot'], FLUENTCRM_PLUGIN_VERSION, true);
wp_enqueue_script('lodash');
$existingSettings = get_option(FLUENTCRM . '-global-settings');
$businessSettings = Arr::get($existingSettings, 'business_settings', []);
$currentUser = wp_get_current_user();
wp_localize_script('fluentcrm-boot', 'fcAdmin', [
'ajaxurl' => admin_url('admin-ajax.php'),
'slug' => FLUENTCRM,
'rest' => $this->getRestInfo(FluentCrm()),
'trans' => TransStrings::getStrings(),
'dashboard_url' => admin_url('admin.php?page=fluentcrm-admin&setup_complete=' . time()),
'business_settings' => (object) $businessSettings,
'has_fluentform' => defined('FLUENTFORM'),
'has_fluentcart' => defined('FLUENTCART_VERSION'),
'auth' => [
'permissions' => PermissionManager::currentUserPermissions(),
'first_name' => $currentUser->first_name,
'last_name' => $currentUser->last_name,
'email' => $currentUser->user_email,
'avatar' => fluentcrmGetAvatarHtml($currentUser->user_email, $currentUser->display_name, 128),
'user_id' => $currentUser->ID
],
]);
$this->outputHtml();
}
/**
* Setup Wizard HTML
*/
public function outputHtml()
{
ob_start();
fluentCrm('view')->render('admin.setup_wizard');
exit();
}
protected function getRestInfo($app)
{
$ns = $app->config->get('app.rest_namespace');
$v = $app->config->get('app.rest_version');
return [
'base_url' => esc_url_raw(rest_url()),
'url' => rest_url($ns . '/' . $v),
'nonce' => wp_create_nonce('wp_rest'),
'namespace' => $ns,
'version' => $v,
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
class UpgradationHandler
{
public static function maybeUpdateDbTables()
{
$currentDbVerson = get_option('_fluentcrm_db_version');
if (!$currentDbVerson || version_compare($currentDbVerson, FLUENTCRM_DB_VERSION, '<')) {
require_once(FLUENTCRM_PLUGIN_PATH . 'database/FluentCRMDBMigrator.php');
// A migration just ran (and an index ALTER may have failed mid-flight).
// Drop the cached index-health snapshot so the next health check hits
// the live DB and the on-load self-heal reflects the true post-migration
// state instead of a pre-migration "ok". Stored as an empty array (not
// deleted) because getIndexHealth() treats an empty cache as stale.
fluentcrm_update_option('_db_index_health', []);
}
}
public static function updateTables()
{
// Run DB Migrations
require_once(FLUENTCRM_PLUGIN_PATH . 'database/FluentCRMDBMigrator.php');
}
}
@@ -0,0 +1,112 @@
<?php
namespace FluentCrm\App\Hooks\Handlers;
/**
* UrlMetrics Class - For Internal Debugging usage only
*
* @package FluentCrm\App\Hooks
*
* @version 1.0.0
*/
class WpQueryLogger
{
static $logInFile = true;
public static function getQueryLog($withStack = true)
{
$trace = debug_backtrace(2, 0);
$trace = reset($trace);
$file = explode('/', $trace['file']);
$caller = end($file);
$caller = substr($caller, 0, strpos($caller, '.'));
$class = explode('\\', __CLASS__);
$class = end($class);
$self = false;
if ($caller == $class) {
$self = true;
}
if (!defined('SAVEQUERIES') || !SAVEQUERIES) {
if ($self) return;
return [
'message' => __('Please enable query logging by calling enableQueryLog() before queries ran.', 'fluent-crm'),
'Total Queries Ran' => null,
'Query Logs' => null
];
}
if (!current_user_can('administrator')) {
return [
'message' => __('Oops! You are not able to see query logs.', 'fluent-crm'),
'Total Queries Ran' => null,
'Query Logs' => null
];
}
if (FluentCrm()->request->get('action') == 'heartbeat') {
return;
}
$result = [];
$queries = (array)$GLOBALS['wpdb']->queries;
foreach ($queries as $key => $query) {
$query = array_slice($query, 0, 3);
if ($withStack) {
$stackArray = [];
$stack = explode(', ', $query[2]);
foreach ($stack as $skey => $sValue) {
$stackArray[++$skey] = $sValue;
}
$query[2] = $stackArray;
$result[++$key] = array_combine([
'query', 'execution_time', 'stack'
], $query);
} else {
$result[++$key] = array_combine([
'query', 'execution_time'
], array_slice($query, 0, 2));
}
}
return [
'Total Queries Ran' => count($queries),
'Query Logs' => array_filter($result)
];
}
public function logQueries()
{
if (!static::$logInFile) return;
$result = static::getQueryLog();
if (!$result) return;
error_log('[' . fluentCrmTimestamp() . ']: ' . json_encode(
$result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
) . PHP_EOL, 3, FluentCrm()->path . 'query.log');
}
public static function enableQueryLog($inFile = false)
{
if (!defined('SAVEQUERIES')) {
define('SAVEQUERIES', true);
static::$logInFile = $inFile;
}
}
public static function init()
{
add_action('shutdown', [get_class(), 'logQueries'], 100);
}
}
@@ -0,0 +1,252 @@
<?php
/**
* @var \FluentCrm\Framework\Foundation\Application $app
*/
/*
* Note: Namespace will be added automatically. For example, if you use MyClass
* as the controller name then it will become FluentCrm\App\Hooks\Handlers\MyClass.
*/
// Init scheduled tasks
\FluentCrm\App\Hooks\Handlers\Scheduler::register();
(new \FluentCrm\App\Hooks\Handlers\FluentBlockEditorHandler())->register();
(new \FluentCrm\App\Hooks\Handlers\FluentConditionalContentBlockHandler())->register();
(new \FluentCrm\App\Modules\AbandonCart\AbandonCart())->register();
(new \FluentCrm\App\Hooks\Handlers\AutoSubscribeHandler())->register();
add_action('fluentcrm_contacts_filter_subscriber', function ($query, $filters) {
return (new \FluentCrm\App\Models\Subscriber)->buildGeneralPropertiesFilterQuery($query, $filters);
}, 10, 2);
add_action('fluentcrm_contacts_filter_segment', function ($query, $filters) {
return (new \FluentCrm\App\Models\Subscriber)->buildSegmentFilterQuery($query, $filters);
}, 10, 2);
add_action('fluentcrm_contacts_filter_custom_fields', function ($query, $filters) {
return (new \FluentCrm\App\Models\Subscriber)->buildCustomFieldsFilterQuery($query, $filters);
}, 10, 2);
add_action('fluentcrm_contacts_filter_activities', function ($query, $filters) {
return (new \FluentCrm\App\Models\Subscriber)->buildActivitiesFilterQuery($query, $filters);
}, 10, 2);
// Add admin init
$app->addAction('wp_loaded', 'AdminMenu@init');
$app->addAction('init', 'ExternalPages@route', 99);
$app->addAction('wp_ajax_fluentcrm_unsubscribe_ajax', 'ExternalPages@handleUnsubscribe');
$app->addAction('wp_ajax_nopriv_fluentcrm_unsubscribe_ajax', 'ExternalPages@handleUnsubscribe');
$app->addAction('wp_ajax_fluentcrm_request_unsubscribe_ajax', 'ExternalPages@handleUnsubscribeRequestAjax');
$app->addAction('wp_ajax_nopriv_fluentcrm_request_unsubscribe_ajax', 'ExternalPages@handleUnsubscribeRequestAjax');
$app->addAction('wp_ajax_fluentcrm_manage_preferences_ajax', 'ExternalPages@handleManageSubPref');
$app->addAction('wp_ajax_nopriv_fluentcrm_manage_preferences_ajax', 'ExternalPages@handleManageSubPref');
$app->addAction('wp_ajax_fluentcrm_request_manage_subscription_ajax', 'ExternalPages@handleManageSubRequestAjax');
$app->addAction('wp_ajax_nopriv_fluentcrm_request_manage_subscription_ajax', 'ExternalPages@handleManageSubRequestAjax');
$app->addAction('wp_ajax_fluentcrm_callback_for_background', 'ExternalPages@handleBackgroundProcessCallback');
$app->addAction('wp_ajax_nopriv_fluentcrm_callback_for_background', 'ExternalPages@handleBackgroundProcessCallback');
$app->addAction('wp_ajax_fluent_crm_account_form', 'PrefFormHandler@handleAjax');
$app->addAction('wp_ajax_nopriv_fluent_crm_account_form', 'PrefFormHandler@handleAjax');
// Fallback for funnel sequence save ajax
$app->addAction('wp_ajax_fluentcrm_save_funnel_sequence_ajax', 'FunnelHandler@saveSequences');
$app->addAction('wp_ajax_fluentcrm_export_funnel', 'FunnelHandler@exportFunnel');
$app->addAction('wp_ajax_fluentcrm_save_funnel_email_action', 'FunnelHandler@saveEmailAction');
$app->addAction('wp_ajax_fluentcrm_save_campaign_email_body', 'FunnelHandler@saveCampaignEmail');
/*
* Integrations & Funnels Handler Init
*/
(new \FluentCrm\App\Hooks\Handlers\FunnelHandler())->register();
// FluentCart's modal checkout fires fluent_cart/before_payment_methods and calls die()
// during init at priority 10, before a priority-10 callback can register. Only
// CheckoutSubscription needs to be early — everything else in FluentCart::init() is fine at 10.
add_action('init', function () {
if (defined('FLUENTCART_VERSION')) {
(new \FluentCrm\App\Services\ExternalIntegrations\FluentCart\CheckoutSubscription())->init();
}
}, 1);
// All external integrations (FluentCart::init() runs here too, minus CheckoutSubscription)
add_action('init', function () {
(new \FluentCrm\App\Hooks\Handlers\Integrations())->register();
}, 10);
$app->addAction('fluentcrm_subscriber_status_to_subscribed', 'FunnelHandler@resumeSubscriberFunnels', 1, 2);
/*
* Cleanup Hooks
*/
$app->addAction('fluentcrm_after_subscribers_deleted', 'Cleanup@deleteSubscribersAssets', 10, 1);
$app->addAction('fluent_crm/campaign_deleted', 'Cleanup@deleteCampaignAssets', 10, 1);
$app->addAction('fluent_crm/list_deleted', 'Cleanup@deleteListAssets', 10, 1);
$app->addAction('fluent_crm/tag_deleted', 'Cleanup@deleteTagAssets', 10, 1);
$app->addAction('fluent_crm/campaign_archived', 'Cleanup@archiveCampaignAssets', 10, 1);
$app->addAction('fluent_crm/sync_subscriber_delete_setting', 'Cleanup@SyncSubscriberDeleteSettings', 10, 2);
$app->addAction('fluentcrm_subscriber_status_to_unsubscribed', 'Cleanup@handleUnsubscribe');
$app->addAction('fluentcrm_subscriber_status_to_bounced', 'Cleanup@handleUnsubscribe');
$app->addAction('fluentcrm_subscriber_status_to_complained', 'Cleanup@handleUnsubscribe');
$app->addAction('fluentcrm_subscriber_status_to_spammed', 'Cleanup@handleUnsubscribe');
$app->addAction('fluent_crm/contact_email_changed', 'Cleanup@handleContactEmailChanged');
$app->addAction('delete_user', 'Cleanup@handleUserDelete', 10, 3);
$app->addAction('fluent_crm/company_deleted', 'Cleanup@handleCompanyDelete', 10, 1);
$app->addAction('after_password_reset', 'Cleanup@handleUserPasswordChanged', 10, 1);
add_action('fluent_crm/debug_log', function ($logData) {
if (!is_array($logData) || empty($logData['title'])) {
return;
}
\FluentCrm\App\Services\Helper::debugLog($logData['title'], \FluentCrm\Framework\Support\Arr::get($logData, 'description', ''), \FluentCrm\Framework\Support\Arr::get($logData, 'type', 'info'));
});
/*
* Admin Bar
*/
$app->addAction('admin_bar_menu', 'AdminBar@init');
add_action('wp_ajax_nopriv_fluentcrm-post-campaigns-emails-processing', function () use ($app) {
$campaignId = isset($_REQUEST['campaign_id']) ? intval($_REQUEST['campaign_id']) : 0;
if ($campaignId) {
// Continue processing a specific campaign — skip housekeeping/discovery
\FluentCrm\App\Hooks\Handlers\Scheduler::processCampaignById($campaignId);
} else {
// No campaign ID — run full discovery (backward compat)
\FluentCrm\App\Hooks\Handlers\Scheduler::processFiveMinutes();
}
wp_send_json_success([
'message' => 'success',
'time' => time()
]);
});
/*
* For Short URL Redirect
*/
add_action('wp_loaded', function () use ($app) {
if (isset($_GET['ns_url'])) {
(new \FluentCrm\App\Hooks\Handlers\RedirectionHandler())->redirect($_GET);
}
});
/*
* Contact Activity Logger Class Init
*/
add_action('init', function () {
(new \FluentCrm\App\Hooks\Handlers\ContactActivityLogger())->register();
(new \FluentCrm\App\Hooks\Handlers\ActivityLogHandler())->register();
});
/*
* Setup-wizard
*/
if (!empty($_GET['page']) && 'fluentcrm-setup' == $_GET['page']) {
add_action('admin_menu', function () {
add_dashboard_page('FluentCRM Setup', 'FluentCRM Setup', 'manage_options', 'fluentcrm-setup', function () {
return '';
});
});
add_action('current_screen', function () {
new \FluentCrm\App\Hooks\Handlers\SetupWizard();
}, 999);
}
add_shortcode('fluentcrm_pref', function ($atts, $content) {
return (new \FluentCrm\App\Hooks\Handlers\PrefFormHandler())->handleShortCode($atts, $content);
});
add_shortcode('fluentcrm_content', function ($atts, $content) {
$result = (new \FluentCrm\App\Hooks\Handlers\PrefFormHandler())->handleDynamicContentShortCode($atts, $content);
return wp_kses_post($result);
});
// require the CLI
if (defined('WP_CLI') && WP_CLI) {
\WP_CLI::add_command('fluent_crm', '\FluentCrm\App\Hooks\CLI\Commands');
}
add_action('admin_notices', function () {
if (defined('FLUENTCAMPAIGN_FRAMEWORK_VERSION') && FLUENTCAMPAIGN_FRAMEWORK_VERSION < 3) {
echo '<div class="fc_notice notice notice-error fc_notice_error"><h3>Update FluentCRM Pro Plugin</h3><p>You are using an out-of-date version of FluentCRM Pro. <a href="' . esc_url(admin_url('plugins.php?s=fluentcampaign=pro&plugin_status=all&fluentcrm_pro_check_update=' . time())) . '">' . esc_html__('Please update FluentCRM Pro to latest version', 'fluent-crm') . '</a>.</p></div>';
}
});
/*
* For REST API Nonce Renew
*/
add_action('wp_ajax_fluentcrm_renew_rest_nonce', function () {
if (!\FluentCrm\App\Services\PermissionManager::currentUserPermissions()) {
wp_send_json([
'error' => 'You do not have permission to do this'
], 403);
}
wp_send_json([
'nonce' => wp_create_nonce('wp_rest'),
'time' => time()
], 200);
});
/*
* Add custom CSS for fcrm_notice
*/
add_action('admin_head', function () {
echo '<style>
.fcrm_notice {
background: #ffffff;
border: 1px solid #E1E4EA;
border-left: 3px solid #FB3748;
padding: 10px 12px !important;
border-radius: 8px;
margin-bottom: 5px;
}
</style>';
});
/*
* MCP — Register abilities for the WordPress Abilities API.
*
* Lazy-register guard:
* - On WP < 6.9 (no Abilities API in core) OR sites without the WP MCP Adapter
* plugin active, `wp_register_ability` is undefined — we skip silently.
* - The opt-out option `fluent_crm_mcp_enabled` (default 'yes') lets admins
* disable the entire MCP surface from Settings → MCP without uninstalling
* the adapter.
*
* See `app/Modules/MCP/MCPInit.php` for the registration logic.
*/
add_action('init', function () {
if (!function_exists('wp_register_ability')) {
return;
}
if (fluentcrm_get_option('mcp_enabled', 'yes') !== 'yes') {
return;
}
(new \FluentCrm\App\Modules\MCP\MCPInit())->init();
}, 5);
@@ -0,0 +1,86 @@
<?php
/**
* @var $app \FluentCrm\Framework\Foundation\Application $app
*/
/*
* Note: Namespace will be added automatically. For example, if you use MyClass
* as the controller name then it will become FluentCrm\App\Hooks\Handlers\MyClass.
*/
$app->addFilter('fluent_crm/countries', 'CountryNames@get');
(new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->register();
$app->addFilter('fluent_crm/purchase_history_woocommerce', 'PurchaseHistory@wooOrders', 10, 2);
$app->addFilter('fluent_crm/purchase_history_edd', 'PurchaseHistory@eddOrders', 10, 2);
$app->addFilter('fluent_crm/purchase_history_payform', 'PurchaseHistory@payformSubmissions', 10, 2);
$app->addFilter('fluent_crm/purchase_history_pmpro', 'PurchaseHistory@pmproOrders', 10, 2);
// Fluent Forms Integration
(new \FluentCrm\App\Hooks\Handlers\FormSubmissions())->register();
add_filter('fluent_crm/parse_campaign_email_text', function ($text, $subscriber) {
return \FluentCrm\App\Services\Libs\Parser\Parser::parse($text, $subscriber);
}, 10, 2);
$app->addFilter('fluent_crm/parse_extended_crm_text', function ($text, $subscriber) {
if (!$subscriber) {
return $text;
}
return \FluentCrm\App\Services\Libs\Parser\Parser::parseCrmValue($text, $subscriber);
}, 10, 2);
$app->addFilter('comment_form_submit_field', 'AutoSubscribeHandler@addSubscribeCheckbox', 10, 1);
$app->addFilter('wp_privacy_personal_data_exporters', 'Cleanup@attachCrmExporter');
$app->addFilter('wp_privacy_personal_data_exporters', 'Cleanup@attachCrmExporter');
$app->addFilter('fluent_crm/block_editor_unregister_all_patterns', 'FluentBlockPatternHandler@shouldUnregisterAllPatterns', 10, 3);
$app->addFilter('fluent_crm/block_editor_custom_pattern_categories', 'FluentBlockPatternHandler@addCustomPatternCategories', 10, 1);
$app->addFilter('fluent_crm/block_editor_custom_patterns', 'FluentBlockPatternHandler@addCustomPatterns', 10, 1);
/*
* deprecated Hooks
* @todo: Remove this by January 2023
*/
add_filter('fluentcrm_parse_campaign_email_text', function ($text, $subscriber) {
if (!$subscriber) {
return $text;
}
_deprecated_hook('fluentcrm_parse_campaign_email_text', '2.6.6', 'fluent_crm/parse_campaign_email_text', 'Use fluent_crm/parse_campaign_email_text filter hook instead');
return \FluentCrm\App\Services\Libs\Parser\Parser::parse($text, $subscriber);
}, 10, 2);
$app->addFilter('fluentcrm_email-design-template-plain', function ($emailBody, $templateData, $campaign) {
_deprecated_hook('fluentcrm_email-design-template-plain', '2.6.6', 'fluent_crm/email-design-template-plain', 'Use fluent_crm/email-design-template-plain filter hook instead');
return (new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->addPlainTemplate($emailBody, $templateData, $campaign);
}, 10, 3);
$app->addFilter('fluentcrm_email-design-template-simple', function ($emailBody, $templateData, $campaign) {
_deprecated_hook('fluentcrm_email-design-template-simple', '2.6.6', 'fluent_crm/email-design-template-simple', 'Use fluent_crm/email-design-template-simple filter hook instead');
return (new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->addSimpleTemplate($emailBody, $templateData, $campaign);
}, 10, 3);
$app->addFilter('fluentcrm_email-design-template-classic', function ($emailBody, $templateData, $campaign) {
_deprecated_hook('fluentcrm_email-design-template-classic', '2.6.6', 'fluent_crm/email-design-template-classic', 'Use fluent_crm/email-design-template-classic filter hook instead');
return (new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->addClassicTemplate($emailBody, $templateData, $campaign);
}, 10, 3);
$app->addFilter('fluentcrm_email-design-template-raw_classic', function ($emailBody, $templateData, $campaign) {
_deprecated_hook('fluentcrm_email-design-template-raw_classic', '2.6.6', 'fluent_crm/email-design-template-raw_classic', 'Use fluent_crm/email-design-template-raw_classic filter hook instead');
return (new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->addRawClassicTemplate($emailBody, $templateData, $campaign);
}, 10, 3);
$app->addFilter('fluentcrm_email-design-template-web_preview', function ($emailBody, $templateData, $campaign) {
_deprecated_hook('fluentcrm_email-design-template-web_preview', '2.6.6', 'fluent_crm/email-design-template-web_preview', 'Use fluent_crm/email-design-template-web_preview filter hook instead');
return (new \FluentCrm\App\Hooks\Handlers\EmailDesignTemplates())->addWebPreviewTemplate($emailBody, $templateData, $campaign);
}, 10, 3);
/*
* </deprecated_hooks_end>
*/
@@ -0,0 +1,41 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Models\ActivityLog;
use FluentCrm\Framework\Http\Request\Request;
class ActivityLogController extends Controller
{
/**
* Get all the System Logs
* @param \FluentCrm\Framework\Http\Request\Request $request
* @return array || \WP_REST_Response
*/
public function index(Request $request)
{
$search = sanitize_text_field($request->get('search'));
$logs = ActivityLog::orderBy('id', 'DESC');
if (!empty($search)) {
$logs = $logs->where('action', 'LIKE', "%{$search}%")
->orWhere('description', 'LIKE', "%{$search}%");
}
$logs = $logs->paginate($request->per_page ?: 20);
return [
'logs' => $logs
];
}
public function deleteAll(Request $request)
{
ActivityLog::where('id', '>', 0)->delete();
return [
'message' => __('All activity logs have been deleted', 'fluent-crm')
];
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,489 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Models\Campaign;
use FluentCrm\App\Models\CampaignUrlMetric;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Http\Request\Request;
/**
* CampaignAnalyticsController - REST API Handler Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
class CampaignAnalyticsController extends Controller
{
public function getLinksReport(CampaignUrlMetric $campaignUrlMetric, $campaignId)
{
$campaign = Campaign::withoutGlobalScopes()->findOrFail($campaignId);
$clickStatus = $campaign->settings['click_tracker'] ?? '';
$openStatus = $campaign->settings['open_tracker'] ?? '';
if ($clickStatus === '') {
$clickStatus = fluentcrmTrackClicking();
}
if ($openStatus === '') {
$openStatus = fluentcrmTrackEmailOpen();
}
$links = array_values($campaignUrlMetric->getLinksReport($campaign));
return $this->sendSuccess([
'links' => $links,
'click_status' => $clickStatus,
'open_status' => $openStatus
]);
}
public function getRevenueReport(Request $request, $campaignId)
{
$limit = intval($request->get('per_page', 10));
$offset = (intval($request->get('page', 1)) - 1) * $limit;
$sources = $this->getActiveRevenueSources();
$multiSource = count($sources) > 1;
if (empty($sources)) {
return [
'orders' => [],
'labels' => $this->getRevenueLabels(false),
'total' => 0
];
}
// Build a single newest-first index across every active commerce source so
// pagination spans them all. Within each source, ids stay in DB-newest order.
$index = [];
foreach ($sources as $source) {
foreach ($this->getAttributedOrderIds($source, $campaignId) as $orderId) {
$index[] = ['source' => $source, 'order_id' => (int) $orderId];
}
}
$totalOrders = count($index);
$pageEntries = array_slice($index, $offset, $limit);
$orders = [];
foreach ($pageEntries as $entry) {
$row = $this->formatRevenueRow($entry['source'], $entry['order_id'], $multiSource);
if ($row) {
$orders[] = $row;
}
}
return [
'orders' => $orders,
'labels' => $this->getRevenueLabels($multiSource),
'total' => $totalOrders
];
}
public function getRevenueReSyncReport(Request $request, $campaignId)
{
$sources = $this->getActiveRevenueSources();
if (empty($sources)) {
return [
'message' => __('No revenue found for this campaign', 'fluent-crm')
];
}
$revenueData = ['orderIds' => []];
$primaryCurrency = null;
foreach ($sources as $source) {
$sourceData = $this->reSyncSourceRevenue($source, $campaignId);
foreach ($sourceData['orderIds'] as $oid) {
if (!in_array($oid, $revenueData['orderIds'])) {
$revenueData['orderIds'][] = $oid;
}
}
foreach ($sourceData['totals'] as $currency => $cents) {
if (!isset($revenueData[$currency])) {
$revenueData[$currency] = 0;
if ($primaryCurrency === null) {
$primaryCurrency = $currency;
}
}
$revenueData[$currency] += $cents;
}
}
if (empty($revenueData['orderIds'])) {
return [
'message' => __('No order found to re-sync', 'fluent-crm')
];
}
fluentcrm_update_campaign_meta($campaignId, '_campaign_revenue', $revenueData);
$primaryTotal = $primaryCurrency ? $revenueData[$primaryCurrency] : 0;
return [
'message' => __('Revenue has been re-synced successfully', 'fluent-crm'),
'total' => number_format($primaryTotal / 100, 2)
];
}
/**
* Active commerce sources that participate in campaign revenue attribution.
* Order matters: it determines display precedence within the merged report.
*/
protected function getActiveRevenueSources()
{
$sources = [];
if (defined('WC_PLUGIN_FILE')) {
$sources[] = 'woo';
}
if (Helper::isEdd3()) {
$sources[] = 'edd';
}
if (defined('FLUENTCART_VERSION')) {
$sources[] = 'fct';
}
return $sources;
}
/**
* Lightweight index query — returns just order IDs attributed to this campaign,
* newest-first per source. Used both for paginated report rendering and re-sync.
*/
protected function getAttributedOrderIds($source, $campaignId)
{
if ($source === 'woo') {
if (Helper::isWooHposEnabled()) {
return fluentCrmDb()->table('wc_orders_meta')
->where('meta_key', '_fc_cid')
->where('meta_value', $campaignId)
->orderBy('id', 'DESC')
->get()
->pluck('order_id')
->map(function ($orderId) {
return intval($orderId);
})
->all();
}
return fluentCrmDb()->table('postmeta')
->where('meta_key', '_fc_cid')
->where('meta_value', $campaignId)
->orderBy('meta_id', 'DESC')
->get()
->pluck('post_id')
->map(function ($orderId) {
return intval($orderId);
})
->all();
}
if ($source === 'edd') {
/*
* EDD 3 writes order attribution meta to edd_ordermeta via the
* order meta API. Do not read legacy postmeta/edd_payment records.
*/
return fluentCrmDb()->table('edd_ordermeta')
->where('meta_key', '_fc_cid')
->where('meta_value', $campaignId)
->orderBy('meta_id', 'DESC')
->get()
->pluck('edd_order_id')
->map(function ($orderId) {
return intval($orderId);
})
->all();
}
if ($source === 'fct') {
return fluentCrmDb()->table('fct_order_meta')
->where('meta_key', '_fc_cid')
->where('meta_value', $campaignId)
->orderBy('id', 'DESC')
->get()
->pluck('order_id')
->map(function ($orderId) {
return intval($orderId);
})
->all();
}
return [];
}
/**
* Sum NET revenue per currency for one source — i.e. only orders in a successful
* (paid/completed) status, with refunded amounts subtracted. Returns
* `['orderIds' => [int...], 'totals' => ['usd' => cents, ...]]`.
* Orders that net to zero or below (fully refunded, cancelled, pending) are skipped
* so they don't pollute the order list with non-revenue rows.
*/
protected function reSyncSourceRevenue($source, $campaignId)
{
$result = ['orderIds' => [], 'totals' => []];
$orderIds = $this->getAttributedOrderIds($source, $campaignId);
if (!$orderIds) {
return $result;
}
if ($source === 'woo') {
$paidStatuses = function_exists('wc_get_is_paid_statuses') ? wc_get_is_paid_statuses() : ['processing', 'completed'];
$currency = strtolower(get_woocommerce_currency());
foreach ($orderIds as $orderId) {
$order = wc_get_order($orderId);
if (!$order || !$order->get_id()) {
continue;
}
if (!in_array($order->get_status(), $paidStatuses, true)) {
continue;
}
$netCents = intval(((float) $order->get_total() - (float) $order->get_total_refunded()) * 100);
if ($netCents <= 0) {
continue;
}
$result['orderIds'][] = (int) $order->get_id();
$result['totals'][$currency] = ($result['totals'][$currency] ?? 0) + $netCents;
}
return $result;
}
if ($source === 'edd') {
// EDD 3 keeps canonical status and refund data in order tables.
$completeStatuses = ['complete', 'completed', 'partially_refunded'];
foreach ($orderIds as $orderId) {
$payment = new \EDD_Payment($orderId);
if (!$payment || !$payment->ID) {
continue;
}
if (!in_array($payment->status, $completeStatuses, true)) {
continue;
}
$netTotal = function_exists('edd_get_order_total')
? edd_get_order_total($payment->ID)
: $payment->total;
$netCents = intval(((float) $netTotal) * 100);
if ($netCents <= 0) {
continue;
}
$currency = strtolower(edd_get_payment_currency_code($payment->ID) ?: 'usd');
$result['orderIds'][] = (int) $payment->ID;
$result['totals'][$currency] = ($result['totals'][$currency] ?? 0) + $netCents;
}
return $result;
}
if ($source === 'fct') {
// Canonical "successful" set: paid, partially_paid, partially_refunded.
// Net revenue subtracts total_refund below so partial refunds still contribute.
$successStatuses = \FluentCart\App\Helpers\Status::getOrderPaymentSuccessStatuses();
$orders = \FluentCart\App\Models\Order::query()
->whereIn('id', $orderIds)
->whereIn('payment_status', $successStatuses)
->get();
foreach ($orders as $order) {
$netCents = (int) $order->total_amount - (int) ($order->total_refund ?? 0);
if ($netCents <= 0) {
continue;
}
$currency = strtolower($order->currency ?: 'usd');
$result['orderIds'][] = (int) $order->id;
$result['totals'][$currency] = ($result['totals'][$currency] ?? 0) + $netCents;
}
return $result;
}
return $result;
}
/**
* Render a single order row for the merged revenue table. The `source` key
* is added when more than one commerce platform is contributing data.
*/
protected function formatRevenueRow($source, $orderId, $multiSource)
{
$row = null;
if ($source === 'woo') {
$row = $this->formatWooOrderRow($orderId);
} else if ($source === 'edd') {
$row = $this->formatEddOrderRow($orderId);
} else if ($source === 'fct') {
$row = $this->formatFluentCartOrderRow($orderId);
}
if (!$row) {
return null;
}
if ($multiSource) {
$row = ['source' => $this->getSourceLabel($source)] + $row;
}
return $row;
}
protected function getSourceLabel($source)
{
$labels = [
'woo' => 'WooCommerce',
'edd' => 'EDD',
'fct' => 'FluentCart',
];
return $labels[$source] ?? $source;
}
protected function getRevenueLabels($multiSource)
{
$labels = [
'order' => '#',
'title' => __('Customer', 'fluent-crm'),
'status' => __('Status', 'fluent-crm'),
'date' => __('Date', 'fluent-crm'),
'total' => __('Total', 'fluent-crm'),
'action' => __('View', 'fluent-crm'),
];
if ($multiSource) {
$labels = ['source' => __('Source', 'fluent-crm')] + $labels;
}
return $labels;
}
protected function formatWooOrderRow($orderId)
{
$order = wc_get_order($orderId);
if (!$order || !$order->get_id()) {
return null;
}
/* translators: 1: billing first name, 2: billing last name */
$buyer = trim(sprintf(_x('%1$s %2$s', 'full name', 'fluent-crm'), $order->get_billing_first_name(), $order->get_billing_last_name()));
$order_timestamp = $order->get_date_created() ? $order->get_date_created()->getTimestamp() : '';
if (!$order_timestamp) {
$show_date = '&ndash;';
} else if ($order_timestamp > strtotime('-1 day', time()) && $order_timestamp <= time()) {
$show_date = sprintf(
/* translators: %s: human-readable time difference */
_x('%s ago', '%s = human-readable time difference', 'fluent-crm'),
human_time_diff($order->get_date_created()->getTimestamp(), time())
);
} else {
/**
* Determine the date format for displaying the order creation date in the WooCommerce admin in FluentCRM.
*
* @param string The date format to be used. Default is 'M j, Y'.
* @param string The context for the date format. Default is 'woocommerce'.
* @since 2.2.0
*/
$show_date = $order->get_date_created()->date_i18n(apply_filters('woocommerce_admin_order_date_format', __('M j, Y', 'fluent-crm')));
}
$editUrl = admin_url('post.php?post=' . absint($order->get_id()) . '&action=edit');
return [
'order' => '#' . esc_html($order->get_order_number()),
'title' => '<a href="' . esc_url($editUrl) . '" class="order-view"><strong>' . esc_html($buyer) . '</strong></a>',
'status' => wc_get_order_status_name($order->get_status()),
'date' => $show_date,
'total' => $order->get_formatted_order_total(),
'action' => '<a href="' . esc_url($editUrl) . '">' . esc_html__('View', 'fluent-crm') . '</a>',
];
}
protected function formatEddOrderRow($orderId)
{
$payment = new \EDD_Payment($orderId);
if (!$payment || !$payment->ID) {
return null;
}
$orderActionHtml = '<a href="' . add_query_arg('id', $payment->ID, admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details')) . '">' . esc_html__('View', 'fluent-crm') . '</a>';
$amount = !empty($payment->total) ? $payment->total : 0;
$customer_id = edd_get_payment_customer_id($payment->ID);
if (!empty($customer_id)) {
$customer = new \EDD_Customer($customer_id);
$customerName = '<a href="' . esc_url(admin_url("edit.php?post_type=download&page=edd-customers&view=overview&id=$customer_id")) . '">' . esc_html($customer->name) . '</a>';
} else {
$email = edd_get_payment_user_email($payment->ID);
$customerName = '<a href="' . esc_url(admin_url("edit.php?post_type=download&page=edd-payment-history&s=$email")) . '">' . esc_html__('(customer missing)', 'fluent-crm') . '</a>';
}
return [
'order' => '#' . $payment->number,
'title' => $customerName,
'status' => $payment->status_nicename,
'date' => date_i18n(get_option('date_format'), strtotime($payment->date)),
'total' => edd_currency_filter(edd_format_amount($amount), edd_get_payment_currency_code($payment->ID)),
'action' => $orderActionHtml,
];
}
protected function formatFluentCartOrderRow($orderId)
{
$order = \FluentCart\App\Models\Order::with('customer')->find($orderId);
if (!$order) {
return null;
}
$customerName = '';
if ($order->customer) {
$customerName = trim($order->customer->first_name . ' ' . $order->customer->last_name);
if (!$customerName) {
$customerName = $order->customer->email;
}
}
$orderUrl = admin_url('admin.php?page=fluent-cart#/orders/' . $order->id . '/view');
return [
'order' => '#' . ($order->invoice_no ?: $order->id),
'title' => '<a target="_blank" rel="noopener" href="' . esc_url($orderUrl) . '">' . esc_html($customerName) . '</a>',
'status' => esc_html(\FluentCrm\App\Services\Helper::getStatusText($order->status)),
'date' => date_i18n(get_option('date_format'), strtotime($order->created_at)),
'total' => \FluentCart\App\Helpers\Helper::toDecimal($order->total_amount, true, $order->currency),
'action' => '<a target="_blank" rel="noopener" href="' . esc_url($orderUrl) . '">' . esc_html__('View', 'fluent-crm') . '</a>',
];
}
public function getUnsubscribers(Request $request, $campaignId)
{
$unsubscribes = CampaignUrlMetric::with('subscriber')
->where('campaign_id', $campaignId)
->where('type', 'unsubscribe')
->paginate();
foreach ($unsubscribes as $unsubscribe) {
$unsubscribe->subscriber->reason = $unsubscribe->subscriber->unsubscribeReason();
}
return [
'unsubscribes' => $unsubscribes
];
}
public function getSegmentedContacts(Request $request, $campaignId)
{
$campaign = Campaign::findOrFail($campaignId);
$contactsModel = $campaign->getSubscribersModel();
$search = $request->getSafe('search', 'sanitize_text_field');
if ($search) {
$contactsModel->searchBy($search);
}
if ($orderBy = $request->getSafe('sort_by', 'sanitize_sql_orderby', 'id')) {
$orderType = $request->getSafe('sort_type', 'sanitize_sql_orderby', 'desc');
$contactsModel->orderBy($orderBy, $orderType);
}
$contacts = $contactsModel->with(['lists', 'tags'])->paginate();
return [
'subscribers' => $contacts
];
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,924 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Http\Controllers\Controller;
use FluentCrm\App\Models\Company;
use FluentCrm\App\Models\CompanyNote;
use FluentCrm\App\Models\CustomCompanyField;
use FluentCrm\App\Models\Subscriber;
use FluentCrm\App\Models\SubscriberNote;
use FluentCrm\App\Services\AutoSubscribe;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Services\Libs\FileSystem;
use FluentCrm\App\Services\Sanitize;
use FluentCrm\Framework\Http\Request\Request;
use FluentCrm\Framework\Support\Arr;
use FluentCrm\Framework\Support\Collection;
class CompanyController extends Controller
{
public function index(Request $request)
{
$order = [
'by' => $request->getSafe('sort_by', 'sanitize_sql_orderby', 'id'),
'order' => $request->getSafe('sort_order', 'sanitize_sql_orderby', 'DESC')
];
$companies = Company::orderBy($order['by'], $order['order'])
->with(['owner'])
->searchBy($request->getSafe('search', 'sanitize_text_field'));
$inlineFilters = $request->get('inline_filters', []);
if ($inlineFilters && is_array($inlineFilters)) {
$inlineFilters = array_filter($inlineFilters);
foreach ($inlineFilters as $key => $values) {
if (!is_array($values)) {
continue;
}
$values = array_map('sanitize_text_field', $values);
if ($key == 'company_categories') {
$companies->whereIn('industry', $values);
} else if ($key == 'company_types') {
$companies->whereIn('type', $values);
}
}
}
$companies = $companies->paginate();
foreach ($companies as $company) {
$company->contacts_count = $company->getContactsCount();
}
return [
'companies' => $companies
];
}
public function searchCompanies(Request $request)
{
$search = $request->getSafe('search', 'sanitize_text_field');
$companies = Company::orderBy('name', 'ASC')
->searchBy($search);
$subscriberId = $request->getSafe('subscriber_id', 'intval');
if ($subscriberId) {
$companies = $companies->doesnthave('subscribers', 'and', function ($query) use ($subscriberId) {
$query->where('fc_subscribers.id', $subscriberId);
});
}
$companies = $companies->limit(50)->get();
$formatted = [];
$values = (array)$request->get('values', []);
$pushedIds = [];
foreach ($companies as $company) {
$pushedIds[] = $company->id;
$formatted[] = [
'id' => $company->id,
'name' => $company->name,
'email' => $company->email,
'logo' => $company->logo,
'phone' => $company->phone,
'website' => $company->website
];
}
if ($values && $newIds = array_diff($values, $pushedIds)) {
$newItems = Company::whereIn('id', $newIds)
->get();
foreach ($newItems as $item) {
$formatted[] = [
'id' => $item->id,
'name' => $item->name,
'email' => $item->email,
'logo' => $item->logo,
'phone' => $item->phone,
'website' => $item->website
];
}
}
return [
'results' => $formatted,
'has_more' => Company::count() >= 50
];
}
public function searchUnattachedContacts(Request $request)
{
$search = $request->getSafe('search', 'sanitize_text_field');
$companyId = $request->getSafe('company_id', 'intval', '');
$contacts = Subscriber::orderBy('id', 'DESC')
->searchBy($search)
->whereDoesntHave('companies', function ($query) use ($companyId) {
$query->where('fc_companies.id', $companyId);
})
->limit($request->getSafe('limit', 'intval', 20))
->get();
return [
'results' => $contacts
];
}
public function attachSubscribers(Request $request)
{
$subscriberIds = $request->get('subscriber_ids');
$companyIds = $request->get('company_ids');
$result = FluentCrmApi('companies')->attachContactsByIds($subscriberIds, $companyIds);
if (!$result) {
return $this->sendError('Invalid data', 422);
}
return [
'message' => __('Selected Companies have been attached successfully', 'fluent-crm'),
'companies' => $result['companies']
];
}
public function detachSubscribers(Request $request)
{
$subscriberIds = $request->get('subscriber_ids');
$companyIds = $request->get('company_ids');
$result = FluentCrmApi('companies')->detachContactsByIds($subscriberIds, $companyIds);
if (!$result) {
return $this->sendError('Invalid data', 422);
}
$result['message'] = __('Company has been successfully detached', 'fluent-crm');
return $result;
}
/**
* Find a company.
*/
public function find(Request $request, $id)
{
$findBy = $request->getSafe('find_by', 'sanitize_text_field', 'id');
$findByValue = $request->getSafe('find_by_value', 'sanitize_text_field');
$customFindBys = ['name', 'email', 'phone'];
if (in_array($findBy, $customFindBys)) {
$company = Company::where($findBy, $findByValue)->first();
if (!$company) {
return $this->sendError('Company not found', 422);
}
} else {
$company = Company::findOrFail($id);
}
$company->load(['owner']);
if ($company->owner) {
$company->owner->stats = $company->owner->stats();
}
$company->contacts_count = $company->getContactsCount();
return [
'company' => $company
];
}
/**
* Store a company.
* @param Request $request
* @return \WP_REST_Response | array
*/
public function create(Request $request)
{
$allData = $request->all();
$allData = $this->validate($allData, [
'name' => 'required|unique:fc_companies,name'
]);
$data = $this->getSanitizedData($allData);
if (empty($data['logo']) && !empty($allData['website']) && Helper::isExperimentalEnabled('company_auto_logo')) {
$data['logo'] = $this->getLogoWebsiteUrl($allData['website']);
}
$company = FluentCrmApi('companies')->createOrUpdate($data);
if ($contactId = $request->getSafe('intended_contact_id', 'intval')) {
$contact = Subscriber::find($contactId);
if ($contact) {
$contact->attachCompanies([$company->id]);
if (!$contact->company_id) {
$contact->company_id = $company->id;
$contact->save();
}
}
}
return [
'message' => __('Company has been created successfully', 'fluent-crm'),
'company' => $company
];
}
public function update(Request $request, $id = 0)
{
if ($id == 0) {
return $this->create($request);
}
$company = Company::findOrFail($id);
$allData = $request->all();
$name = sanitize_text_field($allData['name']);
if (Company::where('id', '!=', $id)->where('name', $name)->first()) {
return $this->sendError([
'message' => __('Company name already exists. Please use a different company name', 'fluent-crm')
], 422);
}
$data = $this->getSanitizedData($allData);
$company = FluentCrmApi('companies')->createOrUpdate($data);
return [
'message' => __('Company has been updated', 'fluent-crm'),
'company' => $company
];
}
public function updateProperty()
{
$column = $this->request->getSafe('property', 'sanitize_text_field');
$value = $this->request->getSafe('value', 'sanitize_text_field');
$companyIds = $this->request->get('companies');
if (!is_array($companyIds)) {
$companyIds = [$companyIds];
}
$companyIds = array_map('intval', $companyIds);
$companyIds = array_filter($companyIds);
$validColumns = ['type', 'logo', 'owner_id', 'refetch_logo'];
$types = Helper::companyTypes();
$statuses = Helper::companyTypes();
$this->validate([
'column' => $column,
'value' => $value,
'company_ids' => $companyIds
], [
'column' => 'required',
'value' => 'required',
'company_ids' => 'required'
]);
if (!in_array($column, $validColumns)) {
return $this->sendError([
'message' => __('Column is not valid', 'fluent-crm')
]);
}
if ($column == 'type' && !in_array($value, $types)) {
return $this->sendError([
'message' => __('Value is not valid', 'fluent-crm')
]);
} else if ($column == 'status' && !in_array($value, $statuses)) {
return $this->sendError([
'message' => __('Value is not valid', 'fluent-crm')
]);
}
$companies = Company::whereIn('id', $companyIds)->get();
foreach ($companies as $company) {
if ($column == 'refetch_logo') {
$newLogo = $this->getLogoWebsiteUrl($company->website);
if ($newLogo) {
$company->logo = $newLogo;
$company->save();
return [
'message' => __('Logo has been updated successfully', 'fluent-crm'),
'updated_logo' => $newLogo
];
}
return $this->sendError([
'message' => __('Sorry, we could not find the logo from website. Please upload manually', 'fluent-crm')
]);
}
$oldValue = $company->{$column};
if ($oldValue != $value) {
$company->{$column} = $value;
$company->save();
if (in_array($column, ['type', 'status', 'owner_id'])) {
do_action('fluent_crm/company_' . $column . '_to_' . $value, $company, $oldValue);
}
}
}
return $this->sendSuccess([
'message' => __('Company successfully updated', 'fluent-crm')
]);
}
public function delete(Request $request, $id)
{
$company = Company::findOrFail($id);
do_action('fluent_crm/before_company_delete', $company);
$company->delete();
do_action('fluent_crm/company_deleted', $id);
return [
'message' => __('Company has been deleted successfully', 'fluent-crm')
];
}
public function handleBulkActions(Request $request)
{
$actionName = sanitize_text_field($request->get('action_name', ''));
$companyIds = array_map('intval', $request->get('company_ids', []));
$companyIds = array_filter($companyIds);
$lastId = $request->get('last_id', 0);
if (!$companyIds) {
$companyQuery = Company::orderBy('id', 'ASC')
->searchBy($request->getSafe('search', 'sanitize_text_field'));
$inlineFilters = $request->get('company_query.inline_filters', []);
if ($inlineFilters && is_array($inlineFilters)) {
$inlineFilters = array_filter($inlineFilters);
foreach ($inlineFilters as $key => $values) {
if (!is_array($values)) {
continue;
}
$values = array_map('sanitize_text_field', $values);
if ($key == 'company_categories') {
$companyQuery->whereIn('industry', $values);
} else if ($key == 'company_types') {
$companyQuery->whereIn('type', $values);
}
}
}
$companyQuery = $companyQuery->limit(50)
->where('id', '>', $lastId);
} else {
$companyQuery = Company::whereIn('id', $companyIds);
}
$companies = $companyQuery->get();
if ($companies->isEmpty()) {
return [
'is_completed' => true,
'completed_companies' => 0,
'message' => __('All companies have been processed', 'fluent-crm')
];
}
$companyIds = $companyQuery->pluck('id')->toArray();
$lastCompanyId = end($companyIds);
if ($actionName == 'delete_companies') {
foreach ($companies as $company) {
$id = $company->id;
do_action('fluent_crm/before_company_delete', $company);
$company->delete();
do_action('fluent_crm/company_deleted', $id);
}
return $this->sendSuccess([
'last_company_id' => $lastCompanyId,
'completed_companies' => count($companyIds),
'message' => __('Selected Companies have been deleted permanently', 'fluent-crm'),
]);
} elseif ($actionName == 'change_company_status') {
$newStatus = sanitize_text_field($request->get('new_status', ''));
if (!$newStatus) {
return $this->sendError([
'message' => __('Please select status', 'fluent-crm')
]);
}
foreach ($companies as $company) {
$oldStatus = $company->status;
if ($oldStatus != $newStatus) {
$company->status = $newStatus;
$company->save();
do_action('fluent_crm/company_status_to_' . $newStatus, $company, $oldStatus);
}
}
return [
'last_company_id' => $lastCompanyId,
'completed_companies' => count($companyIds),
'message' => __('Status has been changed for the selected companies', 'fluent-crm')
];
} else if ($actionName == 'change_company_type') {
$newType = sanitize_text_field($request->get('new_status', ''));
if (!$newType) {
return $this->sendError([
'message' => __('Please select new type', 'fluent-crm')
]);
}
foreach ($companies as $company) {
$oldType = $company->type;
if ($oldType != $newType) {
$company->type = $newType;
$company->save();
do_action('fluent_crm/company_type_to_' . $newType, $company, $oldType);
}
}
return [
'last_company_id' => $lastCompanyId,
'completed_companies' => count($companyIds),
'message' => __('Company Type has been updated for the selected companies', 'fluent-crm')
];
} else if ($actionName == 'change_company_category') {
$newCategory = sanitize_text_field($request->get('new_status', ''));
if (!$newCategory) {
return $this->sendError([
'message' => __('Please select new category', 'fluent-crm')
]);
}
foreach ($companies as $company) {
$oldCategory = $company->industry;
if ($oldCategory != $newCategory) {
$company->industry = $newCategory;
$company->save();
do_action('fluent_crm/company_category_to_' . $newCategory, $company, $oldCategory);
}
}
return [
'last_company_id' => $lastCompanyId,
'completed_companies' => count($companyIds),
'message' => __('Company Category has been updated for the selected companies', 'fluent-crm')
];
}
return [
'last_company_id' => $lastCompanyId,
'completed_companies' => count($companyIds),
'message' => __('Selected bulk action has been successfully completed', 'fluent-crm')
];
}
private function getSanitizedData($allData)
{
$rules = [
'name' => 'required'
];
if (Arr::get($allData, 'website')) {
$allData['website'] = $this->makeHttpUrl($allData['website']);
$rules['website'] = 'url';
}
if (Arr::get($allData, 'linkedin_url')) {
$allData['linkedin_url'] = $this->makeHttpUrl($allData['linkedin_url']);
$rules['linkedin_url'] = 'url';
}
if (Arr::get($allData, 'facebook_url')) {
$allData['facebook_url'] = $this->makeHttpUrl($allData['facebook_url']);
$rules['facebook_url'] = 'url';
}
if (Arr::get($allData, 'twitter_url')) {
$allData['twitter_url'] = $this->makeHttpUrl($allData['twitter_url']);
$rules['twitter_url'] = 'url';
}
$allData = $this->validate($allData, $rules);
$data = Sanitize::company($allData);
return Arr::only($data, array_keys($allData));
}
private function makeHttpUrl($url)
{
if (!$url) {
return $url;
}
$parsed_url = wp_parse_url($url);
if (!$parsed_url || empty($parsed_url['scheme'])) {
$url = 'https://' . $url;
}
return $url;
}
/**
* Returns true only if the URL resolves to a public, routable IP address.
* Blocks private/reserved ranges to prevent SSRF attacks.
*/
private function isSSRFSafeUrl($url)
{
$parsed = wp_parse_url($url);
if (!$parsed || empty($parsed['host'])) {
return false;
}
$scheme = strtolower($parsed['scheme'] ?? '');
if (!in_array($scheme, ['http', 'https'])) {
return false;
}
$host = $parsed['host'];
// Strip IPv6 brackets if present
$host = trim($host, '[]');
// If it looks like a raw IP, validate directly; otherwise resolve the hostname
if (filter_var($host, FILTER_VALIDATE_IP)) {
$ip = $host;
} else {
$ip = gethostbyname($host);
// gethostbyname() returns the original string on failure
if ($ip === $host && !filter_var($ip, FILTER_VALIDATE_IP)) {
return false;
}
}
// Reject private, loopback, link-local, and other reserved ranges
return (bool) filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
private function getLogoWebsiteUrl($url)
{
if (!$url) {
return NULL;
}
$url = $this->makeHttpUrl($url);
if (!$this->isSSRFSafeUrl($url)) {
return NULL;
}
$response = wp_remote_get($url, [
'sslverify' => false, // Disable SSL verification to avoid 403 Forbidden error
'timeout' => 10, // Set a timeout of 10 seconds
'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' // Set a User-Agent header to avoid 403 Forbidden error
]);
// Check for errors in the response
if (is_wp_error($response)) {
return NULL;
}
// Extract the HTML content from the response
$html = wp_remote_retrieve_body($response);
preg_match('/<link rel="apple-touch-icon"(?:.*?)href="([^"]+)"/i', $html, $matches);
// Use regular expressions to find the logo image URL
if (!isset($matches[1])) {
preg_match('/<link rel="(?:shortcut|icon)"(?:.*?)href="([^"]+)"/i', $html, $matches);
}
// If a logo URL is found, download the image to the uploads directory
if (isset($matches[1])) {
$logoUrl = $matches[1];
// Resolve relative URLs against the base domain
if (!preg_match('/^https?:\/\//i', $logoUrl)) {
$parsedBase = wp_parse_url($url);
$baseOrigin = ($parsedBase['scheme'] ?? 'https') . '://' . ($parsedBase['host'] ?? '');
$logoUrl = $baseOrigin . '/' . ltrim($logoUrl, '/');
}
$extension = strtolower(substr($logoUrl, strrpos($logoUrl, '.') + 1));
if (!in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'ico'])) {
return NULL;
}
// Block SSRF on the logo URL too (the link tag href may point to a different host)
if (!$this->isSSRFSafeUrl($logoUrl)) {
return NULL;
}
$uploadDir = wp_upload_dir(); // Get the uploads directory
$filename = md5($url . time()) . '-' . basename($logoUrl); // Get the filename from the URL
$filepath = $uploadDir['basedir'] . '/fluentcrm/' . $filename; // Combine the uploads directory path with the filename
// Download the image using wp_remote_get() and save it to the uploads directory
$image = wp_remote_get($logoUrl, [
'timeout' => 10, // Set a timeout of 10 seconds
'sslverify' => false // Disable SSL verification to avoid 403 Forbidden error
]);
if (!is_wp_error($image)) {
// Check if the downloaded file is actually an image
$headers = wp_remote_retrieve_headers($image);
$imageBody = wp_remote_retrieve_body($image);
if (defined('FILEINFO_MIME_TYPE') && class_exists('\finfo')) {
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$content_type = $finfo->buffer($imageBody);
} else {
$content_type = wp_remote_retrieve_header($headers, 'content-type');
if (!$content_type) {
$content_type = Arr::get($headers, 'content-type');
}
if (strpos($content_type, 'image/') !== 0) {
return null;
}
// Temporary file to validate the image
$tmpFilePath = tempnam(sys_get_temp_dir(), 'tmpimg');
file_put_contents($tmpFilePath, $imageBody);
$imgSize = getimagesize($tmpFilePath);
wp_delete_file($tmpFilePath);
if (!$imgSize) {
return null;
}
}
if (strpos($content_type, 'image/') === 0) {
global $wp_filesystem;
if (!$wp_filesystem) {
require_once(ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
FileSystem::setCustomUploadDir([
'baseurl' => $uploadDir['baseurl'],
'basedir' => $uploadDir['basedir'],
]);
$wp_filesystem->put_contents($filepath, $imageBody);
// Return the URL of the saved image
return $uploadDir['baseurl'] . FLUENTCRM_UPLOAD_DIR . '/' . $filename;
} else {
// If the downloaded file is not an image, delete the file and return null
wp_delete_file($filepath);
}
}
}
// If no logo URL is found, or if an error occurs, or if the downloaded file is not an image, return null
return NULL;
}
public function getNotes()
{
$companyId = $this->request->get('id');
$search = $this->request->get('search');
$includeId = intval($this->request->get('include_id', 0));
$notes = CompanyNote::where('subscriber_id', $companyId);
if (!empty($search)) {
global $wpdb;
$notes = $notes->where('title', 'LIKE', '%' . $wpdb->esc_like(sanitize_text_field($search)) . '%');
}
$notes = $notes->orderBy('id', 'DESC')
->paginate();
foreach ($notes as $note) {
$note->added_by = $note->createdBy();
}
$fields['fields'] = Helper::getNoteSyncFields();
$response = [
'notes' => $notes,
'fields' => $fields
];
if ($includeId) {
$noteIds = (new Collection($notes->items()))->pluck('id')->toArray();
if (!in_array($includeId, $noteIds)) {
$includedNote = CompanyNote::where('id', $includeId)
->where('subscriber_id', $companyId)
->first();
if ($includedNote) {
$includedNote->added_by = $includedNote->createdBy();
$response['included_note'] = $includedNote;
}
}
}
return $this->sendSuccess($response);
}
public function addNote(Request $request, $id)
{
$company = Company::findOrFail($id);
$note = $this->validate($request->get('note'), [
'title' => 'required',
'description' => 'required',
'type' => 'required',
'created_at' => 'nullable|date'
]);
if (empty($note['created_at'])) {
$note['created_at'] = current_time('mysql');
}
$note['subscriber_id'] = $id;
$note = Sanitize::contactNote($note);
$subscriberNote = CompanyNote::create(wp_unslash($note));
/**
* Subscriber's Note Added
*
* @param SubscriberNote $subscriberNote Note Model.
* @param Subscriber $subscriber Contact Model.
* @param array $note Contact Note Data Array.
* @since 1.0
*/
do_action('fluent_crm/company_note_added', $subscriberNote, $company, $note);
return $this->sendSuccess([
'note' => $subscriberNote,
'message' => __('Note has been successfully added', 'fluent-crm')
]);
}
public function updateNote(Request $request, $id, $noteId)
{
$company = Company::findOrFail($id);
$note = $this->validate($request->get('note'), [
'title' => 'required',
'description' => 'required',
'type' => 'required',
'created_at' => 'sometimes|date'
]);
$note = Arr::only(wp_unslash($note), ['title', 'description', 'type', 'created_at']);
if (empty($note['created_at'])) {
unset($note['created_at']);
}
$note = Sanitize::contactNote($note);
$companyNote = CompanyNote::findOrFail($noteId);
$companyNote->fill($note);
$companyNote->save();
/**
* Subscriber's Note Updated
*
* @param CompanyNote $companyNote Note Model.
* @param Company $company Contact Model.
* @param array $note Contact Note Data Array.
* @since 1.0
*/
do_action('fluent_crm/company_note_updated', $companyNote, $company, $note);
return $this->sendSuccess([
'note' => $companyNote,
'message' => __('Note successfully updated', 'fluent-crm')
]);
}
public function deleteNote($id, $noteId)
{
$company = Company::findOrFail($id);
CompanyNote::where('id', $noteId)->delete();
/**
* Subscriber's Note Delete
*
* @param int $noteId Note ID.
* @param Company $company Company Model.
* @since 1.0
*/
do_action('fluent_crm/company_note_deleted', $noteId, $company);
return $this->sendSuccess([
'message' => __('Note successfully deleted', 'fluent-crm')
]);
}
public function bulkDeleteNotes(Request $request, $id)
{
$company = Company::findOrFail($id);
$noteIds = array_filter(array_map('intval', (array) $request->get('note_ids', [])));
if (empty($noteIds)) {
return $this->sendError([
'message' => __('No note IDs provided', 'fluent-crm')
]);
}
if (count($noteIds) > 200) {
return $this->sendError([
'message' => __('Too many notes selected. Please delete 200 or fewer notes at a time.', 'fluent-crm')
]);
}
// Scope delete to this company so users cannot delete notes belonging to other companies.
$deletableNoteIds = CompanyNote::where('subscriber_id', $company->id)
->whereIn('id', $noteIds)
->pluck('id')
->toArray();
$deletedCount = 0;
if ($deletableNoteIds) {
$deletedCount = CompanyNote::whereIn('id', $deletableNoteIds)->delete();
foreach ($deletableNoteIds as $deletedNoteId) {
do_action('fluent_crm/company_note_deleted', $deletedNoteId, $company);
}
}
return $this->sendSuccess([
'message' => sprintf(
/* translators: %d: number of deleted notes */
_n('%d note deleted', '%d notes deleted', $deletedCount, 'fluent-crm'),
$deletedCount
)
]);
}
public function getCustomGlobalFields(CustomCompanyField $model)
{
return $this->sendSuccess(
$model->getGlobalFields(
$this->request->get('with', [])
)
);
}
public function saveCustomGlobalFields(CustomCompanyField $model)
{
$fields = $model->saveGlobalFields(
Helper::parseArrayOrJson($this->request->get('fields'))
);
return $this->sendSuccess([
'fields' => $fields,
'message' => __('Fields saved successfully!', 'fluent-crm')
]);
}
public function updateCustomFieldGroupName(CustomCompanyField $model)
{
$oldName = sanitize_text_field($this->request->get('old_name'));
$newName = sanitize_text_field($this->request->get('new_name'));
$updatedCustomFields = $model->updateGroupName($oldName, $newName);
return $this->sendSuccess([
'fields' => $updatedCustomFields,
'message' => __('Group name updated successfully!', 'fluent-crm')
]);
}
public function getCompanyExternalView(Request $request, $companyId)
{
$company = Company::findOrFail($companyId);
$sectionId = $request->get('section_provider');
return apply_filters('fluent_crm/company_profile_section_' . $sectionId, [
'heading' => '',
'content_html' => ''
], $company);
}
public function saveExternalViewData(Request $request, $companyId)
{
$company = Company::findOrFail($companyId);
$sectionId = $request->get('section_provider');
$response = apply_filters('fluent_crm/company_profile_section_save_' . $sectionId, '', $request->get('data', []), $company);
if (!$response) {
return $this->sendError([
'message' => __('Handler could not be found.', 'fluent-crm')
]);
}
return $response;
}
}
@@ -0,0 +1,103 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\App;
use FluentCrm\Framework\Validator\ValidationException;
use FluentCrm\Framework\Validator\Validator;
/**
* abstract REST API Controller Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
abstract class Controller
{
/**
* @var \FluentCrm\App\App
*/
protected $app = null;
/**
* @var \FluentCrm\Framework\Http\Request\Request
*/
protected $request = null;
/**
* @var \FluentCrm\Framework\Http\Response\Response
*/
protected $response = null;
public function __construct()
{
$this->app = App::getInstance();
$this->request = $this->app['request'];
$this->response = $this->app['response'];
}
public function validate($data, $rules, $messages = [])
{
$validator = new Validator($data, $rules, $messages);
if ($validator->validate()->fails()) {
// Sanitize validation error messages before returning them
$errors = $validator->errors();
if (is_array($errors)) {
array_walk_recursive($errors, function (&$value) {
if (is_string($value)) {
$value = sanitize_text_field($value);
}
});
}
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Sanitization is already done above
throw new ValidationException(
esc_html__('Unprocessable Entity!', 'fluent-crm'),
422,
null,
$errors
);
}
return $data;
}
public function send($data = null, $code = 200)
{
return $this->response->send($data, $code);
}
public function sendSuccess($data = null, $code = 200)
{
return $this->response->sendSuccess($data, $code);
}
public function sendError($data = null, $code = 422)
{
return $this->response->sendError($data, $code);
}
public function validationErrors($data = null, $code = 422)
{
if ($data instanceof ValidationException) {
$data = $data->errors();
}
// Sanitize error payload before sending the response to prevent unescaped output
if (is_array($data)) {
array_walk_recursive($data, function (&$value) {
if (is_string($value)) {
$value = sanitize_text_field($value);
}
});
} elseif (is_string($data)) {
$data = sanitize_text_field($data);
}
return $this->sendError($data, $code);
}
}
@@ -0,0 +1,494 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Models\Company;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Services\Libs\FileSystem;
use FluentCrm\App\Services\Sanitize;
use FluentCrm\Framework\Support\Arr;
use FluentCrm\Framework\Http\Request\Request;
use FluentCrm\App\Models\Subscriber;
/**
* CsvController - REST API Handler Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
class CsvController extends Controller
{
/**
* @param \FluentCrm\Framework\Http\Request\Request $request
* @return \WP_REST_Response
* @throws \FluentCrm\Framework\Validator\ValidationException
*/
public function upload(Request $request)
{
if (is_multisite()) {
add_filter('upload_mimes', function ($types) {
if (empty($types['csv'])) {
$types['csv'] = 'text/csv';
}
return $types;
});
}
$files = $this->validate($this->request->files(), [
'file' => 'mimetypes:' . implode(',', fluentcrmCsvMimes())
], [
'file.mimetypes' => __('The file must be a valid CSV.', 'fluent-crm')
]);
$delimeter = $request->get('delimiter', 'comma');
if ($delimeter == 'comma') {
$delimeter = ',';
} else {
$delimeter = ';';
}
$uploadedFiles = FileSystem::put($files);
try {
$csv = $this->getCsvReader(FileSystem::get($uploadedFiles[0]['file']));
$csv->setDelimiter($delimeter);
$headers = $csv->fetchOne();
} catch (\Exception $exception) {
return $this->sendError([
'message' => $exception->getMessage()
]);
}
if (count($headers) != count(array_unique($headers))) {
return $this->sendError([
'message' => __('Looks like your csv has same name header multiple times. Please fix your csv first and remove any duplicate header column', 'fluent-crm')
]);
}
if ($request->get('type') == 'company') {
$mappables = Company::mappables();
} else {
$mappables = Subscriber::mappables();
}
$headerItems = array_values(array_filter($headers));
$subscriberColumns = array_keys($mappables);
$maps = [];
$customFields = fluentcrm_get_custom_contact_fields();
$fieldsMap = [];
if ($customFields) {
foreach ($customFields as $field) {
$fieldsMap[$field['slug']] = $field['label'];
}
}
foreach ($headerItems as $headerItem) {
$tableMap = (in_array($headerItem, $subscriberColumns)) ? $headerItem : null;
if (!$tableMap) {
$santizedItem = str_replace(' ', '_', strtolower($headerItem));
if (in_array($santizedItem, $subscriberColumns)) {
$tableMap = $santizedItem;
}
}
if (!empty($fieldsMap) && in_array($headerItem, $fieldsMap)) {
$tableMap = array_search($headerItem, $fieldsMap);
}
$maps[] = [
'csv' => $headerItem,
'table' => $tableMap
];
}
if ($request->get('type') == 'company') {
/**
* Determine the columns of the company table in FluentCRM.
*
* This filter allows you to modify the columns of the company table in the CSV export.
*
* @since 2.8.0
*
* @param array $subscriberColumns An array of default subscriber columns.
*/
$columns = apply_filters(
'fluent_crm/company_table_columns', $subscriberColumns
);
} else {
/**
* Determine the columns of the subscriber table in FluentCRM.
*
* This filter allows you to modify the columns displayed in the subscriber table.
*
* @since 2.8.0
*
* @param array $subscriberColumns An array of default subscriber table columns.
*/
$columns = apply_filters(
'fluent_crm/subscriber_table_columns', $subscriberColumns
);
}
return $this->send([
'file' => $uploadedFiles[0]['file'],
'headers' => $headerItems,
'fields' => $mappables,
'columns' => $columns,
'map' => $maps
]);
}
public function import()
{
$inputs = $this->request->only([
'map', 'tags', 'lists', 'file', 'update', 'new_status', 'double_optin_email', 'import_silently', 'force_update_status'
]);
if (Arr::get($inputs, 'import_silently') == 'yes') {
if (!defined('FLUENTCRM_DISABLE_TAG_LIST_EVENTS')) {
define('FLUENTCRM_DISABLE_TAG_LIST_EVENTS', true);
}
}
$forceStatusChange = Arr::get($inputs, 'force_update_status') == 'yes';
$delimeter = $this->request->get('delimiter', 'comma');
if ($delimeter == 'comma') {
$delimeter = ',';
} else {
$delimeter = ';';
}
$status = $inputs['new_status'];
try {
$reader = $this->getCsvReader(FileSystem::get($inputs['file']));
$reader->setDelimiter($delimeter);
if (method_exists($reader, 'getRecords')) {
$aHeaders = $reader->fetchOne(0);
$allRecords = $reader->getRecords($aHeaders);
if (!is_array($allRecords)) {
$allRecords = iterator_to_array($allRecords, true);
}
unset($allRecords[0]);
$allRecords = array_values($allRecords);
} else {
$aHeaders = $reader->fetchOne(0);
$allRecords = $reader->fetchAssoc($aHeaders);
if (!is_array($allRecords)) {
$allRecords = iterator_to_array($allRecords, true);
}
unset($allRecords[0]);
$allRecords = array_values($allRecords);
}
} catch (\Exception $exception) {
return $this->sendError([
'message' => $exception->getMessage()
]);
}
$page = $this->request->get('importing_page', 1);
$processPerRequest = apply_filters('fluent_crm/csv_import_contact_limit_per_request', 100);
$offset = ($page - 1) * $processPerRequest;
$records = array_slice($allRecords, $offset, $processPerRequest);
$customFieldKeys = $this->customFieldKeys();
$subscribers = [];
$skipped = [];
$isCompanyEnabled = Helper::isCompanyEnabled();
foreach ($records as $record) {
if (!array_filter($record)) {
continue;
}
$subscriber = [
'custom_values' => []
];
foreach ($inputs['map'] as $map) {
if (!$map['table']) {
continue;
}
if (isset($map['csv'], $map['table'])) {
if (in_array($map['table'], ['tags', 'lists'])) {
//if tags or lists are mapped to be imported
if ($map['table'] == 'tags') {
$subscriber['tags'] = !empty($record[$map['csv']]) ? explode(',', $record[$map['csv']]) : [];
} else {
$subscriber['lists'] = !empty($record[$map['csv']]) ? explode(',', $record[$map['csv']]) : [];
}
}
else if (in_array($map['table'], $customFieldKeys)) {
$subscriber['custom_values'][$map['table']] = $record[$map['csv']];
} else {
$subscriber[$map['table']] = $record[$map['csv']];
}
}
}
if (!array_key_exists('email', $subscriber)) {
return $this->sendError(['email' => __('The email field is required.', 'fluent-crm')], 422);
}
$subscriber['email'] = is_string($subscriber['email']) ? trim($subscriber['email']) : $subscriber['email'];
if ($subscriber['email'] && is_email($subscriber['email'])) {
if (isset($subscriber['company_id']) && $subscriber['company_id'] && $isCompanyEnabled) {
$companyNameOrId = $subscriber['company_id'];
if (is_string($companyNameOrId)) {
$company = Company::query()->firstOrCreate([
'name' => $subscriber['company_id']
], [
'name' => $subscriber['company_id']
]);
if ($company) {
$subscriber['company_id'] = $company->id;
} else {
unset($subscriber['company_id']);
}
} else {
$company = Company::find($subscriber['company_id']);
if (!$company) {
unset($subscriber['company_id']);
}
}
}
$subscribers[] = Sanitize::contact($subscriber);
} else {
$skipped[] = $subscriber;
}
}
if (!isset($inputs['tags'])) {
$inputs['tags'] = [];
}
if (!isset($inputs['lists'])) {
$inputs['lists'] = [];
}
$sendDoubleOptin = Arr::get($inputs, 'double_optin_email') == 'yes';
$result = Subscriber::import(
$subscribers, $inputs['tags'], $inputs['lists'], $inputs['update'], $status, $sendDoubleOptin, $forceStatusChange, 'csv'
);
$totalSkipped = count($result['skips']) + count($skipped);
$completed = $offset + count($records);
$totalCount = count($allRecords);
$hasMore = $completed < $totalCount;
if (!$hasMore) {
FileSystem::delete($inputs['file']);
}
return $this->sendSuccess([
'total' => $totalCount,
'completed' => $completed,
'total_page' => ceil($totalCount / $processPerRequest),
'skipped' => $totalSkipped,
'invalid_contacts' => $skipped,
'skipped_contacts' => $result['skips'],
'invalid_email_counts' => count($skipped),
'inserted' => count($result['inserted']),
'updated' => count($result['updated']),
'has_more' => $hasMore,
'last_page' => $page,
'tags' => $inputs['tags'],
'lists' => $inputs['lists'],
'offset' => $offset,
'result' => $result
]);
}
public function importCompanies()
{
$inputs = $this->request->only([
'map', 'file', 'update', 'create_owner'
]);
$delimeter = $this->request->get('delimiter', 'comma');
if ($delimeter == 'comma') {
$delimeter = ',';
} else {
$delimeter = ';';
}
try {
$reader = $this->getCsvReader(FileSystem::get($inputs['file']));
$reader->setDelimiter($delimeter);
if (method_exists($reader, 'getRecords')) {
$aHeaders = $reader->fetchOne(0);
$allRecords = $reader->getRecords($aHeaders);
if (!is_array($allRecords)) {
$allRecords = iterator_to_array($allRecords, true);
}
unset($allRecords[0]);
$allRecords = array_values($allRecords);
} else {
$aHeaders = $reader->fetchOne(0);
$allRecords = $reader->fetchAssoc($aHeaders);
if (!is_array($allRecords)) {
$allRecords = iterator_to_array($allRecords, true);
}
unset($allRecords[0]);
$allRecords = array_values($allRecords);
}
} catch (\Exception $exception) {
return $this->sendError([
'message' => $exception->getMessage()
]);
}
$page = $this->request->get('importing_page', 1);
$processPerRequest = 100;
$offset = ($page - 1) * $processPerRequest;
$records = array_slice($allRecords, $offset, $processPerRequest);
$willCreateOwner = $this->request->get('create_owner') == 'yes';
$willUpdate = $this->request->get('update') == 'yes';
$customFields = fluentcrm_get_custom_company_fields();
$companies = [];
$skipped = [];
foreach ($records as $record) {
if (!array_filter($record)) {
continue;
}
$company = [];
foreach ($inputs['map'] as $map) {
if (!$map['table']) {
continue;
}
if (isset($map['csv'], $map['table'])) {
$company[$map['table']] = trim($record[$map['csv']]);
}
}
if (empty($company['name'])) {
return $this->sendError(['email' => __('The company name field is required.', 'fluent-crm')], 422);
}
if (!$willUpdate) {
// check if exists
if (Company::where('name', $company['name'])->first()) {
$skipped[] = $company;
continue;
}
}
if ($customFields) {
$customValues = [];
foreach ($company as $dataKey => $dataValue) {
if (strpos($dataKey, '_custom_') === 0) {
$customKey = str_replace('_custom_', '', $dataKey);
$customValues[$customKey] = $dataValue;
unset($company[$dataKey]);
}
}
$company['custom_values'] = $customValues;
}
$company = Sanitize::company($company);
if (!empty($company['owner_email']) && is_email($company['owner_email'])) {
$ownerEmail = sanitize_email($company['owner_email']);
} else {
$ownerEmail = null;
}
if ($ownerEmail) {
$owner = FluentCrmApi('contacts')->getContact($ownerEmail);
if ($owner) {
$company['owner_id'] = $owner->id;
} else if ($willCreateOwner) {
$owner = FluentCrmApi('contacts')->createOrUpdate([
'full_name' => sanitize_text_field(Arr::get($company, 'owner_name')),
'email' => $ownerEmail,
'status' => 'subscribed'
]);
if ($owner) {
$company['owner_id'] = $owner->id;
}
}
}
$createdCompany = FluentCrmApi('companies')->createOrUpdate($company);
$companies[] = $createdCompany;
}
$completed = $offset + count($companies);
$totalCount = count($allRecords);
$hasMore = $completed < $totalCount;
if (!$hasMore) {
FileSystem::delete($inputs['file']);
}
return $this->sendSuccess([
'total' => $totalCount,
'completed' => count($companies),
'total_page' => ceil($totalCount / $processPerRequest),
'skipped' => count($skipped),
'has_more' => $hasMore,
'last_page' => $page,
'offset' => $offset
]);
}
protected function customFieldKeys()
{
$fields = fluentcrm_get_option('contact_custom_fields', []);
$keys = [];
foreach ($fields as $field) {
$keys[] = $field['slug'];
}
return $keys;
}
private function getCsvReader($file)
{
if (!class_exists(' \League\Csv\Reader')) {
include FLUENTCRM_PLUGIN_PATH . 'app/Services/Libs/csv/autoload.php';
}
return \League\Csv\Reader::createFromString($file);
}
}
@@ -0,0 +1,51 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Models\CustomContactField;
use FluentCrm\App\Services\Helper;
/**
* CustomContactFieldsController - REST API Handler Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
class CustomContactFieldsController extends Controller
{
public function getGlobalFields(CustomContactField $model)
{
return $this->sendSuccess(
$model->getGlobalFields(
$this->request->get('with', [])
)
);
}
public function saveGlobalFields(CustomContactField $model)
{
$fields = $model->saveGlobalFields(
Helper::parseArrayOrJson($this->request->get('fields'))
);
return $this->sendSuccess([
'fields' => $fields,
'message' => __('Fields saved successfully!', 'fluent-crm')
]);
}
public function updateGroupName(CustomContactField $model)
{
$oldName = sanitize_text_field($this->request->get('old_name'));
$newName = sanitize_text_field($this->request->get('new_name'));
$updatedCustomFields = $model->updateGroupName($oldName, $newName);
return $this->sendSuccess([
'fields' => $updatedCustomFields,
'message' => __('Group name updated successfully!', 'fluent-crm')
]);
}
}
@@ -0,0 +1,268 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Models\CampaignEmail;
use FluentCrm\App\Services\Helper;
use FluentCrm\App\Services\Stats;
use FluentCrm\Framework\Support\Arr;
/**
* DashboardController - REST API Handler Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
class DashboardController extends Controller
{
public function getStats(Stats $stats)
{
$overallStats = $stats->getCounts();
$nextMinuteTask = Helper::getNextMinuteTaskTimeStamp();
$notices = [];
if ((time() - $nextMinuteTask) > 120) {
$notices[] = '<div class=""><b>Attention: </b> Looks like the scheduled cron jobs are not running timely. Please consider setup server side cron. <a href="' . admin_url('admin.php?page=fluentcrm-admin#/settings/settings_tools') . '">Click here to check the status</a></div>';
}
$systemTips = '';
$emailsCount = Arr::get($overallStats, 'email_sent.count', 0);
if ($emailsCount > 400000) {
$lastEmail = CampaignEmail::orderBy('id', 'ASC')->first();
if ($lastEmail && strtotime($lastEmail->created_at) < strtotime('-120 days')) {
$emailsCount = number_format($emailsCount, 0);
$sysBody = '<div class="fc_system_tips">';
/* translators: %s: number of emails in the database */
$sysBody .= '<p>' . sprintf(__('You have %s email history in the database. Consider cleaning up old email history to speed up your next email campaign.', 'fluent-crm'), $emailsCount) . '</p>';
$sysBody .= '<a href="' . fluentcrm_menu_url_base('settings/settings_tools') . '" class="el-button fcrm_primary_btn">' . __('View Data Cleanup', 'fluent-crm') . '</a>';
$sysBody .= '</div>';
$systemTips = [
'title' => __('Database Cleanup Suggestion', 'fluent-crm'),
'body' => $sysBody,
];
}
}
/**
* Define the FluentCRM dashboard notices.
*
* This filter allows modification of the notices displayed on the FluentCRM dashboard.
*
* @since 2.8.40
*
* @param array $notices An array of notices to be displayed on the dashboard.
*/
$notices = apply_filters('fluent_crm/dashboard_notices', $notices);
/**
* Define the dashboard data for FluentCRM.
*
* @since 2.9.23
*
* @param array {
* The dashboard data array.
*
* @type array $stats Overall statistics.
* @type array $sales Sales statistics.
* @type array $dashboard_notices Notices to be displayed on the dashboard.
* @type array $onboarding Onboarding statistics.
* @type array $quick_links Quick links for the dashboard.
* @type array $ff_config FluentForm configuration.
* @type array $recommendation Recommendations for the user.
* @type array $system_tips System tips for the user.
* }
*/
return apply_filters('fluent_crm/dashboard_data', [
'stats' => $overallStats,
/**
* Determine the FluentCRMsales statistics data.
*
* This filter allows modification of the sales statistics data before it is used.
*
* @since 2.7.0
*
* @param array An array of sales statistics data.
*/
'sales' => apply_filters('fluent_crm/sales_stats', []),
'dashboard_notices' => $notices,
'onboarding' => $stats->getOnboardingStat(),
'quick_links' => $stats->getQuickLinks(),
'ff_config' => [
'is_installed' => defined('FLUENTFORM'),
'create_form_link' => admin_url('admin.php?page=fluent_forms#add=1')
],
'recommendation' => $this->recommendation(),
'system_tips' => $systemTips,
'recent_contacts' => $stats->getRecentContacts(3),
'active_automations' => $stats->getActiveAutomations(3),
'recent_campaigns' => $stats->getRecentCampaigns(3),
'triggers' => $this->getTriggers()
]);
}
private function recommendation()
{
if (defined('FLUENTCAMPAIGN')) {
return false;
}
$recommendations = [];
if (defined('WC_PLUGIN_FILE')) {
$recommendations[] = [
'provider' => 'WooCommerce',
'title' => __('Do more with WooCommerce + FluentCRM', 'fluent-crm'),
'description' => __('Integrate FluentCRM with WooCommerce and segment your customers by purchase behavior, send super targeted emails, onboarding emails, cross promotions and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/woocommerce-marketing-automation/',
'base_title' => __('Supercharge your WooCommerce store by upgrading FluentCRM Pro', 'fluent-crm')
];
$recommendations[] = [
'provider' => 'WooCommerce',
'title' => __('Do more with WooCommerce + FluentCRM', 'fluent-crm'),
'description' => __('Integrate FluentCRM with WooCommerce and segment your customers by purchase behavior, send super targeted emails, onboarding emails, cross promotions and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/woocommerce-marketing-automation/',
'base_title' => __('Supercharge your WooCommerce store by upgrading FluentCRM Pro', 'fluent-crm')
];
}
if (Helper::isEdd3()) {
$recommendations[] = [
'provider' => 'EDD',
'title' => __('Do more with EDD + FluentCRM', 'fluent-crm'),
'description' => __('Integrate FluentCRM with Easy Digital Downloads and segment your customers by purchase behavior, send super targeted emails, onboarding emails, cross promotions and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/easy-digital-downloads-integration-fluentcrm/',
'base_title' => __('Supercharge your Digital Downloads store by upgrading FluentCRM Pro', 'fluent-crm')
];
}
if (defined('LLMS_PLUGIN_FILE')) {
$recommendations[] = [
'provider' => 'LifterLMS',
'title' => __('Do more with LifterLMS + FluentCRM', 'fluent-crm'),
'description' => __('Integrate LifterLMS with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/lifterlms/',
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
$recommendations[] = [
'provider' => 'LifterLMS',
'title' => __('Do more with LifterLMS + FluentCRM', 'fluent-crm'),
'description' => __('Integrate LifterLMS with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/lifterlms/',
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (defined('LEARNDASH_VERSION')) {
$recommendations[] = [
'provider' => 'LearnDash',
'title' => __('Do more with LearnDash + FluentCRM', 'fluent-crm'),
'description' => __('Integrate LearnDash with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/learndash-integration-fluentcrm/',
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
$recommendations[] = [
'provider' => 'LearnDash',
'title' => __('Do more with LearnDash + FluentCRM', 'fluent-crm'),
'description' => __('Integrate LearnDash with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/integrations/learndash-integration-fluentcrm/',
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (defined('TUTOR_VERSION')) {
$recommendations[] = [
'provider' => 'TutorLMS',
'title' => __('Do more with TutorLMS + FluentCRM', 'fluent-crm'),
'description' => __('Integrate TutorLMS with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/docs/tutorlms-integration-with-fluentcrm/',
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (defined('LP_PLUGIN_FILE')) {
$recommendations[] = [
'provider' => 'LearnPress',
'title' => __('Do more with LearnPress + FluentCRM', 'fluent-crm'),
'description' => __('Integrate LearnPress with FluentCRM and segment your students by courses, send super targeted emails, onboarding emails, cross promote more courses and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'learn_more' => 'https://fluentcrm.com/docs/learpress-integration-with-fluentcrm/',
'base_title' => __('Supercharge your LMS by upgrading FluentCRM Pro', 'fluent-crm')
];
}
if (defined('PMPRO_VERSION')) {
$recommendations[] = [
'provider' => 'PaidMembership Pro',
'title' => __('Do more with PaidMembership Pro + FluentCRM', 'fluent-crm'),
'description' => __('Integrate PaidMembership Pro with FluentCRM and segment your members by membership levels, send super targeted emails, onboarding emails, cross promote more levels and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your Membership Site by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (defined('WLM3_PLUGIN_VERSION')) {
$recommendations[] = [
'provider' => 'Wishlist Member',
'title' => __('Do more with Wishlist Member + FluentCRM', 'fluent-crm'),
'description' => __('Integrate Wishlist Member with FluentCRM and segment your members by membership levels, send super targeted emails, onboarding emails, cross promote more levels and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your Membership Site by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (defined('MEPR_PLUGIN_NAME')) {
$recommendations[] = [
'provider' => 'MemberPress',
'title' => __('Do more with MemberPress + FluentCRM', 'fluent-crm'),
'description' => __('Integrate MemberPress with FluentCRM and segment your members by membership levels, send super targeted emails, onboarding emails, cross promote more levels and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your Membership Site by upgrading FluentCRM Pro', 'fluent-crm')
];
} else if (class_exists('\Restrict_Content_Pro')) {
$recommendations[] = [
'provider' => 'Restrict Content Pro',
'title' => __('Do more with Restrict Content Pro + FluentCRM', 'fluent-crm'),
'description' => __('Integrate Restrict Content Pro with FluentCRM and segment your members by membership levels, send super targeted emails, onboarding emails, cross promote more levels and many more.', 'fluent-crm'),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your Membership Site by upgrading FluentCRM Pro', 'fluent-crm')
];
}
if (defined('BP_REQUIRED_PHP_VERSION') && function_exists('\buddypress')) {
$title = defined('BP_PLATFORM_VERSION') ? 'BuddyBoss' : 'BuddyPress';
$recommendations[] = [
'provider' => $title,
/* translators: %s: plugin name (BuddyBoss or BuddyPress) */
'title' => sprintf(__('Do more with %s + FluentCRM', 'fluent-crm'), $title),
/* translators: %s: plugin name (BuddyBoss or BuddyPress) */
'description' => sprintf(__('Integrate %s with FluentCRM and segment your members by different group, send super targeted emails, onboarding emails, cross promote more groups and many more.', 'fluent-crm'), $title),
'btn_text' => __('Upgrade to Pro', 'fluent-crm'),
'base_title' => __('Supercharge your Community Site by upgrading FluentCRM Pro', 'fluent-crm')
];
}
if (!$recommendations) {
return false;
}
return $recommendations[array_rand($recommendations)];
}
private function getTriggers()
{
/**
* Determine the list of funnel triggers in FluentCRM.
*
* This filter allows you to modify the array of funnel triggers.
*
* @since 1.0.0
*
* @param array An array of funnel triggers.
*/
return apply_filters('fluentcrm_funnel_triggers', []);
}
}
@@ -0,0 +1,195 @@
<?php
namespace FluentCrm\App\Http\Controllers;
use FluentCrm\App\Services\Helper;
use FluentCrm\Framework\Http\Request\Request;
use FluentCrm\Framework\Support\Arr;
/**
* DocsController - REST API Handler Class
*
* REST API Handler
*
* @package FluentCrm\App\Http
*
* @version 1.0.0
*/
class DocsController extends Controller
{
private $restApi = 'https://fluentcrm.com/wp-json/wp/v2/';
public function index()
{
$formattedDocs = $this->getDocsPerChunk($this->restApi . 'docs?per_page=100', 'fluentcrm_all_docs');
$moreDocs = $this->getDocsPerChunk($this->restApi . 'docs?per_page=100&offset=100', 'fluentcrm_all_docs_2');
if ($moreDocs) {
$formattedDocs = array_merge($formattedDocs, $moreDocs);
}
return [
'docs' => $formattedDocs
];
}
public function getDoc($docId)
{
$request = wp_remote_get($this->restApi . 'docs/' . $docId);
if (is_wp_error($request)) {
return [
'content' => 'sorry, we could not fetch the doc at this moment. Please try again',
'is_error' => true
];
}
$doc = json_decode(wp_remote_retrieve_body($request), true);
return [
'title' => sanitize_text_field($doc['title']['rendered']),
'content' => links_add_target(Helper::sanitizeHtml($doc['content']['rendered'])),
'link' => esc_url($doc['link']),
'id' => $doc['id']
];
}
public function getAddons(Request $request)
{
$canAutoInstallToolkit = (bool) apply_filters('fluent_toolkit/can_auto_install', false);
$toolkitPluginFile = 'fluent-toolkit/fluent-toolkit.php';
$toolkitLoaded = defined('FLUENT_TOOLKIT_VERSION');
$toolkitPluginExists = $this->isPluginInstalled($toolkitPluginFile);
$toolkitActionText = __('Get FluentHub from GitHub', 'fluent-crm');
if ($canAutoInstallToolkit) {
$toolkitActionText = $toolkitPluginExists ? __('Activate FluentHub', 'fluent-crm') : __('Install FluentHub', 'fluent-crm');
}
$addOns = [
'fluentform' => [
'title' => __('Fluent Forms', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluentform.png'),
'is_installed' => defined('FLUENTFORM'),
'learn_more_url' => 'https://wordpress.org/plugins/fluentform/',
'settings_url' => admin_url('admin.php?page=fluent_forms'),
'action_text' => $this->isPluginInstalled('fluent-form/fluent-form.php') ? __('Activate Fluent Forms', 'fluent-crm') : __('Install Fluent Forms', 'fluent-crm'),
'description' => __('Collect leads and build any type of forms, accept payments, connect with your CRM with the Fastest Contact Form Builder Plugin for WordPress', 'fluent-crm')
],
'fluentsmtp' => [
'title' => __('Fluent SMTP', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-smtp.svg'),
'is_installed' => defined('FLUENTMAIL'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-smtp/',
'settings_url' => admin_url('options-general.php?page=fluent-mail#/'),
'action_text' => $this->isPluginInstalled('fluent-smtp/fluent-smtp.php') ? __('Activate Fluent SMTP', 'fluent-crm') : __('Install Fluent SMTP', 'fluent-crm'),
'description' => __('The Ultimate SMTP and SES Plugin for WordPress. Connect with any SMTP, SendGrid, Mailgun, SES, Sendinblue, PepiPost, Google, Microsoft and more.', 'fluent-crm')
],
'fluent-support' => [
'title' => __('Fluent Support', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-support.svg'),
'is_installed' => defined('FLUENT_SUPPORT_VERSION'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-support/',
'settings_url' => admin_url('admin.php?page=fluent-support#/'),
'action_text' => $this->isPluginInstalled('fluent-support/fluent-support.php') ? __('Activate Fluent Support', 'fluent-crm') : __('Install Fluent Support', 'fluent-crm'),
'description' => __('WordPress Helpdesk and Customer Support Ticket Plugin. Provide awesome support and manage customer queries right from your WordPress dashboard.', 'fluent-crm')
],
'fluent-cart' => [
'title' => __('Fluent Cart', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-cart-dark.svg'),
'is_installed' => defined('FLUENTCART_VERSION'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-cart/',
'settings_url' => admin_url('admin.php?page=fluent-cart#/'),
'action_text' => $this->isPluginInstalled('fluent-cart/fluent-cart.php') ? __('Activate Fluent Cart', 'fluent-crm') : __('Install Fluent Cart', 'fluent-crm'),
'description' => __('WordPress eCommerce and Shopping Cart Plugin. Build an online store and manage products, orders, and customers right from your WordPress dashboard.', 'fluent-crm')
],
'fluent-boards' => [
'title' => __('Fluent Boards', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-boards.svg'),
'is_installed' => defined('FLUENT_BOARDS'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-boards/',
'settings_url' => admin_url('admin.php?page=fluent-boards#/'),
'action_text' => $this->isPluginInstalled('fluent-boards/fluent-boards.php') ? __('Activate Fluent Boards', 'fluent-crm') : __('Install Fluent Boards', 'fluent-crm'),
'description' => __('WordPress Project Management and Collaboration Plugin. Manage projects, tasks, and team collaboration right from your WordPress dashboard.', 'fluent-crm')
],
'fluent-community' => [
'title' => __('Fluent Community', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-community.svg'),
'is_installed' => defined('FLUENT_COMMUNITY_PLUGIN_VERSION'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-community/',
'settings_url' => admin_url('admin.php?page=fluent-community#/'),
'action_text' => $this->isPluginInstalled('fluent-community/fluent-community.php') ? __('Activate Fluent Community', 'fluent-crm') : __('Install Fluent Community', 'fluent-crm'),
'description' => __('WordPress Forum and Community Plugin. Build a thriving online community and discussion forum right from your WordPress dashboard.', 'fluent-crm')
],
'fluent-booking' => [
'title' => __('Fluent Booking', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-booking.svg'),
'is_installed' => defined('FLUENT_BOOKING_VERSION'),
'learn_more_url' => 'https://wordpress.org/plugins/fluent-booking/',
'settings_url' => admin_url('admin.php?page=fluent-booking#/'),
'action_text' => $this->isPluginInstalled('fluent-booking/fluent-booking.php') ? __('Activate Fluent Booking', 'fluent-crm') : __('Install Fluent Booking', 'fluent-crm'),
'description' => __('WordPress Appointment Booking Plugin. Manage appointments, bookings, and customer scheduling right from your WordPress dashboard.', 'fluent-crm')
],
'fluent-toolkit' => [
'title' => __('FluentHub', 'fluent-crm'),
'logo' => fluentCrmMix('images/fluent-toolkit.svg'),
'is_installed' => $toolkitLoaded,
'learn_more_url' => 'https://github.com/WPManageNinja/fluent-toolkit',
'settings_url' => admin_url('admin.php?page=fluent-toolkit'),
'action_text' => $toolkitActionText,
'install_route' => $canAutoInstallToolkit ? 'mcp/install-adapter' : '',
'install_url' => $canAutoInstallToolkit ? '' : 'https://github.com/WPManageNinja/fluent-toolkit',
'description' => __('FluentCRM ships AI agent tools, but they only become available once FluentHub is installed and active.', 'fluent-crm')
]
];
$data = [
'addons' => $addOns
];
if (in_array('experimental_features', $request->get('with', []))) {
$data['experimental_features'] = Helper::getExperimentalSettings();
}
return $data;
}
private function isPluginInstalled($plugin)
{
return file_exists(WP_PLUGIN_DIR . '/' . $plugin);
}
private function getDocsPerChunk($url, $chunkKey)
{
return fluentCrmGetFromCache($chunkKey, function () use ($url) {
$request = wp_remote_get($url);
if (is_wp_error($request)) {
return [];
}
$docs = json_decode(wp_remote_retrieve_body($request), true);
$formattedDocs = [];
foreach ($docs as $doc) {
if (empty($doc['title'])) {
continue;
}
$primaryCategory = Arr::get($doc, 'taxonomy_info.doc_category.0', ['value' => 'none', 'label' => 'Other']);
$formattedDocs[] = [
'title' => sanitize_text_field($doc['title']['rendered']),
'content' => links_add_target(Helper::sanitizeHtml($doc['content']['rendered'])),
'link' => esc_url($doc['link']),
'category' => wp_kses_post_deep($primaryCategory)
];
}
return $formattedDocs;
}, WEEK_IN_SECONDS);
}
}

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