Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
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.
{description}
Copyright (C) {year} {fullname}
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,471 @@
<?php
namespace AIOSEO\TableOfContents\Admin;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles all general admin code.
*
* @since 1.0.0
*/
class Admin {
/**
* The main page slug.
*
* @since 1.0.0
*
* @var string
*/
private $pageSlug = 'table-of-contents';
/**
* The current page.
* This gets set as soon as we've identified that we're on a Table of Contents Plus page.
*
* @since 1.0.0
*
* @var string
*/
private $currentPage = '';
/**
* An list of asset slugs to use.
*
* @since 1.0.0
*
* @var array
*/
private $assetSlugs = [
'pages' => 'src/vue/pages/{page}/main.js'
];
/**
* The plugin basename.
*
* @since 1.1.0
*
* @var string
*/
public $plugin = '';
/**
* The list of pages.
*
* @since 1.2.0
*
* @var array
*/
private $pages = [];
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
if ( ! is_admin() ) {
return;
}
add_action( 'admin_menu', [ $this, 'registerMenu' ] );
add_action( 'admin_menu', [ $this, 'hideScheduledActionsMenu' ], 999 );
add_filter( 'language_attributes', [ $this, 'addDirAttribute' ], 3000 );
add_filter( 'plugin_row_meta', [ $this, 'registerRowMeta' ], 10, 2 );
add_filter( 'plugin_action_links_' . AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME, [ $this, 'registerActionLinks' ], 10, 2 );
add_action( 'admin_footer', [ $this, 'addAioseoModalPortal' ] );
}
/**
* Checks whether the current page is a Table of Contents Plus page.
*
* @since 1.0.0
*
* @return bool Whether the current page is a Table of Contents Plus page.
*/
public function isTableOfContentsPage() {
return ! empty( $this->currentPage );
}
/**
* Add the dir attribute to the HTML tag.
*
* @since 1.0.0
*
* @param string $output The HTML language attribute.
* @return string The modified HTML language attribute.
*/
public function addDirAttribute( $output ) {
if ( is_rtl() || preg_match( '/dir=[\'"](ltr|rtl|auto)[\'"]/i', (string) $output ) ) {
return $output;
}
return 'dir="ltr" ' . $output;
}
/**
* Registers the menu.
*
* @since 1.0.0
*
* @return void
*/
public function registerMenu() {
$hook = add_menu_page(
__( 'Table of Contents Plus', 'table-of-contents-plus' ),
__( 'ToC+', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug,
[ $this, 'renderMenuPage' ],
'data:image/svg+xml;base64,' . base64_encode( $this->getMenuIcon() )
);
add_action( "load-{$hook}", [ $this, 'checkCurrentPage' ] );
$this->registerMenuPages();
}
/**
* Renders the element that we mount our Vue UI on.
*
* @since 1.0.0
*
* @return void
*/
public function renderMenuPage() {
echo '<div id="table-of-contents-plus-app"></div>';
}
/**
* Returns the branded menu icon (anchor badge) as SVG markup.
*
* @since 202607.1
*
* @return string The SVG markup.
*/
private function getMenuIcon() {
return '<svg width="20" height="20" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M64 128C99.3462 128 128 99.3462 128 64C128 28.6538 99.3462 0 64 0C28.6538 0 0 28.6538 0 64C0 99.3462 28.6538 128 64 128Z M64.1538 25.5384C67.5385 25.5384 70.6154 26.7692 72.9231 29.3846C75.2308 31.6923 76.3077 34.6153 76.4615 37.8461V38.4615C76.4615 41.2307 75.6923 43.6923 74.1538 45.8461C72.9231 47.5384 71.3846 48.923 69.5385 49.8461V52.923H76.3077C78.3077 52.923 80 54.6153 80 56.6153V60.6153C80 62.6153 78.3077 64.3077 76.3077 64.3077H69.5385V89.2307C72.3077 88.6153 74.9231 87.3846 77.5385 85.8461C80.3077 84.1538 82.4615 82.1538 83.8461 80L80.9231 76.923C79.3846 75.3846 79.5385 72.7692 81.3846 71.3846L91.2308 63.6923C93.6923 61.8461 97.0769 63.5384 97.0769 66.6153V74.1538C97.0769 78 96 81.6923 93.8461 85.0769C91.8461 88.3076 89.0769 91.2307 86 93.5384C82.7692 96 79.2308 97.8461 75.3846 99.2307C71.5385 100.615 67.6923 101.385 63.8461 101.385C60 101.385 56.3077 100.615 52.3077 99.2307C48.4615 97.8461 44.9231 96 41.6923 93.5384C38.4615 91.0769 35.8461 88.3076 33.8461 85.0769C31.6923 81.6923 30.6154 78 30.6154 74.1538V66.6153C30.6154 63.5384 34 61.8461 36.4615 63.6923L46.3077 71.3846C48 72.7692 48.1538 75.3846 46.7692 76.923L43.8461 80C45.3846 82.1538 47.3846 84 50.1538 85.8461C52.7692 87.3846 55.5385 88.6153 58.1538 89.2307V64.4615H51.3846C49.3846 64.4615 47.6923 62.7692 47.6923 60.7692V56.7692C47.6923 54.7692 49.3846 53.0769 51.3846 53.0769H58.4615V50C56.6154 49.0769 55.0769 47.6923 53.8461 46C52.3077 44 51.5385 41.5384 51.5385 39.0769V38.6153C51.5385 35.0769 52.7692 32 55.0769 29.5384C57.6923 26.923 60.6154 25.5384 64.1538 25.5384ZM64.1538 34.1538C62.9231 34.1538 62 34.6153 61.2308 35.3846C60.4615 36.1538 60 37.2307 60 38.4615C60 39.6923 60.4615 40.7692 61.2308 41.5384C62 42.3077 62.9231 42.7692 64.1538 42.7692C65.3846 42.7692 66.3077 42.3077 67.0769 41.5384C67.8461 40.7692 68.3077 39.6923 68.3077 38.4615C68.3077 37.2307 67.8461 36.1538 67.0769 35.3846C66.3077 34.6153 65.3846 34.1538 64.1538 34.1538Z" fill="#a7aaad"/></svg>'; // phpcs:ignore Generic.Files.LineLength.MaxExceeded
}
/**
* Registers our menu pages.
*
* @since 1.0.0
*
* @return void
*/
public function registerMenuPages() {
// Relabel the auto-created first submenu (which otherwise inherits the "ToC+"
// menu title) to "Settings" for clarity.
add_submenu_page(
$this->pageSlug,
__( 'Settings', 'table-of-contents-plus' ),
__( 'Settings', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug,
[ $this, 'renderMenuPage' ]
);
$hook = add_submenu_page(
$this->pageSlug,
__( 'About Us', 'table-of-contents-plus' ),
__( 'About Us', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug . '-about',
[ $this, 'renderMenuPage' ]
);
$this->pages[] = $this->pageSlug . '-about';
add_action( "load-{$hook}", [ $this, 'checkCurrentPage' ] );
}
/**
* Checks if the current page is a Table of Contents Plus page and if so, starts enqueing the relevant assets.
*
* @since 1.0.0
*
* @return void
*/
public function checkCurrentPage() {
global $admin_page_hooks; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
$currentScreen = function_exists( 'get_current_screen' ) ? get_current_screen() : false;
if ( empty( $currentScreen->id ) || empty( $admin_page_hooks ) ) { // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
return;
}
$pages = [
'about'
];
foreach ( $pages as $page ) {
$addScripts = false;
if ( 'toplevel_page_table-of-contents' === $currentScreen->id ) {
$page = 'settings';
$addScripts = true;
}
if ( strpos( $currentScreen->id, 'table-of-contents-' . $page ) !== false ) {
$addScripts = true;
}
if ( ! $addScripts ) {
continue;
}
// We don't want other plugins adding notices to our screens. Let's clear them out here.
remove_all_actions( 'admin_notices' );
remove_all_actions( 'network_admin_notices' );
remove_all_actions( 'all_admin_notices' );
$this->currentPage = $page;
add_action( 'admin_enqueue_scripts', [ $this, 'enqueueMenuAssets' ], 11 );
add_filter( 'admin_footer_text', [ $this, 'addFooterText' ] );
break;
}
}
/**
* Enqueues our menu assets, based on the current page.
*
* @since 1.0.0
*
* @return void
*/
public function enqueueMenuAssets() {
if ( ! $this->currentPage ) {
return;
}
$scriptHandle = str_replace( '{page}', $this->currentPage, $this->assetSlugs['pages'] );
aioseoTableOfContents()->core->assets->load( $scriptHandle, [], aioseoTableOfContents()->helpers->getVueData( $this->currentPage ) );
}
/**
* Hides the Scheduled Actions menu.
*
* @since 1.0.0
*
* @return void
*/
public function hideScheduledActionsMenu() {
// Don't hide it for developers when the main plugin isn't active.
if ( defined( 'AIOSEO_TABLE_OF_CONTENTS_DEV' ) && ! function_exists( 'aioseo' ) ) {
return;
}
global $submenu;
if ( ! isset( $submenu['tools.php'] ) ) {
return;
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended, HM.Security.NonceVerification.Recommended
// Don't hide it if we're on the Scheduled Actions menu page.
$page = isset( $_GET['page'] )
? sanitize_text_field( wp_unslash( $_GET['page'] ) )
: '';
// phpcs:enable
if ( 'action-scheduler' === $page || aioseoTableOfContents()->helpers->isDev() ) {
return;
}
foreach ( $submenu['tools.php'] as $index => $props ) {
if ( ! empty( $props[2] ) && 'action-scheduler' === $props[2] ) {
unset( $submenu['tools.php'][ $index ] );
return;
}
}
}
/**
* Registers our row meta for the plugins page.
*
* @since 1.0.0
*
* @param array $actions List of existing actions.
* @param string $pluginFile The plugin file.
* @return array List of action links.
*/
public function registerRowMeta( $actions, $pluginFile ) {
$reviewLabel = str_repeat( '<span class="dashicons dashicons-star-filled" style="font-size: 18px; width:16px; height: 16px; color: #ffb900;"></span>', 5 );
$actionLinks = [
'suggest-feature' => [
// Translators: This is an action link users can click to open a feature request.
'label' => __( 'Suggest a Feature', 'table-of-contents-plus' ),
'url' => aioseoTableOfContents()->helpers->utmUrl( AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL . 'table-of-contents-suggest-a-feature/', 'plugin-row-meta', 'feature' ),
],
'review' => [
'label' => $reviewLabel,
'url' => aioseoTableOfContents()->helpers->utmUrl( 'https://aioseo.com/table-of-contents-plus-rating', 'plugin-row-meta', 'review' ),
]
];
return $this->parseActionLinks( $actions, $pluginFile, $actionLinks );
}
/**
* Registers our action links for the plugins page.
*
* @since 1.0.0
*
* @param array $actions List of existing actions.
* @param string $pluginFile The plugin file.
* @return array List of action links.
*/
public function registerActionLinks( $actions, $pluginFile ) {
$actionLinks = [
'support' => [
// Translators: This is an action link users can click to open our support.
'label' => __( 'Support', 'table-of-contents-plus' ),
'url' => aioseoTableOfContents()->helpers->utmUrl( AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL . 'contact/', 'plugin-action-links', 'Support' ),
]
];
if ( isset( $actions['edit'] ) ) {
unset( $actions['edit'] );
}
$actions = $this->parseActionLinks( $actions, $pluginFile, $actionLinks, 'before' );
// Prepend an internal Settings link. Built separately from the links above
// because those open in a new tab, whereas Settings should stay in the admin.
$settingsLink = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url( admin_url( 'admin.php?page=' . $this->pageSlug ) ),
esc_html__( 'Settings', 'table-of-contents-plus' )
);
return array_merge( [ 'settings' => $settingsLink ], $actions );
}
/**
* Parses the action links.
*
* @since 1.0.0
*
* @param array $actions The actions.
* @param string $pluginFile The plugin file.
* @param array $actionLinks The action links.
* @param string $position The position.
* @return array The parsed actions.
*/
private function parseActionLinks( $actions, $pluginFile, $actionLinks = [], $position = 'after' ) {
if ( empty( $this->plugin ) ) {
$this->plugin = AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME;
}
if ( $this->plugin === $pluginFile && ! empty( $actionLinks ) ) {
foreach ( $actionLinks as $key => $value ) {
$link = [
$key => sprintf(
'<a href="%1$s" %2$s target="_blank">%3$s</a>',
esc_url( $value['url'] ),
isset( $value['title'] ) ? 'title="' . esc_attr( $value['title'] ) . '"' : '',
$value['label']
)
];
$actions = 'after' === $position ? array_merge( $actions, $link ) : array_merge( $link, $actions );
}
}
return $actions;
}
/**
* Add the div for the modal portal.
*
* @since 1.1.0
*
* @return void
*/
public function addAioseoModalPortal() {
if ( ! function_exists( 'aioseo' ) ) {
echo '<div id="aioseo-modal-portal"></div>';
}
}
/**
* Checks whether the current page is a Table of Contents Plus menu page.
*
* @since 1.2.0
*
* @return bool Whether the current page is a Table of Contents Plus menu page.
*/
public function isTableOfContentsScreen() {
$currentScreen = aioseoTableOfContents()->helpers->getCurrentScreen();
if ( empty( $currentScreen->id ) ) {
return false;
}
$adminPages = array_keys( $this->pages );
$adminPages = array_map( function( $slug ) {
if ( 'aioseo' === $slug ) {
return 'toplevel_page_table-of-contents';
}
return 'table-of-contents_page_' . $slug;
}, $adminPages );
return in_array( $currentScreen->id, $adminPages, true );
}
/**
* Add footer text to the WordPress admin screens.
*
* @since 1.2.0
*
* @return string The footer text.
*/
public function addFooterText() {
$linkText = esc_html__( 'Give us a 5-star rating!', 'table-of-contents-plus' );
$href = 'https://aioseo.com/table-of-contents-plus-rating';
$link1 = sprintf(
'<a href="%1$s" target="_blank" title="%2$s">&#9733;&#9733;&#9733;&#9733;&#9733;</a>',
$href,
$linkText
);
$link2 = sprintf(
'<a href="%1$s" target="_blank" title="%2$s">WordPress.org</a>',
$href,
$linkText
);
printf(
// Translators: 1 - The plugin name, 2 - Star icons, 3 - "WordPress.org", 4 - The plugin name.
esc_html__( 'Please rate %1$s %2$s on %3$s to help us spread the word. Thank you!', 'table-of-contents-plus' ),
sprintf( '<strong>%1$s</strong>', esc_html( AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME ) ),
wp_kses_post( $link1 ),
wp_kses_post( $link2 )
);
// Stop WP Core from outputting its version number and instead add both theirs & ours.
global $wp_version; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
printf(
wp_kses_post( '<p class="alignright">%1$s</p>' ),
sprintf(
// Translators: 1 - WP Core version number, 2 - version number.
esc_html__( 'WordPress %1$s | Table of Contents Plus %2$s', 'table-of-contents-plus' ),
esc_html( $wp_version ), // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
esc_html( AIOSEO_TABLE_OF_CONTENTS_VERSION )
)
);
remove_filter( 'update_footer', 'core_update_footer' );
return '';
}
}
@@ -0,0 +1,233 @@
<?php
namespace AIOSEO\TableOfContents\Admin\Notices;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Review plugin notice.
*
* @since 1.2.0
*/
class Review {
/**
* Class constructor.
*
* @since 1.2.0
*/
public function __construct() {
add_action( 'wp_ajax_table-of-contents-plus-dismiss-review-plugin-cta', [ $this, 'dismissNotice' ] );
}
/**
* Go through all the checks to see if we should show the notice.
*
* @since 1.2.0
*
* @return void
*/
public function maybeShowNotice() {
// Don't show to users that cannot interact with the plugin.
if ( ! current_user_can( 'edit_posts' ) ) {
return;
}
if ( aioseoTableOfContents()->admin->isTableOfContentsScreen() ) {
return;
}
$dismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', true );
if ( '3' === $dismissed || '4' === $dismissed ) {
return;
}
if ( ! empty( $dismissed ) && $dismissed > time() ) {
return;
}
// Show once plugin has been active for 2 weeks.
if ( ! aioseoTableOfContents()->internalOptions->internal->firstActivated ) {
aioseoTableOfContents()->internalOptions->internal->firstActivated = time();
}
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( $activated > strtotime( '-2 weeks' ) ) {
return;
}
$this->showNotice();
// Print the script to the footer.
add_action( 'admin_footer', [ $this, 'printScript' ] );
}
/**
* Actually show the review plugin 2.0.
*
* @since 1.2.0
*
* @return void
*/
public function showNotice() {
$string1 = sprintf(
// Translators: 1 - The plugin name ("Table of Contents Plus").
__( 'Hey, we noticed you have been using %1$s for some time - that’s awesome! Could you please do us a BIG favor and give it a 5-star rating on WordPress to help us spread the word and boost our motivation?', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>' . esc_html( AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME ) . '</strong>'
);
// Translators: 1 - The plugin name ("Table of Contents Plus").
$string9 = __( 'Ok, you deserve it', 'table-of-contents-plus' );
$string10 = __( 'Nope, maybe later', 'table-of-contents-plus' );
$string11 = __( 'I already did', 'table-of-contents-plus' );
?>
<div class="notice notice-info table-of-contents-plus-review-plugin-cta is-dismissible">
<div class="step-3">
<p><?php echo $string1; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
<p>
<?php // phpcs:ignore Generic.Files.LineLength.MaxExceeded ?>
<a href="https://aioseo.com/table-of-contents-plus-rating" class="table-of-contents-plus-dismiss-review-notice" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string9 ); ?>
</a>&nbsp;&bull;&nbsp;
<a href="#" class="table-of-contents-plus-dismiss-review-notice-delay" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string10 ); ?>
</a>&nbsp;&bull;&nbsp;
<a href="#" class="table-of-contents-plus-dismiss-review-notice" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string11 ); ?>
</a>
</p>
</div>
</div>
<?php
}
/**
* Print the script for dismissing the notice.
*
* @since 1.2.0
*
* @return void
*/
public function printScript() {
// Create a nonce.
$nonce = wp_create_nonce( 'table-of-contents-plus-dismiss-review' );
?>
<style>
@keyframes dismissBtnVisible {
from { opacity: 0.99; }
to { opacity: 1; }
}
.table-of-contents-plus-review-plugin-cta button.notice-dismiss {
animation-duration: 0.001s;
animation-name: dismissBtnVisible;
}
</style>
<script>
window.addEventListener('load', function () {
var aioseoTableOfContentsSetupButton,
dismissBtn,
interval
aioseoTableOfContentsSetupButton = function (dismissBtn) {
var notice = document.querySelector('.notice.table-of-contents-plus-review-plugin-cta'),
delay = false,
relay = true,
stepOne = notice.querySelector('.step-1'),
stepTwo = notice.querySelector('.step-2'),
stepThree = notice.querySelector('.step-3')
// Add an event listener to the dismiss button.
dismissBtn.addEventListener('click', function (event) {
var httpRequest = new XMLHttpRequest(),
postData = ''
// Build the data to send in our request.
postData += '&delay=' + delay
postData += '&relay=' + relay
postData += '&action=table-of-contents-plus-dismiss-review-plugin-cta'
postData += '&nonce=<?php echo esc_html( $nonce ); ?>'
httpRequest.open('POST', '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.send(postData)
})
notice.addEventListener('click', function (event) {
if (event.target.matches('.table-of-contents-plus-review-switch-step-3')) {
event.preventDefault()
stepOne.style.display = 'none'
stepTwo.style.display = 'none'
stepThree.style.display = 'block'
}
if (event.target.matches('.table-of-contents-plus-review-switch-step-2')) {
event.preventDefault()
stepOne.style.display = 'none'
stepThree.style.display = 'none'
stepTwo.style.display = 'block'
}
if (event.target.matches('.table-of-contents-plus-dismiss-review-notice-delay')) {
event.preventDefault()
delay = true
relay = false
dismissBtn.click()
}
if (event.target.matches('.table-of-contents-plus-dismiss-review-notice')) {
if ('#' === event.target.getAttribute('href')) {
event.preventDefault()
}
relay = false
dismissBtn.click()
}
})
}
dismissBtn = document.querySelector('.table-of-contents-plus-review-plugin-cta .notice-dismiss')
if (!dismissBtn) {
document.addEventListener('animationstart', function (event) {
if (event.animationName == 'dismissBtnVisible') {
dismissBtn = document.querySelector('.table-of-contents-plus-review-plugin-cta .notice-dismiss')
if (dismissBtn) {
aioseoTableOfContentsSetupButton(dismissBtn)
}
}
}, false)
} else {
aioseoTableOfContentsSetupButton(dismissBtn)
}
});
</script>
<?php
}
/**
* Dismiss the review plugin CTA.
*
* @since 1.2.0
*
* @return void
*/
public function dismissNotice() {
// Early exit if we're not on a table-of-contents-plus-dismiss-review-plugin-cta action.
if ( ! isset( $_POST['action'] ) || 'table-of-contents-plus-dismiss-review-plugin-cta' !== $_POST['action'] ) {
return;
}
check_ajax_referer( 'table-of-contents-plus-dismiss-review', 'nonce' );
$delay = isset( $_POST['delay'] ) ? 'true' === sanitize_text_field( wp_unslash( $_POST['delay'] ) ) : false;
$relay = isset( $_POST['relay'] ) ? 'true' === sanitize_text_field( wp_unslash( $_POST['relay'] ) ) : false;
if ( ! $delay ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', $relay ? '4' : '3' );
wp_send_json_success();
return;
}
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', strtotime( '+1 week' ) );
wp_send_json_success();
}
}
@@ -0,0 +1,360 @@
<?php
namespace AIOSEO\TableOfContents\Admin;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles our notifications.
*
* @since 1.0.0
*/
class Notifications {
/**
* The URL of the notifications endpoint.
*
* @since 1.0.0
*
* @var string
*/
private $url = 'https://table-of-contents-plugin-cdn.aioseo.com/notifications.json';
/**
* The review notice class instance.
*
* @since 1.0.0
*
* @var Notices\Review
*/
private $reviewNotice;
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
add_action( 'aioseo_table_of_contents_admin_notifications_update', [ $this, 'update' ] );
if ( ! is_admin() ) {
return;
}
add_action( 'init', [ $this, 'init' ], 2 );
add_action( 'admin_notices', [ $this, 'renderNotices' ] );
}
/**
* Initialize notifications.
*
* @since 1.0.0
*
* @return void
*/
public function init() {
// If our tables do not exist, let runUpdates() handle creation.
// Calling updateDbSchema() here AND in runUpdates() causes duplicate
// dbDelta() calls which triggers "table already exists" errors.
if ( ! aioseoTableOfContents()->core->db->tableExists( 'aioseo_table_of_contents_notifications' ) ) {
return;
}
$this->checkForUpdates();
$this->reviewNotice = new Notices\Review();
}
/**
* Renders the notices.
*
* @since 1.2.0
*
* @return void
*/
public function renderNotices() {
if ( ! is_admin() ) {
return;
}
// reviewNotice is only instantiated once our tables exist (see init()).
if ( ! $this->reviewNotice ) {
return;
}
$this->reviewNotice->maybeShowNotice();
}
/**
* Checks if we should update our notifications.
*
* @since 1.0.0
*
* @return void
*/
private function checkForUpdates() {
$nextRun = aioseoTableOfContents()->core->cache->get( 'admin_notifications_update' );
if ( null !== $nextRun && time() < $nextRun ) {
return;
}
aioseoTableOfContents()->actionScheduler->scheduleAsync( 'aioseo_table_of_contents_admin_notifications_update' );
aioseoTableOfContents()->core->cache->update( 'admin_notifications_update', time() + DAY_IN_SECONDS );
}
/**
* Pulls in the notifications from our remote endpoint and stores them in the DB.
*
* @since 1.0.0
*
* @return void
*/
public function update() {
$notifications = $this->fetch();
if ( empty( $notifications ) ) {
return;
}
foreach ( $notifications as $notification ) {
// First, let's check to see if the notification exists. If so, we want to override it.
$aioseoNotification = aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'notification_id', $notification->id )
->run()
->model( 'AIOSEO\\TableOfContents\\Models\\Notification' );
$buttons = [
'button1' => [
'label' => ! empty( $notification->btns->main->text ) ? sanitize_text_field( $notification->btns->main->text ) : null,
'url' => ! empty( $notification->btns->main->url ) ? esc_url_raw( $notification->btns->main->url ) : null
],
'button2' => [
'label' => ! empty( $notification->btns->alt->text ) ? sanitize_text_field( $notification->btns->alt->text ) : null,
'url' => ! empty( $notification->btns->alt->url ) ? esc_url_raw( $notification->btns->alt->url ) : null
]
];
if ( ! $aioseoNotification->exists() ) {
$aioseoNotification = new Models\Notification();
$aioseoNotification->slug = uniqid();
$aioseoNotification->dismissed = 0;
}
$aioseoNotification->notification_id = $notification->id;
$aioseoNotification->title = sanitize_text_field( $notification->title );
$aioseoNotification->content = sanitize_text_field( $notification->content );
$aioseoNotification->type = ! empty( $notification->notification_type ) ? sanitize_text_field( $notification->notification_type ) : 'info';
$aioseoNotification->level = $notification->type;
$aioseoNotification->start = ! empty( $notification->start ) ? sanitize_text_field( $notification->start ) : null;
$aioseoNotification->end = ! empty( $notification->end ) ? sanitize_text_field( $notification->end ) : null;
$aioseoNotification->button1_label = $buttons['button1']['label'];
$aioseoNotification->button1_action = $buttons['button1']['url'];
$aioseoNotification->button2_label = $buttons['button2']['label'];
$aioseoNotification->button2_action = $buttons['button2']['url'];
$aioseoNotification->save();
// Trigger the drawer to open.
aioseoTableOfContents()->core->cache->update( 'show_notifications_drawer', true );
}
}
/**
* Pulls in the notifications from the remote feed.
*
* @since 1.0.0
*
* @return array A list of notifications.
*/
private function fetch() {
$response = aioseoTableOfContents()->helpers->wpRemoteGet( $this->getUrl() );
if ( is_wp_error( $response ) ) {
return [];
}
$body = wp_remote_retrieve_body( $response );
if ( empty( $body ) ) {
return [];
}
$notifications = json_decode( $body );
if ( empty( $notifications ) ) {
return [];
}
return $this->verify( $notifications );
}
/**
* Verifies a notification to see if it's valid before it is stored.
*
* @since 1.0.0
*
* @param array $notifications List of notifications items to verify.
* @return array List of verified notifications.
*/
private function verify( $notifications ) {
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return [];
}
$data = [];
foreach ( $notifications as $notification ) {
// The content and type should never be empty. If they are, ignore the notification.
if ( empty( $notification->content ) || empty( $notification->type ) ) {
continue;
}
if ( ! is_array( $notification->type ) ) {
$notification->type = [ $notification->type ];
}
foreach ( $notification->type as $type ) {
$type = sanitize_text_field( $type );
// Ignore the notification if not a single type matches.
if ( ! $this->validateType( $type ) ) {
continue 2;
}
}
// Ignore the notification if it already expired.
if ( ! empty( $notification->end ) && time() > strtotime( $notification->end ) ) {
continue;
}
// Ignore the notification if it existed before installing Table of Contents Plus.
// Prevents spamming the user with notifications after activation.
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( ! empty( $notification->start ) && $activated > strtotime( $notification->start ) ) {
continue;
}
$data[] = $notification;
}
return $data;
}
/**
* Validates the notification type.
*
* @since 1.0.0
*
* @param string $type The notification type we are targeting.
* @return bool Whether the notification is valid.
*/
public function validateType( $type ) {
if ( 'all' === $type ) {
return true;
}
// Table of Contents Plus is a free plugin with no license, so all users are unlicensed.
if ( 'free' === $type ) {
return true;
}
// There are no licensed users to target.
if ( 'licensed' === $type ) {
return false;
}
// Store notice if version matches.
if ( $this->versionMatch( aioseoTableOfContents()->version, $type ) ) {
return true;
}
return false;
}
/**
* Checks whether two versions are equal.
*
* @since 1.0.0
*
* @param string $currentVersion The current version being used.
* @param string|array $compareVersion The version to compare with.
* @return bool Whether it is a match.
*/
private function versionMatch( $currentVersion, $compareVersion ) {
if ( is_array( $compareVersion ) ) {
foreach ( $compareVersion as $compare_single ) {
$recursiveResult = $this->versionMatch( $currentVersion, $compare_single );
if ( $recursiveResult ) {
return true;
}
}
return false;
}
$currentParse = explode( '.', $currentVersion );
if ( strpos( $compareVersion, '-' ) ) {
$compareParse = explode( '-', $compareVersion );
} elseif ( strpos( $compareVersion, '.' ) ) {
$compareParse = explode( '.', $compareVersion );
} else {
return false;
}
$currentCount = count( $currentParse );
$compareCount = count( $compareParse );
for ( $i = 0; $i < $currentCount || $i < $compareCount; $i++ ) {
if ( isset( $compareParse[ $i ] ) && 'x' === strtolower( $compareParse[ $i ] ) ) {
unset( $compareParse[ $i ] );
}
if ( ! isset( $currentParse[ $i ] ) ) {
unset( $compareParse[ $i ] );
} elseif ( ! isset( $compareParse[ $i ] ) ) {
unset( $currentParse[ $i ] );
}
}
foreach ( $compareParse as $index => $subNumber ) {
if ( $currentParse[ $index ] !== $subNumber ) {
return false;
}
}
return true;
}
/**
* Returns the URL for the notifications endpoint.
*
* @since 1.0.0
*
* @return string The URL.
*/
private function getUrl() {
if ( defined( 'AIOSEO_TABLE_OF_CONTENTS_NOTIFICATIONS_URL' ) ) {
return AIOSEO_TABLE_OF_CONTENTS_NOTIFICATIONS_URL;
}
return $this->url;
}
/**
* Extends a notice by a (default) 1 week start date.
*
* @since 1.0.0
*
* @param string $notice The notice name.
* @param string $start How long to extend the notice.
* @return void
*/
public function remindMeLater( $notice, $start = '+1 week' ) {
$notification = Models\Notification::getNotificationByName( $notice );
if ( ! $notification->exists() ) {
return;
}
$notification->start = gmdate( 'Y-m-d H:i:s', strtotime( $start ) );
$notification->save();
}
}
@@ -0,0 +1,201 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles the registration, validation and authorization of API routes.
*
* @since 1.0.0
*/
class Api {
/**
* The REST API namespace.
*
* @since 1.0.0
*
* @var string
*/
public $namespace = 'aioseoTableOfContents/v1';
/**
* The routes we use in the rest API.
*
* @since 1.0.0
*
* @var array
*/
private $routes = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'GET' => [
'options' => [ 'callback' => [ 'VueSettings', 'getOptions' ], 'access' => 'any' ],
'toc-settings' => [ 'callback' => [ 'TocSettings', 'getSettings' ], 'access' => 'aioseo_table_of_contents_page' ],
'ping' => [ 'callback' => [ 'Ping', 'ping' ], 'access' => 'any' ]
],
'POST' => [
'notifications/dismiss' => [ 'callback' => [ 'Notifications', 'dismissNotifications' ], 'access' => 'any' ],
'objects' => [ 'callback' => [ 'PostsTerms', 'searchForObjects' ], 'access' => [ 'aioseo_table_of_contents_page' ] ],
'options' => [ 'callback' => [ 'VueSettings', 'saveChanges' ], 'access' => 'aioseo_table_of_contents_page' ],
'plugins/deactivate' => [ 'callback' => [ 'Plugins', 'deactivatePlugins' ], 'access' => 'install_plugins' ],
'plugins/install' => [ 'callback' => [ 'Plugins', 'installPlugins' ], 'access' => 'install_plugins' ],
'toc-settings' => [ 'callback' => [ 'TocSettings', 'saveSettings' ], 'access' => 'aioseo_table_of_contents_page' ],
'settings/toggle-radio' => [ 'callback' => [ 'VueSettings', 'toggleRadio' ], 'access' => 'aioseo_table_of_contents_page' ],
'settings/items-per-page' => [ 'callback' => [ 'VueSettings', 'changeItemsPerPage' ], 'access' => 'aioseo_table_of_contents_page' ]
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* Class contructor.
*
* @since 1.0.0
*/
public function __construct() {
add_filter( 'rest_allowed_cors_headers', [ $this, 'allowedHeaders' ] );
add_action( 'rest_api_init', [ $this, 'registerRoutes' ] );
}
/**
* Registers the API routes.
*
* @since 1.0.0
*
* @return void
*/
public function registerRoutes() {
$class = new \ReflectionClass( get_called_class() );
foreach ( $this->routes as $method => $data ) {
foreach ( $data as $route => $options ) {
register_rest_route(
$this->namespace,
$route,
[
'methods' => $method,
'permission_callback' => empty( $options['permissions'] ) ? [ $this, 'validRequest' ] : [ $this, $options['permissions'] ],
'callback' => is_array( $options['callback'] )
? [
(
! empty( $options['callback'][2] )
? $options['callback'][2] . '\\' . $options['callback'][0]
: (
class_exists( $class->getNamespaceName() . '\\' . $options['callback'][0] )
? $class->getNamespaceName() . '\\' . $options['callback'][0]
: __NAMESPACE__ . '\\' . $options['callback'][0]
)
),
$options['callback'][1]
]
: [ $this, $options['callback'] ]
]
);
}
}
}
/**
* Sets headers that are allowed for our API routes.
*
* @since 1.0.0
*
* @param array $allowHeaders The allowed request headers.
* @return array The allowed request headers.
*/
public function allowedHeaders( $allowHeaders ) {
if ( ! array_search( 'X-WP-Nonce', $allowHeaders, true ) ) {
$allowHeaders[] = 'X-WP-Nonce';
}
return $allowHeaders;
}
/**
* Determine if the user is logged in and has the proper permissions.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return bool Whether the user is allowed access to the route.
*/
public function validRequest( $request ) {
return is_user_logged_in() && $this->validateAccess( $request );
}
/**
* Validates access for the routes.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return bool Whether the user is allowed access to the route.
*/
private function validateAccess( $request ) {
$routeData = $this->getRouteData( $request );
if ( empty( $routeData ) || empty( $routeData['access'] ) ) {
return false;
}
// Admins users always have access.
if ( aioseoTableOfContents()->access->isAdmin() ) {
return true;
}
switch ( $routeData['access'] ) {
case 'any':
// Users with any Table of Contents Plus permission can access the route.
$user = wp_get_current_user();
foreach ( $user->get_role_caps() as $capability => $enabled ) {
if ( $enabled && preg_match( '/^aioseo_table_of_contents_/', (string) $capability ) ) {
return true;
}
}
return false;
default:
// The user has access if he has any of the required capabilities.
if ( ! is_array( $routeData['access'] ) ) {
$routeData['access'] = [ $routeData['access'] ];
}
foreach ( $routeData['access'] as $access ) {
if ( current_user_can( $access ) ) {
return true;
}
}
return false;
}
}
/**
* Returns the data for the route that is being accessed.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return array The route data.
*/
private function getRouteData( $request ) {
// NOTE: Since WordPress uses case-insensitive patterns to match routes,
// we are forcing everything to lower case to ensure we have the proper route.
// This prevents users with lower privileges from accessing routes they shouldn't.
$route = aioseoTableOfContents()->helpers->toLowercase( $request->get_route() );
$route = untrailingslashit( str_replace( '/' . $this->namespace . '/', '', $route ) );
$routeData = isset( $this->routes[ $request->get_method() ][ $route ] ) ? $this->routes[ $request->get_method() ][ $route ] : [];
// No direct route name, let's try the regexes.
if ( empty( $routeData ) ) {
foreach ( $this->routes[ $request->get_method() ] as $routeRegex => $routeInfo ) {
$routeRegex = str_replace( '@', '\@', $routeRegex );
if ( preg_match( "@{$routeRegex}@", (string) $route ) ) {
$routeData = $routeInfo;
break;
}
}
}
return $routeData;
}
}
@@ -0,0 +1,70 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles notification related routes.
*
* @since 1.0.0
*/
class Notifications {
/**
* This allows us to not repeat code over and over.
*
* @since 1.0.0
*
* @param string $slug The slug of the reminder.
* @return \WP_REST_Response The response.
*/
public static function reminder( $slug ) {
aioseoTableOfContents()->notifications->remindMeLater( $slug );
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
/**
* Dismiss notifications.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function dismissNotifications( $request ) {
$slugs = $request->get_json_params();
$notifications = aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->whereIn( 'slug', $slugs )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' );
foreach ( $notifications as $notification ) {
$notification->dismissed = 1;
$notification->save();
}
// Dismiss static notifications.
if ( in_array( 'notification-review', $slugs, true ) ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', '3' );
}
if ( in_array( 'notification-review-delay', $slugs, true ) ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', strtotime( '+1 week' ) );
}
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin install/deinstall.
*
* @since 1.0.0
*/
class Plugins {
/**
* Installs plugins.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function installPlugins( $request ) {
$body = $request->get_json_params();
$plugins = ! empty( $body['plugins'] ) ? $body['plugins'] : [];
$network = ! empty( $body['network'] ) ? $body['network'] : false;
$error = esc_html__( 'Installation failed. Please check permissions and try again.', 'table-of-contents-plus' );
if ( ! is_array( $plugins ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
if ( ! aioseoTableOfContents()->helpers->canInstall() ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$failed = [];
$completed = [];
foreach ( $plugins as $plugin ) {
if ( empty( $plugin['plugin'] ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
$result = aioseoTableOfContents()->helpers->installAddon( $plugin['plugin'], $network );
if ( ! $result ) {
$failed[] = $plugin['plugin'];
} else {
$completed[ $plugin['plugin'] ] = $result;
}
}
return new \WP_REST_Response( [
'success' => true,
'completed' => $completed,
'failed' => $failed
], 200 );
}
/**
* Deactivates plugins.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function deactivatePlugins( $request ) {
$body = $request->get_json_params();
$plugins = ! empty( $body['plugins'] ) ? $body['plugins'] : [];
$network = ! empty( $body['network'] ) ? $body['network'] : false;
$error = esc_html__( 'Deactivation failed. Please check permissions and try again.', 'table-of-contents-plus' );
if ( ! is_array( $plugins ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
if ( ! current_user_can( 'install_plugins' ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$failed = [];
$completed = [];
foreach ( $plugins as $plugin ) {
if ( empty( $plugin['plugin'] ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
$deactivated = deactivate_plugins( $plugin['plugin'], false, $network );
if ( is_wp_error( $deactivated ) ) {
$failed[] = $plugin['plugin'];
}
$completed[] = $plugin['plugin'];
}
return new \WP_REST_Response( [
'success' => true,
'completed' => $completed,
'failed' => $failed
], 200 );
}
}
@@ -0,0 +1,79 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles post/term lookups.
*
* @since 1.0.0
*/
class PostsTerms {
/**
* Returns posts by ID/name.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function searchForObjects( $request ) {
$body = $request->get_json_params();
$searchTerm = ! empty( $body['query'] ) ? sanitize_text_field( $body['query'] ) : null;
$type = ! empty( $body['type'] ) ? sanitize_text_field( $body['type'] ) : null;
if ( empty( $searchTerm ) || empty( $type ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => 'No search term or object type was provided.'
], 400 );
}
$wpdb = aioseoTableOfContents()->core->db->db;
$like = '%' . $wpdb->esc_like( $searchTerm ) . '%';
$objects = [];
if ( 'posts' === $body['type'] ) {
$postTypes = aioseoTableOfContents()->helpers->getPublicPostTypes( true );
$objects = aioseoTableOfContents()->core->db
->start( 'posts' )
->select( 'ID, post_type, post_title, post_name' )
->whereRaw( $wpdb->prepare( '( post_title LIKE %s OR post_name LIKE %s OR ID = %d )', $like, $like, $searchTerm ) )
->whereIn( 'post_type', $postTypes )
->whereIn( 'post_status', [ 'publish', 'draft', 'future', 'pending' ] )
->orderBy( 'post_title' )
->limit( 10 )
->run()
->result();
}
if ( empty( $objects ) ) {
return new \WP_REST_Response( [
'success' => true,
'objects' => []
], 200 );
}
$parsedObjects = [];
foreach ( $objects as $object ) {
if ( 'posts' === $type ) {
$parsedObjects[] = [
'value' => (int) $object->ID,
'slug' => $object->post_name,
'label' => $object->post_title,
'type' => $object->post_type,
'link' => get_permalink( $object->ID )
];
}
}
return new \WP_REST_Response( [
'success' => true,
'objects' => $parsedObjects
], 200 );
}
}
@@ -0,0 +1,213 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Reads and writes the table of contents settings.
*
* The frontend engine still stores its settings in the legacy 'toc-options'
* option, so this controller bridges the Vue settings UI to that store and
* mirrors the sanitization the legacy admin page used.
*
* Follow-up (tech debt): migrate these user settings onto the modern Options
* framework the other AIOSEO plugins use. That store persists on activation and
* version-tracks reliably, which would remove the existing-install detection
* gymnastics in {@see \AIOSEO\TableOfContents\Main\Updates::migrateAppearanceDefaults()}.
*
* @since 1.0.0
*/
class TocSettings {
/**
* Returns the current settings merged with the defaults, plus the data the UI needs.
*
* @since 1.0.0
*
* @return \WP_REST_Response The response.
*/
public static function getSettings() {
$engine = aioseoTableOfContents()->standalone->frontend;
return new \WP_REST_Response( [
'success' => true,
'settings' => $engine->get_options(),
'postTypes' => self::getPostTypes()
], 200 );
}
/**
* Saves the settings to the legacy 'toc-options' option.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST request.
* @return \WP_REST_Response The response.
*/
public static function saveSettings( $request ) {
$engine = aioseoTableOfContents()->standalone->frontend;
$defaults = $engine->get_defaults();
$body = $request->get_json_params();
if ( empty( $body ) || ! is_array( $body ) ) {
return new \WP_REST_Response( [ 'success' => false ], 400 );
}
$string = function ( $key ) use ( $body, $defaults ) {
return isset( $body[ $key ] ) ? trim( sanitize_text_field( wp_unslash( $body[ $key ] ) ) ) : $defaults[ $key ];
};
$bool = function ( $key ) use ( $body ) {
return ! empty( $body[ $key ] );
};
$int = function ( $key ) use ( $body, $defaults ) {
return isset( $body[ $key ] ) ? intval( $body[ $key ] ) : $defaults[ $key ];
};
$color = function ( $key, $default ) use ( $engine, $body ) {
return ! empty( $body[ $key ] ) ? $engine->hex_value( trim( wp_unslash( $body[ $key ] ) ), $default ) : $default;
};
$enum = function ( $key, $allowed ) use ( $string, $defaults ) {
$value = $string( $key );
return in_array( $value, $allowed, true ) ? $value : $defaults[ $key ];
};
$restrictPath = $string( 'restrict_path' );
if ( $restrictPath && 0 !== strpos( $restrictPath, '/' ) ) {
// The restrict path must start with a forward slash, otherwise clear it.
$restrictPath = '';
}
$sanitized = [
'fragment_prefix' => $string( 'fragment_prefix' ),
'position' => $int( 'position' ),
'start' => $int( 'start' ),
'show_heading_text' => $bool( 'show_heading_text' ),
'heading_text' => $string( 'heading_text' ),
'heading_alignment' => $enum( 'heading_alignment', [ 'left', 'center', 'right' ] ),
'auto_insert_post_types' => self::sanitizeStringArray( $body, 'auto_insert_post_types' ),
'show_heirarchy' => $bool( 'show_heirarchy' ),
'ordered_list' => $bool( 'ordered_list' ),
'numbering_style' => $enum( 'numbering_style', [ 'hierarchical', 'decimal', 'upper-roman', 'lower-roman', 'upper-alpha', 'lower-alpha' ] ),
'smooth_scroll' => $bool( 'smooth_scroll' ),
'smooth_scroll_offset' => $int( 'smooth_scroll_offset' ),
'visibility' => $bool( 'visibility' ),
'visibility_show' => $string( 'visibility_show' ),
'visibility_hide' => $string( 'visibility_hide' ),
'toggle_style' => $enum( 'toggle_style', [ 'plus_minus', 'caret', 'brackets' ] ),
'visibility_hide_by_default' => $bool( 'visibility_hide_by_default' ),
'width' => $string( 'width' ),
'width_custom' => isset( $body['width_custom'] ) ? floatval( $body['width_custom'] ) : $defaults['width_custom'],
'width_custom_units' => $string( 'width_custom_units' ),
'wrapping' => $int( 'wrapping' ),
'font_size' => isset( $body['font_size'] ) ? floatval( $body['font_size'] ) : $defaults['font_size'],
'font_size_units' => $string( 'font_size_units' ),
'theme' => $int( 'theme' ),
'custom_background_colour' => $color( 'custom_background_colour', TOC_DEFAULT_BACKGROUND_COLOUR ),
'custom_border_colour' => $color( 'custom_border_colour', TOC_DEFAULT_BORDER_COLOUR ),
'custom_title_colour' => $color( 'custom_title_colour', TOC_DEFAULT_TITLE_COLOUR ),
'custom_links_colour' => $color( 'custom_links_colour', TOC_DEFAULT_LINKS_COLOUR ),
'custom_links_hover_colour' => $color( 'custom_links_hover_colour', TOC_DEFAULT_LINKS_HOVER_COLOUR ),
'custom_links_visited_colour' => $color( 'custom_links_visited_colour', TOC_DEFAULT_LINKS_VISITED_COLOUR ),
'lowercase' => $bool( 'lowercase' ),
'hyphenate' => $bool( 'hyphenate' ),
'bullet_spacing' => $bool( 'bullet_spacing' ),
'include_homepage' => $bool( 'include_homepage' ),
'exclude_css' => $bool( 'exclude_css' ),
'heading_levels' => self::sanitizeIntArray( $body, 'heading_levels' ),
'exclude' => $string( 'exclude' ), // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude
'restrict_path' => $restrictPath,
'css_container_class' => $string( 'css_container_class' ),
'sitemap_show_page_listing' => $bool( 'sitemap_show_page_listing' ),
'sitemap_show_category_listing' => $bool( 'sitemap_show_category_listing' ),
'sitemap_heading_type' => $int( 'sitemap_heading_type' ),
'sitemap_pages' => $string( 'sitemap_pages' ),
'sitemap_categories' => $string( 'sitemap_categories' ),
'show_toc_in_widget_only' => $bool( 'show_toc_in_widget_only' ),
'show_toc_in_widget_only_post_types' => self::sanitizeStringArray( $body, 'show_toc_in_widget_only_post_types' ),
'rest_toc_output' => $bool( 'rest_toc_output' )
];
$options = array_merge( $engine->get_options(), $sanitized );
update_option( 'toc-options', $options );
$engine->set_option( $options );
return new \WP_REST_Response( [
'success' => true,
'settings' => $options
], 200 );
}
/**
* Sanitizes an array of strings from the request body.
*
* @since 1.0.0
*
* @param array $body The request body.
* @param string $key The key to sanitize.
* @return array The sanitized array.
*/
private static function sanitizeStringArray( $body, $key ) {
if ( empty( $body[ $key ] ) || ! is_array( $body[ $key ] ) ) {
return [];
}
return array_values( array_map( 'sanitize_text_field', array_map( 'wp_unslash', $body[ $key ] ) ) );
}
/**
* Sanitizes an array of integers from the request body.
*
* @since 1.0.0
*
* @param array $body The request body.
* @param string $key The key to sanitize.
* @return array The sanitized array.
*/
private static function sanitizeIntArray( $body, $key ) {
if ( empty( $body[ $key ] ) || ! is_array( $body[ $key ] ) ) {
return [];
}
return array_values( array_map( 'intval', $body[ $key ] ) );
}
/**
* Returns the public post types the table of contents can be enabled for.
*
* @since 1.0.0
*
* @return array The post types as { name, label, icon } objects.
*/
public static function getPostTypes() {
$exclude = [ 'attachment', 'revision', 'nav_menu_item', 'safecss' ];
$builtinIcons = [
'post' => 'dashicons-admin-post',
'page' => 'dashicons-admin-page'
];
$postTypes = [];
foreach ( get_post_types( [ 'public' => true ], 'objects' ) as $postType ) {
if ( in_array( $postType->name, $exclude, true ) ) {
continue;
}
if ( isset( $builtinIcons[ $postType->name ] ) ) {
$icon = $builtinIcons[ $postType->name ];
} elseif ( is_string( $postType->menu_icon ) && 0 === strpos( $postType->menu_icon, 'dashicons-' ) ) {
$icon = $postType->menu_icon;
} else {
$icon = 'dashicons-admin-post';
}
$postTypes[] = [
'name' => $postType->name,
'label' => $postType->labels->name,
'icon' => $icon
];
}
return $postTypes;
}
}
@@ -0,0 +1,111 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles the user Vue settings (toggled radios, table pagination, etc.).
*
* @since 1.0.0
*/
class VueSettings {
/**
* Returns the settings.
*
* @since 1.0.0
*
* @return \WP_REST_Response The response.
*/
public static function getOptions() {
return new \WP_REST_Response( [
'success' => true,
'options' => aioseoTableOfContents()->options->all(),
'internalOptions' => aioseoTableOfContents()->internalOptions->all(),
'settings' => aioseoTableOfContents()->vueSettings->all()
], 200 );
}
/**
* Toggles a radio in the settings.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function toggleRadio( $request ) {
$body = $request->get_json_params();
$radio = ! empty( $body['radio'] ) ? sanitize_text_field( $body['radio'] ) : null;
$value = ! empty( $body['value'] ) ? sanitize_text_field( $body['value'] ) : null;
$radios = aioseoTableOfContents()->vueSettings->toggledRadio;
if ( ! array_key_exists( $radio, $radios ) ) {
return new \WP_REST_Response( [
'success' => false
], 400 );
}
$radios[ $radio ] = $value;
aioseoTableOfContents()->vueSettings->toggledRadio = $radios;
return new \WP_REST_Response( [
'success' => true
], 200 );
}
/**
* Toggles a table's items per page setting.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function changeItemsPerPage( $request ) {
$body = $request->get_json_params();
$table = ! empty( $body['table'] ) ? sanitize_text_field( $body['table'] ) : null;
$value = ! empty( $body['value'] ) ? intval( $body['value'] ) : null;
$tables = aioseoTableOfContents()->vueSettings->tablePagination;
if ( ! array_key_exists( $table, $tables ) ) {
return new \WP_REST_Response( [
'success' => false
], 400 );
}
$tables[ $table ] = $value;
aioseoTableOfContents()->vueSettings->tablePagination = $tables;
return new \WP_REST_Response( [
'success' => true
], 200 );
}
/**
* Save options from the frontend.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function saveChanges( $request ) {
$body = $request->get_json_params();
$options = ! empty( $body['options'] ) ? $body['options'] : []; // The options class will sanitize them.
aioseoTableOfContents()->options->sanitizeAndSave( $options );
// Re-initialize the notices.
aioseoTableOfContents()->notifications->init();
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
}
@@ -0,0 +1,655 @@
<?php
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles the loading of our file assets.
*
* @since 1.0.0
*/
class Assets {
/**
* Whether we should load dev scripts.
*
* @since 1.0.0
*
* @var boolean|null
*/
private $shouldLoadDevScripts = null;
/**
* The script handle to use for asset enqueuing.
*
* @since 1.0.0
*
* @var string
*/
private $scriptHandle = 'table-of-contents-plus';
/**
* Holds the location of the manifest file.
*
* @since 1.0.0
*
* @var string
*/
private $manifestFile = '';
/**
* True if we are in a dev environment. This mirrors the global isDev.
*
* @since 1.0.0
*
* @var bool
*/
private $isDev = false;
/**
* Asset handles that should load as regular JS and not as modern JS module.
*
* @since 1.0.0
*
* @var array An array of handles.
*/
private $noModuleTag = [];
/**
* Core class instance.
*
* @since 1.1.0
*
* @var Core
*/
public $core = null;
/**
* The plugin version.
*
* @since 1.1.0
*
* @var int
*/
public $version = 0;
/**
* The domain.
*
* @since 1.1.0
*
* @var string
*/
public $domain = '';
/**
* The port.
*
* @since 1.1.0
*
* @var int
*/
public $port = 0;
/**
* Class constructor.
*
* @since 1.0.0
*
* @param Core $core The AIOSEO Core class.
*/
public function __construct( $core ) {
$this->core = $core;
$this->version = aioseoTableOfContents()->version;
$this->manifestFile = AIOSEO_TABLE_OF_CONTENTS_DIR . '/dist/manifest.php';
$this->isDev = aioseoTableOfContents()->isDev;
if ( $this->isDev ) {
$this->domain = getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DOMAIN' );
$this->port = getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DEV_PORT' );
}
add_filter( 'script_loader_tag', [ $this, 'scriptLoaderTag' ], 10, 3 );
}
/**
* The asset to load.
*
* @since 1.0.0
*
* @param string $asset The asset to load.
* @param array $dependencies An array of dependencies.
* @param mixed $data Any data to be localized.
* @param string $objectName The object name to use when localizing.
* @return void
*/
public function load( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
$this->jsPreloadImports( $asset );
$this->loadCss( $asset );
$this->enqueueJs( $asset, $dependencies, $data, $objectName );
}
/**
* Filter the script loader tag if this is our script.
*
* @since 1.0.0
*
* @param string $tag The tag that is going to be output.
* @param string $handle The handle for the script.
* @return string The modified tag.
*/
public function scriptLoaderTag( $tag, $handle, $src ) {
if ( $this->skipModuleTag( $handle ) ) {
return $tag;
}
$tag = str_replace( $src, $this->normalizeAssetsHost( $src ), $tag );
// Remove the type and re-add it as module.
$tag = preg_replace( '/type=[\'"].*?[\'"]/', '', (string) $tag );
$tag = preg_replace( '/<script/', '<script type="module"', (string) $tag );
return $tag;
}
/**
* Preload JS imports.
*
* @since 1.0.0
*
* @param string $asset The asset to load imports for.
* @return void
*/
private function jsPreloadImports( $asset ) {
static $urls = []; // Prevent script from being loaded multiple times.
$res = '';
foreach ( $this->importsUrls( $asset ) as $url ) {
if ( isset( $urls[ $url ] ) ) {
continue;
}
$urls[ $url ] = true;
$res .= '<link rel="modulepreload" href="' . esc_attr( $url ) . "\">\n";
}
$allowedHtml = [
'link' => [
'rel' => [],
'href' => []
]
];
if ( ! empty( $res ) ) {
if ( ! function_exists( 'wp_enqueue_script_module' ) ) {
add_action( 'admin_head', function () use ( &$res, $allowedHtml ) {
echo wp_kses( $res, $allowedHtml );
} );
add_action( 'wp_head', function () use ( &$res, $allowedHtml ) {
echo wp_kses( $res, $allowedHtml );
} );
} else {
add_action( 'admin_print_footer_scripts', function () use ( &$res, $allowedHtml ) {
echo wp_kses( $res, $allowedHtml );
}, 1000 );
}
}
}
/**
* Loads CSS for an asset from the manifest file.
*
* @since 1.0.0
*
* @param string $asset The script to load CSS for.
* @return void
*/
private function loadCss( $asset ) {
if ( $this->shouldLoadDev() ) {
return;
}
foreach ( $this->getCssUrls( $asset ) as $file => $url ) {
wp_enqueue_style( $this->cssHandle( $file ), $url, [], $this->version );
}
}
/**
* Register a CSS asset.
*
* @since 1.0.0
*
* @param string $asset The script to load CSS for.
* @param array $dependencies An array of dependencies.
* @param string $devPath The file's dev path.
* @return void
*/
public function registerCss( $asset, $dependencies = [], $devPath = '' ) {
$handle = $this->cssHandle( $asset );
if ( wp_style_is( $handle, 'registered' ) ) {
return;
}
$devPath = $devPath ?: $asset;
$url = $this->shouldLoadDev()
? $this->getDevUrl() . ltrim( $devPath, '/' )
: $this->assetUrl( $asset );
if ( ! $url ) {
return;
}
wp_register_style( $handle, $url, $dependencies, $this->version );
}
/**
* Enqueue css.
*
* @since 1.0.0
*
* @param string $asset The css to load.
* @param string $devPath The file's dev path.
* @param array $dependencies An array of dependencies.
* @return void
*/
public function enqueueCss( $asset, $dependencies = [], $devPath = '' ) {
$this->registerCss( $asset, $dependencies, $devPath );
$handle = $this->cssHandle( $asset );
if ( wp_style_is( $handle, 'enqueued' ) ) {
return;
}
wp_enqueue_style( $handle );
}
/**
* Register the JS to enqueue.
*
* @since 1.0.0
*
* @param string $asset The script to load.
* @param array $dependencies An array of dependencies.
* @param mixed $data Any data to be localized.
* @param string $objectName The object name to use when localizing.
* @return void
*/
public function registerJs( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
$handle = $this->jsHandle( $asset );
if ( wp_script_is( $handle, 'registered' ) ) {
return;
}
$url = $this->shouldLoadDev()
? $this->getDevUrl() . ltrim( $asset, '/' )
: $this->jsUrl( $asset );
if ( ! $url ) {
return;
}
wp_register_script( $handle, $url, $dependencies, $this->version, true );
if ( empty( $data ) ) {
return;
}
wp_localize_script(
$handle,
$objectName,
$data
);
}
/**
* Register the JS to enqueue.
*
* @since 1.0.0
*
* @param string $asset The script to load.
* @param array $dependencies An array of dependencies.
* @param mixed $data Any data to be localized.
* @param string $objectName The object name to use when localizing.
* @return void
*/
public function enqueueJs( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
$this->registerJs( $asset, $dependencies, $data, $objectName );
$handle = $this->jsHandle( $asset );
if ( wp_script_is( $handle, 'enqueued' ) ) {
return;
}
wp_enqueue_script( $handle );
}
/**
* Return the dev URL.
*
* @since 1.0.0
*
* @return string The dev URL.
*/
private function getDevUrl() {
$protocol = is_ssl() ? 'https://' : 'http://';
return $protocol . $this->domain . ':' . $this->port . '/';
}
/**
* Get the asset URL.
*
* @since 1.0.0
*
* @param string $asset The asset to find the URL for.
* @return string The URL for the asset.
*/
private function assetUrl( $asset ) {
$assetManifest = $this->getAssetManifestItem( $asset );
return ! empty( $assetManifest['file'] )
? $this->basePath() . $assetManifest['file']
: $this->basePath() . ltrim( $asset, '/' );
}
/**
* Get the JS URL.
*
* @since 1.0.0
*
* @param string $asset The asset to find the URL for.
* @return string The URL for the asset.
*/
public function jsUrl( $asset ) {
$manifestAsset = $this->getManifestItem( $asset );
return ! empty( $manifestAsset['file'] )
? $this->basePath() . $manifestAsset['file']
: $this->basePath() . ltrim( $asset, '/' );
}
/**
* Get an item from the manifest.
*
* @since 1.0.0
*
* @param string $asset The asset to find.
* @return string Manifest object.
*/
private function getManifestItem( $asset ) {
$manifest = $this->getManifest();
$asset = ltrim( $asset, '/' );
return isset( $manifest[ $asset ] ) ? $manifest[ $asset ] : null;
}
/**
* Get the CSS asset handle.
*
* @since 1.0.0
*
* @param string $asset The asset to find the handle for.
* @return string The asset handle.
*/
public function cssHandle( $asset ) {
return "{$this->scriptHandle}/css/$asset";
}
/**
* Get the JS asset handle.
*
* @since 1.0.0
*
* @param string $asset The asset to find the handle for.
* @return string The asset handle.
*/
public function jsHandle( $asset = '' ) {
return "{$this->scriptHandle}/js/$asset";
}
/**
* Get the manifest to load assets from.
*
* @since 1.0.0
*
* @return array An array of files.
*/
private function getManifest() {
static $file = null;
if ( $file ) {
return $file;
}
$manifestJson = ''; // This is set in the view.
if ( file_exists( $this->manifestFile ) ) {
require_once $this->manifestFile;
}
$file = json_decode( $manifestJson, true );
return $file;
}
/**
* Get an item from the asset manifest.
*
* @since 1.0.0
*
* @param string $item An item to retrieve.
* @return string|null The asset item.
*/
private function getAssetManifestItem( $item ) {
$assetManifest = $this->getManifest();
return ! empty( $assetManifest[ $item ] ) ? $assetManifest[ $item ] : null;
}
/**
* Get an asset's array of URLs to import.
*
* @since 1.0.0
*
* @param string $asset The asset to find imports for.
* @return array An array of imports.
*/
private function importsUrls( $asset ) {
$urls = [];
$manifestAsset = $this->getManifestItem( $asset );
if ( ! empty( $manifestAsset['imports'] ) ) {
foreach ( $manifestAsset['imports'] as $import ) {
$importAsset = $this->getManifestItem( $import );
if ( ! empty( $importAsset['file'] ) ) {
$urls[] = $this->getPublicUrlBase() . $importAsset['file'];
// Load the import's CSS if any.
$this->loadCss( $import );
}
}
}
return $urls;
}
/**
* Returns an asset's CSS urls.
*
* @since 1.0.0
*
* @param string $asset The asset to find CSS URLs for.
* @return array An array of CSS URLs to load.
*/
private function getCssUrls( $asset ) {
$urls = [];
$manifestAsset = $this->getManifestItem( $asset );
if ( ! empty( $manifestAsset['css'] ) ) {
foreach ( $manifestAsset['css'] as $file ) {
$urls[ $file ] = $this->getPublicUrlBase() . $file;
}
}
return $urls;
}
/**
* Check if we should load the dev watcher scripts.
*
* @since 1.0.0
*
* @return boolean True if we should load the dev watcher scripts.
*/
private function shouldLoadDev() {
if ( null !== $this->shouldLoadDevScripts ) {
return $this->shouldLoadDevScripts;
}
if (
! $this->isDev ||
(
defined( 'AIOSEO_TABLE_OF_CONTENTS_LOAD_DEV_SCRIPTS' ) &&
false === AIOSEO_TABLE_OF_CONTENTS_LOAD_DEV_SCRIPTS
)
) {
$this->shouldLoadDevScripts = false;
return $this->shouldLoadDevScripts;
}
if ( ! $this->domain && ! $this->port ) {
$this->shouldLoadDevScripts = false;
return $this->shouldLoadDevScripts;
}
set_error_handler( function() {} ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
$connection = fsockopen( $this->domain, $this->port ); // phpcs:ignore WordPress.WP.AlternativeFunctions
restore_error_handler();
if ( ! $connection ) {
$this->shouldLoadDevScripts = false;
return $this->shouldLoadDevScripts;
}
$this->shouldLoadDevScripts = true;
return $this->shouldLoadDevScripts;
}
/**
* Get the path for the assets.
*
* @since 1.0.0
*
* @param bool $maybeDev Whether to try and load dev scripts.
* @return string The path for the assets.
*/
public function getAssetsPath( $maybeDev = true ) {
return $maybeDev && $this->shouldLoadDev()
? $this->getDevUrl()
: $this->basePath();
}
/**
* Finds out if a handle should be loaded as regular JS and not as modern JS module.
*
* @since 1.0.0
*
* @param string $handle The script handle.
* @return bool Should the module tag be skipped.
*/
public function skipModuleTag( $handle ) {
if ( ! aioseoTableOfContents()->helpers->stringContains( $handle, $this->jsHandle( '' ) ) ) {
return true;
}
foreach ( $this->noModuleTag as $tag ) {
if ( aioseoTableOfContents()->helpers->stringContains( $handle, $tag ) ) {
return true;
}
}
return false;
}
/**
* Normalize the assets host. Some sites manually set the WP_PLUGINS_URL
* and if that domain has www. and the site_url does not, then it will fail to load
* our assets. This doesn't fix the issue 100% because it will still fail on
* sub-domains that don't have the proper CORS headers. Those sites will need
* manual fixes.
*
* 4.1.10
*
* @param string $path The path to normalize.
* @return string The normalized path.
*/
public function normalizeAssetsHost( $path ) {
static $paths = [];
if ( isset( $paths[ $path ] ) ) {
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
}
// We need to verify the domain on the $path attribute matches
// what's in site_url() for our assets or they won't load.
$siteUrl = site_url();
$siteUrlEscaped = aioseoTableOfContents()->helpers->escapeRegex( $siteUrl );
if ( preg_match( "/^$siteUrlEscaped/i", (string) $path ) ) {
$paths[ $path ] = $path;
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
}
// We now know that the path doesn't contain the site_url().
$newPath = $path;
$siteUrlParsed = wp_parse_url( $siteUrl );
$host = aioseoTableOfContents()->helpers->escapeRegex( str_replace( 'www.', '', $siteUrlParsed['host'] ) );
$scheme = aioseoTableOfContents()->helpers->escapeRegex( $siteUrlParsed['scheme'] );
$siteUrlHasWww = preg_match( "/^{$scheme}:\/\/www\.$host/", (string) $siteUrl );
$pathHasWww = preg_match( "/^{$scheme}:\/\/www\.$host/", (string) $path );
// Check if the path contains www.
if ( $pathHasWww && ! $siteUrlHasWww ) {
// If the path contains www., we want to strip it out.
$newPath = preg_replace( "/^({$scheme}:\/\/)(www\.)($host)/", '$1$3', (string) $path );
}
// Check if the site_url contains www.
if ( $siteUrlHasWww && ! $pathHasWww ) {
// If the site_url contains www., we want to add it in to the path.
$newPath = preg_replace( "/^({$scheme}:\/\/)($host)/", '$1www.$2', (string) $path );
}
$paths[ $path ] = $newPath;
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
}
/**
* Returns the public URL base.
*
* @since 1.0.0
*
* @return string The URL base.
*/
private function getPublicUrlBase() {
return $this->shouldLoadDev() ? $this->getDevUrl() . 'dist/assets/' : $this->basePath();
}
/**
* Returns the base path URL.
*
* @since 1.0.0
*
* @return string The base path URL.
*/
private function basePath() {
return $this->normalizeAssetsHost( plugins_url( 'dist/assets/', AIOSEO_TABLE_OF_CONTENTS_FILE ) );
}
}
@@ -0,0 +1,637 @@
<?php
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles our cache.
*
* @since 1.0.0
*/
class Cache {
/**
* The name of our cache table.
*
* @since 1.0.0
*
* @var string
*/
private $table = 'aioseo_table_of_contents_cache';
/**
* Our cache.
*
* @since 1.0.0
*
* @var array
*/
private static $cache = [];
/**
* Prefix for this cache.
*
* @since 1.0.0
*
* @var string
*/
protected $prefix = 'aioseo_table_of_contents_';
/**
* Whether to use transients as fallback.
*
* @since 1.0.0
*
* @var bool|null
*/
private $useTransientFallback = null;
/**
* Class constructor.
*
* @since 4.7.8
*/
public function __construct() {
add_action( 'init', [ $this, 'checkIfTableExists' ] ); // This needs to run on init because the DB
// class gets instantiated along with the cache class.
}
/**
* Checks if the cache table exists and creates it if it doesn't.
*
* @since 4.7.8
*
* @return void
*/
public function checkIfTableExists() {
if ( ! aioseoTableOfContents()->core->db->tableExists( $this->table ) ) {
aioseoTableOfContents()->preUpdates->createCacheTable();
}
// Table is guaranteed to exist now. Skip future re-checks this request
// and refresh the transient so isCacheTableAvailable() won't query next request either.
$this->useTransientFallback = false;
set_transient( 'aioseo_plugin_cache_table_exists', 1, WEEK_IN_SECONDS );
}
/**
* Returns the cache value if it exists and isn't expired.
*
* @since 1.0.0
* @version 202607 Renamed key to name
*
* @param string $key The key of the cache. Use a '%' for a LIKE query.
* @return mixed The value or null if the cache does not exist.
*/
public function get( $key ) {
$key = $this->prepareKey( $key );
// Check if we're supposed to do a LIKE get.
$isLikeGet = preg_match( '/%/', (string) $key );
// Check static cache first (only for non-LIKE queries)
if ( ! $isLikeGet && isset( self::$cache[ $key ] ) ) {
return self::$cache[ $key ];
}
// Check if we should use transients
if ( ! $this->isCacheTableAvailable() ) {
if ( $isLikeGet ) {
// Use custom query for LIKE patterns
return $this->getTransientLike( $key );
}
$value = $this->getTransient( $key );
if ( null !== $value ) {
self::$cache[ $key ] = $value;
}
return $value;
}
$result = aioseoTableOfContents()->core->db
->start( $this->table )
->select( '`name`, `value`, `is_object`' )
->whereRaw( '( `expiration` IS NULL OR `expiration` > \'' . aioseoTableOfContents()->helpers->timeToMysql( time() ) . '\' )' );
if ( $isLikeGet ) {
$key = esc_sql( aioseoTableOfContents()->core->db->db->esc_like( $key ) );
$result->whereRaw( '`name` LIKE \'' . $key . '\'' );
} else {
$key = esc_sql( $key );
$result->where( 'name', $key );
}
$result->output( ARRAY_A )->run();
// If we have nothing in the cache, let's return null.
$values = $result->nullSet() ? null : $result->result();
// If we have something, let's normalize it.
if ( $values ) {
foreach ( $values as &$value ) {
// Use is_object flag to determine decode type: if 0 (false) decode to array, if 1 (true) decode to object.
$value['value'] = json_decode( $value['value'], empty( $value['is_object'] ) );
}
// Return only the single cache value.
if ( ! $isLikeGet ) {
$values = $values[0]['value'];
}
}
// Return values without a static cache.
// This is here because clearing the LIKE cache is not simple.
if ( $isLikeGet ) {
return $values;
}
self::$cache[ $key ] = $values;
return self::$cache[ $key ];
}
/**
* Updates the given cache or creates it if it doesn't exist.
*
* @since 1.0.0
* @version 202607 Renamed key to name
*
* @param string $key The name of the cache.
* @param mixed $value The value.
* @param int $expiration The expiration time in seconds. Defaults to 24 hours. 0 to no expiration.
* @return void
*/
public function update( $key, $value, $expiration = DAY_IN_SECONDS ) {
$key = $this->prepareKey( $key );
// If the value is null we'll convert it and give it a shorter expiration.
if ( null === $value ) {
$value = false;
$expiration = 10 * MINUTE_IN_SECONDS;
}
// Check if we should use transients
if ( ! $this->isCacheTableAvailable() ) {
$this->updateTransient( $key, $value, $expiration );
$this->updateStatic( $key, $value );
return;
}
$isObject = is_object( $value );
$jsonValue = wp_json_encode( $value );
$expiration = 0 < $expiration ? aioseoTableOfContents()->helpers->timeToMysql( time() + $expiration ) : null;
// Handle JSON encoding errors.
if ( false === $jsonValue && JSON_ERROR_NONE !== json_last_error() ) {
if ( aioseoTableOfContents()->helpers->isDev() ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( 'AIOSEO Plugin Cache: JSON encode failed for name "' . $key . '" - ' . json_last_error_msg() );
}
return;
}
aioseoTableOfContents()->core->db->insert( $this->table )
->set( [
'name' => $this->prepareKey( $key ),
'value' => $jsonValue,
'is_object' => $isObject,
'expiration' => $expiration,
'created' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
'updated' => aioseoTableOfContents()->helpers->timeToMysql( time() )
] )->onDuplicate( [
'value' => $jsonValue,
'is_object' => $isObject,
'expiration' => $expiration,
'updated' => aioseoTableOfContents()->helpers->timeToMysql( time() )
] )
->run();
$this->updateStatic( $key, $value );
}
/**
* Deletes the cache record with the given key.
*
* @since 1.0.0
*
* @param string $key The name of the cache.
* @return void
*/
public function delete( $key ) {
$key = $this->prepareKey( $key );
// Check if we should use transients
if ( ! $this->isCacheTableAvailable() ) {
$this->deleteTransient( $key );
$this->clearStatic( $key );
return;
}
aioseoTableOfContents()->core->db->delete( $this->table )
->where( 'name', $key )
->run();
$this->clearStatic( $key );
}
/**
* Prepares the key before using the cache.
*
* @since 1.0.0
*
* @param string $key The name of the cache to prepare.
* @return string The prepared key.
*/
private function prepareKey( $key ) {
$key = trim( (string) $key );
$key = $this->prefix && 0 !== strpos( $key, $this->prefix ) ? $this->prefix . $key : $key;
if ( aioseoTableOfContents()->helpers->isDev() && 80 < mb_strlen( $key, 'UTF-8' ) ) {
throw new \Exception( 'You are using a cache name that is too large, shorten your name and try again: [' . esc_html( $key ) . ']' );
}
return $key;
}
/**
* Clears all of our cache.
*
* @since 1.0.0
*
* @return void
*/
public function clear() {
if ( $this->prefix ) {
$this->clearPrefix( '' );
return;
}
// Check if we should use transients
if ( ! $this->isCacheTableAvailable() ) {
// Delete all AIOSEO plugin cache transients
$this->deleteAllTransients();
$this->clearStatic();
return;
}
aioseoTableOfContents()->core->db->truncate( $this->table )->run();
$this->clearStatic();
}
/**
* Clears all of our cache under a certain prefix.
*
* @since 1.0.0
*
* @param string $prefix A prefix to clear or empty to clear everything.
* @return void
*/
public function clearPrefix( $prefix ) {
$prefix = $this->prepareKey( $prefix );
// Check if we should use transients
if ( ! $this->isCacheTableAvailable() ) {
// Delete transients by prefix
$this->deleteTransientsByPrefix( $prefix );
$this->clearStaticPrefix( $prefix );
return;
}
aioseoTableOfContents()->core->db->delete( $this->table )
->whereRaw( "`name` LIKE '$prefix%'" )
->run();
$this->clearStaticPrefix( $prefix );
}
/**
* Clears all of our static in-memory cache of a prefix.
*
* @since 1.0.0
*
* @param string $prefix The prefix to clear.
* @return void
*/
private function clearStaticPrefix( $prefix ) {
$prefix = $this->prepareKey( $prefix );
foreach ( array_keys( self::$cache ) as $key ) {
if ( 0 === strpos( $key, $prefix ) ) {
unset( self::$cache[ $key ] );
}
}
}
/**
* Clears all of our static in-memory cache.
*
* @since 1.0.0
* @version 202607 Renamed key to name
*
* @param string $key The name of the cache to clear.
* @return void
*/
private function clearStatic( $key = null ) {
if ( empty( $key ) ) {
self::$cache = [];
return;
}
unset( self::$cache[ $this->prepareKey( $key ) ] );
}
/**
* Updates the static in-memory cache for a single given key.
*
* @since 1.0.0
*
* @param string $key The key to update.
* @param mixed $value The value to cache.
* @return void
*/
private function updateStatic( $key = null, $value = null ) {
if ( empty( $key ) ) {
$this->clearStatic( $key );
return;
}
self::$cache[ $this->prepareKey( $key ) ] = $value;
}
/**
* Checks if the cache table is available for use.
*
* @since 1.0.0
*
* @return bool True if table exists and is accessible.
*/
private function isCacheTableAvailable() {
if ( null !== $this->useTransientFallback ) {
return ! $this->useTransientFallback;
}
// Check transient first to avoid a DB query on every request.
if ( get_transient( 'aioseo_plugin_cache_table_exists' ) ) {
$this->useTransientFallback = false;
return true;
}
// Transient not set — check the DB directly (avoids circular dependency with Database::tableExists).
global $wpdb;
$tableName = $wpdb->prefix . $this->table;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$tableExists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tableName ) );
if ( ! $tableExists ) {
$this->useTransientFallback = true;
return false;
}
// Verify the table has the expected 'name' column. During upgrades from older versions
// the table may still have the legacy 'key' column. If the migration hasn't run yet,
// we must fall back to transients to avoid "Unknown column 'name'" errors.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$nameColumnExists = $wpdb->get_var(
$wpdb->prepare(
"SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = %s
AND COLUMN_NAME = 'name'",
$tableName
)
);
if ( ! $nameColumnExists ) {
$this->useTransientFallback = true;
return false;
}
set_transient( 'aioseo_plugin_cache_table_exists', 1, WEEK_IN_SECONDS );
$this->useTransientFallback = false;
return true;
}
/**
* Gets the transient name for a cache key.
*
* @since 1.0.0
*
* @param string $key The cache key.
* @return string The transient name.
*/
private function getTransientName( $key ) {
// Store the original key to maintain compatibility with LIKE queries
return 'aioseo_plugin_cache_' . $key;
}
/**
* Gets a value from transients.
*
* @since 1.0.0
*
* @param string $key The cache key.
* @return mixed The cached value or null.
*/
private function getTransient( $key ) {
$transientName = $this->getTransientName( $key );
$data = get_transient( $transientName );
if ( false === $data ) {
return null;
}
// Decode the wrapper structure
$wrapper = json_decode( $data, true );
if ( ! is_array( $wrapper ) || ! isset( $wrapper['value'] ) ) {
return null;
}
// Decode JSON value using is_object flag (matching database cache behavior)
// If is_object is 1 (true), decode to object; if 0 (false), decode to array
$decoded = json_decode( $wrapper['value'], empty( $wrapper['is_object'] ) );
return $decoded;
}
/**
* Gets multiple transients using a LIKE query.
*
* @since 1.0.0
*
* @param string $pattern The pattern to match (with % wildcards).
* @return mixed Array of matching cache entries or null.
*/
private function getTransientLike( $pattern ) {
global $wpdb;
$transientPattern = $this->getTransientName( $pattern );
// Query for non-expired transients matching the pattern
$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"SELECT REPLACE(option_name, '_transient_', '') as `key`, option_value as `value`
FROM {$wpdb->options}
WHERE option_name LIKE %s
AND option_name NOT LIKE %s
AND (
NOT EXISTS (
SELECT 1 FROM {$wpdb->options} timeout
WHERE timeout.option_name = CONCAT('_transient_timeout_', REPLACE(option_name, '_transient_', ''))
AND CAST(timeout.option_value AS UNSIGNED) > 0
AND CAST(timeout.option_value AS UNSIGNED) < UNIX_TIMESTAMP()
)
)",
'_transient_' . implode( '%', array_map( [ $wpdb, 'esc_like' ], explode( '%', $transientPattern ) ) ),
'_transient_timeout_%'
),
ARRAY_A
);
if ( empty( $results ) ) {
return null;
}
// Decode JSON values with is_object flag
foreach ( $results as &$result ) {
$result['key'] = str_replace( 'aioseo_plugin_cache_', '', $result['key'] );
// Decode the wrapper structure
$wrapper = json_decode( $result['value'], true );
if ( is_array( $wrapper ) && isset( $wrapper['value'] ) ) {
// Decode JSON value using is_object flag (matching database cache behavior)
// If is_object is 1 (true), decode to object; if 0 (false), decode to array
$result['value'] = json_decode( $wrapper['value'], empty( $wrapper['is_object'] ) );
} else {
// Fallback for malformed data
$result['value'] = null;
}
}
return $results;
}
/**
* Updates a transient value.
*
* @since 1.0.0
*
* @param string $key The cache key.
* @param mixed $value The value to cache.
* @param int $expiration Expiration in seconds.
* @return void
*/
private function updateTransient( $key, $value, $expiration ) {
$transientName = $this->getTransientName( $key );
// Detect if value is an object to match database cache behavior
$isObject = is_object( $value );
// Encode as JSON to match database cache behavior
$jsonValue = wp_json_encode( $value );
if ( false === $jsonValue && JSON_ERROR_NONE !== json_last_error() ) {
if ( aioseoTableOfContents()->helpers->isDev() ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( 'AIOSEO Plugin Cache: JSON encode failed for key "' . $key . '" - ' . json_last_error_msg() );
}
return;
}
// Wrap the value with metadata including is_object flag
$wrapper = [
'value' => $jsonValue,
'is_object' => $isObject
];
$wrappedValue = wp_json_encode( $wrapper );
if ( false === $wrappedValue ) {
if ( aioseoTableOfContents()->helpers->isDev() ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( 'AIOSEO Plugin Cache: JSON encode failed for wrapper on key "' . $key . '"' );
}
return;
}
set_transient( $transientName, $wrappedValue, $expiration );
}
/**
* Deletes a transient.
*
* @since 1.0.0
*
* @param string $key The cache key.
* @return void
*/
private function deleteTransient( $key ) {
$transientName = $this->getTransientName( $key );
delete_transient( $transientName );
}
/**
* Deletes all transients matching a prefix.
*
* @since 1.0.0
*
* @param string $prefix The prefix to match.
* @return void
*/
private function deleteTransientsByPrefix( $prefix ) {
global $wpdb;
$escapedPrefix = $wpdb->esc_like( $this->getTransientName( $prefix ) );
// Delete both the transient and its timeout
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"DELETE FROM {$wpdb->options}
WHERE option_name LIKE %s
OR option_name LIKE %s",
'_transient_' . $escapedPrefix . '%',
'_transient_timeout_' . $escapedPrefix . '%'
)
);
}
/**
* Deletes all AIOSEO plugin cache transients.
*
* @since 1.0.0
*
* @return void
*/
private function deleteAllTransients() {
global $wpdb;
$prefix = 'aioseo_plugin_cache_%';
// Delete both transients and their timeouts
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"DELETE FROM {$wpdb->options}
WHERE option_name LIKE %s
OR option_name LIKE %s",
'_transient_' . $wpdb->esc_like( $prefix ),
'_transient_timeout_' . $wpdb->esc_like( $prefix )
)
);
}
}
@@ -0,0 +1,95 @@
<?php
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Options;
use AIOSEO\TableOfContents\Utils;
/**
* Loads core classes.
*
* @since 1.0.0
*/
class Core {
/**
* DB class instance.
*
* @since 1.1.0
*
* @var Database
*/
public $db = null;
/**
* Filesystem class instance.
*
* @since 1.1.0
*
* @var Filesystem
*/
public $fs = null;
/**
* Assets class instance.
*
* @since 1.1.0
*
* @var Assets
*/
public $assets = null;
/**
* Cache class instance.
*
* @since 1.1.0
*
* @var Cache
*/
public $cache = null;
/**
* NetworkCache class instance.
*
* @since 1.1.0
*
* @var NetworkCache
*/
public $networkCache = null;
/**
* Options Cache class instance.
*
* @since 1.1.0
*
* @var \AIOSEO\TableOfContents\Options\Cache
*/
public $optionsCache = null;
/**
* Uninstall class instance.
*
* @since 1.1.0
*
* @var Uninstall
*/
public $uninstall = null;
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
$this->db = new Database();
$this->fs = new Filesystem( $this );
$this->assets = new Assets( $this );
$this->cache = new Cache();
$this->networkCache = new NetworkCache();
$this->optionsCache = new Options\Cache();
$this->uninstall = new Uninstall();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,280 @@
<?php
// phpcs:disable WordPress.WP.AlternativeFunctions
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Interface for the filesystem.
*
* @since 1.0.0
*/
class Filesystem {
/**
* Holds the WP filesystem instance.
*
* @since 1.0.0
*
* @var \WP_Filesystem_Base
*/
public $fs = null;
/**
* Core class instance.
*
* @since 1.1.0
*
* @var Core
*/
public $core = null;
/**
* Class constructor.
*
* @since 1.0.0
*
* @param Core $core The Core class.
* @param array $args Optional arguments needed to construct the class with.
*/
public function __construct( $core, $args = [] ) {
$this->core = $core;
$this->init( $args );
}
/**
* Initialize the filesystem.
*
* @since 1.0.0
*
* @param array $args List of arguments for the WP_Filesystem class.
* @return void
*/
public function init( $args = [] ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem( $args );
global $wp_filesystem;
if ( is_object( $wp_filesystem ) ) {
$this->fs = $wp_filesystem;
}
}
/**
* Wrapper method to check if a file exists.
*
* @since 1.0.0
*
* @param string $filename The filename to check if it exists.
* @return bool Returns true if the file or dir specified exists; false otherwise.
*/
public function exists( $filename ) {
if ( ! $this->isWpfsValid() ) {
return @file_exists( $filename );
}
return $this->fs->exists( $filename );
}
/**
* Retrieve the contents of a file.
*
* @since 1.0.0
*
* @param string $filename The filename to get the contents for.
* @return string|bool The function returns the read data or false on failure.
*/
public function getContents( $filename ) {
if ( ! $this->exists( $filename ) ) {
return false;
}
if ( ! $this->isWpfsValid() ) {
return @file_get_contents( $filename );
}
return $this->fs->get_contents( $filename );
}
/**
* Reads entire file into an array.
*
* @since 1.0.0
*
* @param string $file Path to the file.
* @return array|bool File contents in an array on success, false on failure.
*/
public function getContentsArray( $file ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $this->isWpfsValid() ) {
return @file( $file );
}
return $this->fs->get_contents_array( $file );
}
/**
* Sets the access and modification times of a file.
* Note: If $file doesn't exist, it will be created.
*
* @since 1.0.0
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file. Default 0.
* @param int $atime Optional. Access time to set for file. Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
if ( 0 === $time ) {
$time = time();
}
if ( 0 === $atime ) {
$atime = time();
}
if ( ! $this->isWpfsValid() ) {
return @touch( $file, $time, $atime );
}
return $this->fs->touch( $file, $time, $atime );
}
/**
* Writes a string to a file.
*
* @since 1.0.0
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644. Default false.
* @return int|bool True on success, false on failure.
*/
public function putContents( $file, $contents, $mode = false ) {
if ( ! $this->isWpfsValid() ) {
return @file_put_contents( $file, $contents );
}
return $this->fs->put_contents( $file, $contents, $mode );
}
/**
* Checks if a file or dir is writable.
*
* @since 1.0.0
*
* @param string $file Path to file or dir.
* @return bool Whether $file is writable.
*/
public function isWritable( $file ) {
if ( ! $this->isWpfsValid() ) {
return @is_writable( $file );
}
return $this->fs->is_writable( $file );
}
/**
* Checks if a file is readable.
*
* @since 1.0.0
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function isReadable( $file ) {
if ( ! $this->isWpfsValid() ) {
return @is_readable( $file );
}
return $this->fs->is_readable( $file );
}
/**
* Gets the file size (in bytes).
*
* @since 1.0.0
*
* @param string $file Path to file.
* @return int|bool Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
if ( ! $this->isWpfsValid() ) {
return @filesize( $file );
}
return $this->fs->size( $file );
}
/**
* Checks if resource is a file.
*
* @since 1.0.0
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function isFile( $file ) {
if ( ! $this->isWpfsValid() ) {
return @is_file( $file );
}
return $this->fs->is_file( $file );
}
/**
* Checks if resource is a directory.
*
* @since 1.0.0
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function isDir( $path ) {
if ( ! $this->isWpfsValid() ) {
return @is_dir( $path );
}
return $this->fs->is_dir( $path );
}
/**
* A simple check to ensure that the WP_Filesystem is valid.
*
* @since 1.0.0
*
* @return bool True if valid, false if not.
*/
public function isWpfsValid() {
if (
! is_a( $this->fs, 'WP_Filesystem_Base' ) ||
(
// Errors is a WP_Error object.
! empty( $this->fs->errors ) &&
// We check if the errors array is empty for compatibility with WP < 5.1.
! empty( $this->fs->errors->errors )
)
) {
return false;
}
return true;
}
/**
* In order to prevent conflicts, we need to return a clone.
*
* @since 1.0.0
*
* @return Filesystem The cloned Filesystem object.
*/
public function noConflict() {
return clone $this;
}
}
@@ -0,0 +1,115 @@
<?php
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles our network cache.
*
* @since 1.0.0
*/
class NetworkCache extends Cache {
/**
* Returns the cache value for a key if it exists and is not expired.
*
* @since 1.0.0
*
* @param string $key The cache key name. Use a '%' for a like query.
* @return mixed The value or null if the cache does not exist.
*/
public function get( $key ) {
if ( ! is_multisite() ) {
return parent::get( $key );
}
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
$value = parent::get( $key );
aioseoTableOfContents()->helpers->restoreCurrentBlog();
return $value;
}
/**
* Updates the given cache or creates it if it doesn't exist.
*
* @since 1.0.0
*
* @param string $key The cache key name.
* @param mixed $value The value.
* @param int $expiration The expiration time in seconds. Defaults to 24 hours. 0 to no expiration.
* @return void
*/
public function update( $key, $value, $expiration = DAY_IN_SECONDS ) {
if ( ! is_multisite() ) {
parent::update( $key, $value, $expiration );
return;
}
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
parent::update( $key, $value, $expiration );
aioseoTableOfContents()->helpers->restoreCurrentBlog();
}
/**
* Deletes the given cache key.
*
* @since 1.0.0
*
* @param string $key The cache key.
* @return void
*/
public function delete( $key ) {
if ( ! is_multisite() ) {
parent::delete( $key );
return;
}
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
parent::delete( $key );
aioseoTableOfContents()->helpers->restoreCurrentBlog();
}
/**
* Clears all of our cache.
*
* @since 1.0.0
*
* @return void
*/
public function clear() {
if ( ! is_multisite() ) {
parent::clear();
return;
}
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
parent::clear();
aioseoTableOfContents()->helpers->restoreCurrentBlog();
}
/**
* Clears all of our cache under a certain prefix.
*
* @since 1.0.0
*
* @param string $prefix A prefix to clear or empty to clear everything.
* @return void
*/
public function clearPrefix( $prefix ) {
if ( ! is_multisite() ) {
parent::clearPrefix( $prefix );
return;
}
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
parent::clearPrefix( $prefix );
aioseoTableOfContents()->helpers->restoreCurrentBlog();
}
}
@@ -0,0 +1,66 @@
<?php
namespace AIOSEO\TableOfContents\Core;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin deinstallation.
*
* @since 1.0.0
*/
class Uninstall {
/**
* Removes all our tables and options.
*
* @since 1.0.0
*
* @param bool $force Whether we should ignore the uninstall option or not. We ignore it when we reset all data via the Debug Panel.
* @return void
*/
public function dropData( $force = false ) {
// Confirm that user has decided to remove all data, otherwise stop.
if (
! $force &&
( ! aioseoTableOfContents()->options->advanced->enable || ! aioseoTableOfContents()->options->advanced->uninstall )
) {
return;
}
// Delete all our custom tables.
global $wpdb;
foreach ( $this->getDbTables() as $tableName ) {
$wpdb->query( 'DROP TABLE IF EXISTS ' . $tableName ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
// Delete all the plugin settings.
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'aioseo\_table_of_contents\_%'" );
// Remove any transients we've left behind.
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_aioseo\_table_of_contents\_%'" );
// Delete all entries from the action scheduler table.
$wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE hook LIKE 'aioseo\_table_of_contents\_%'" );
$wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_groups WHERE slug = 'aioseo\_table_of_contents'" );
}
/**
* Returns all the DB tables with their prefix.
*
* @since 1.0.0
*
* @return array List of tables.
*/
private function getDbTables() {
global $wpdb;
$tables = [];
foreach ( aioseoTableOfContents()->core->db->customTables as $tableName ) {
$tables[] = $wpdb->prefix . $tableName;
}
return $tables;
}
}
@@ -0,0 +1,99 @@
<?php
namespace AIOSEO\TableOfContents\Db;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Database Schema for Table of Contents Plus tables.
*
* This class defines the complete, current state of all database tables
* used by the Table of Contents Plus addon. These schemas are used with WordPress's
* dbDelta() function to automatically create tables and add missing columns.
*
* @since 202607
*/
class Schema {
/**
* Get all table schemas for Table of Contents Plus tables.
*
* Returns an array of CREATE TABLE statements for all tables
* used by Table of Contents Plus. These will be processed by dbDelta() to ensure
* the database schema matches the definitions.
*
* @since 202607
*
* @return array Array of SQL CREATE TABLE statements.
*/
public function getSchema() {
return [
$this->getNotificationsTableSchema(),
$this->getCacheTableSchema()
];
}
/**
* Get the schema for aioseo_table_of_contents_notifications table.
*
* @since 202607
*
* @return string SQL CREATE TABLE statement.
*/
private function getNotificationsTableSchema() {
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_notifications';
$charsetCollate = aioseoTableOfContents()->core->db->db->get_charset_collate();
return "CREATE TABLE {$tableName} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
notification_id bigint(20) unsigned DEFAULT NULL,
notification_name varchar(255) DEFAULT NULL,
slug varchar(13) NOT NULL,
title text NOT NULL,
content longtext NOT NULL,
type varchar(64) NOT NULL,
level text NOT NULL,
start datetime DEFAULT NULL,
end datetime DEFAULT NULL,
button1_label varchar(255) DEFAULT NULL,
button1_action varchar(255) DEFAULT NULL,
button2_label varchar(255) DEFAULT NULL,
button2_action varchar(255) DEFAULT NULL,
dismissed tinyint(1) NOT NULL DEFAULT 0,
new tinyint(1) NOT NULL DEFAULT 1,
created datetime NOT NULL,
updated datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY ndx__aioseo_table_of_contents_notifications_slug (slug),
KEY ndx__aioseo_table_of_contents_notifications_dates (start, end),
KEY ndx__aioseo_table_of_contents_notifications_type (type),
KEY ndx__aioseo_table_of_contents_notifications_dismissed (dismissed)
) {$charsetCollate};";
}
/**
* Get the schema for aioseo_table_of_contents_cache table.
*
* @since 202607
*
* @return string SQL CREATE TABLE statement.
*/
public function getCacheTableSchema() {
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
$charsetCollate = aioseoTableOfContents()->core->db->db->get_charset_collate();
return "CREATE TABLE {$tableName} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
name varchar(80) NOT NULL,
value longtext NOT NULL,
is_object TINYINT(1) DEFAULT 0,
expiration datetime DEFAULT NULL,
created datetime NOT NULL,
updated datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY ndx_aioseo_table_of_contents_cache_name (name),
KEY ndx_aioseo_table_of_contents_cache_expiration (expiration)
) {$charsetCollate};";
}
}
@@ -0,0 +1,56 @@
<?php
namespace AIOSEO\TableOfContents\Main;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin (de)activation.
*
* @since 1.0.0
*/
class Activate {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
register_activation_hook( AIOSEO_TABLE_OF_CONTENTS_FILE, [ $this, 'activate' ] );
register_deactivation_hook( AIOSEO_TABLE_OF_CONTENTS_FILE, [ $this, 'deactivate' ] );
}
/**
* Runs on activation.
*
* @since 1.0.0
*
* @return void
*/
public function activate() {
aioseoTableOfContents()->access->addCapabilities();
// Set the activation timestamps.
$time = time();
aioseoTableOfContents()->internalOptions->internal->activated = $time;
if ( ! aioseoTableOfContents()->internalOptions->internal->firstActivated ) {
aioseoTableOfContents()->internalOptions->internal->firstActivated = $time;
}
aioseoTableOfContents()->core->cache->clear();
}
/**
* Runs on deactivation.
*
* @since 1.0.0
*
* @return void
*/
public function deactivate() {
aioseoTableOfContents()->access->removeCapabilities();
}
}
@@ -0,0 +1,28 @@
<?php
namespace AIOSEO\TableOfContents\Main;
use AIOSEO\TableOfContents\Highlighter;
use AIOSEO\TableOfContents\Links;
use AIOSEO\TableOfContents\LinkStatus;
use AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Main class where core features are handled/registered.
*
* @since 1.0.0
*/
class Main {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
new Activate();
}
}
@@ -0,0 +1,68 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contract for a discrete, individually-logged migration.
*
* Migrations registered with the {@see MigrationRunner} are tracked by name in
* the migration log option. The runner uses {@see self::verify()} as the source
* of truth for completion — up()'s exit status is not trusted, because that's
* the failure mode that historically left sites half-applied (the version flag
* advanced even when the work hadn't actually landed).
*
* @since 202607
*/
interface Migration {
/**
* Stable identifier. Becomes the key in the migration log option.
*
* IMPORTANT: never rename after the migration has shipped — the runner
* keys log entries off this string. A rename would cause the migration
* to re-run on every site that already had it.
*
* Convention: snake_case verb_noun, no version suffix.
*
* @since 202607
*
* @return string
*/
public function name();
/**
* Release this migration was introduced in. Diagnostic only.
*
* @since 202607
*
* @return string
*/
public function version();
/**
* Perform the migration. Throw on hard failure — the runner catches and
* logs as status = 0 so the migration is retried on the next request.
*
* Must be idempotent: the runner may invoke up() multiple times across
* retries (e.g. when verify() returned false after a previous up()).
*
* @since 202607
*
* @return void
*/
public function up();
/**
* Post-condition check. Returns true when the migration's intended state
* is in place. Called BEFORE up() to short-circuit when already applied,
* and AFTER up() to confirm success.
*
* @since 202607
*
* @return bool
*/
public function verify();
}
@@ -0,0 +1,102 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Wraps the `aioseo_table_of_contents_migrations_log` option that tracks
* per-migration execution state for the {@see MigrationRunner}.
*
* The option is stored without autoload — healthy sites short-circuit on
* `lastSchemaVersion === aioseoTableOfContents()->version` before the runner ever
* reads the log, so paying autoload overhead on every request would be wasted
* work.
*
* @since 202607
*/
class MigrationLog {
/**
* Option name. Per-plugin namespacing means addons can each own their own
* log without colliding with the main plugin's entries.
*
* @since 202607
*
* @var string
*/
private $optionName = 'aioseo_table_of_contents_migrations_log';
/**
* Per-request cache. The runner can call read() multiple times across
* migrations within one request — no need to round-trip wp_options each
* time.
*
* Null means "not loaded yet"; array (possibly empty) means "loaded".
*
* @since 202607
*
* @var array|null
*/
private $cache = null;
/**
* Read the full log.
*
* @since 202607
*
* @return array Keyed by migration name. Empty array when the option does not exist.
*/
public function read() {
if ( null !== $this->cache ) {
return $this->cache;
}
$raw = get_option( $this->optionName, '' );
if ( empty( $raw ) ) {
$this->cache = [];
return $this->cache;
}
$decoded = json_decode( $raw, true );
if ( ! is_array( $decoded ) ) {
$this->cache = [];
return $this->cache;
}
$this->cache = $decoded;
return $this->cache;
}
/**
* Write the full log.
*
* On first write the option is created with autoload disabled. Subsequent
* writes preserve that flag automatically — WordPress's update_option()
* does not change autoload on existing options.
*
* @since 202607
*
* @param array $log Log keyed by migration name.
* @return void
*/
public function write( array $log ) {
$encoded = wp_json_encode( $log );
if ( false === $encoded ) {
return;
}
$existing = get_option( $this->optionName, null );
if ( null === $existing ) {
add_option( $this->optionName, $encoded, '', 'no' );
} else {
update_option( $this->optionName, $encoded );
}
$this->cache = $log;
}
}
@@ -0,0 +1,205 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Discovers, executes, and logs {@see Migration} instances.
*
* The runner closes the half-applied failure mode: the version flag is only
* advanced when EVERY registered migration's verify() returns true. A
* concurrent-request lock loser bails without touching state; a lock holder
* that dies mid-migration leaves the relevant log entry at status = 0 (or
* absent), and the runner retries on the next request until verify() actually
* passes.
*
* @since 202607
*/
class MigrationRunner {
/**
* Registered migrations, in registration order.
*
* @since 202607
*
* @var Migration[]
*/
private $migrations = [];
/**
* Log accessor.
*
* @since 202607
*
* @var MigrationLog
*/
private $log;
/**
* Lock name. MySQL GET_LOCK is per-connection, so this serializes across
* concurrent PHP processes for the same site.
*
* @since 202607
*
* @var string
*/
private $lockName = 'aioseo_table_of_contents_migration_runner';
/**
* @since 202607
*/
public function __construct() {
$this->log = new MigrationLog();
}
/**
* Register a migration. Order is preserved — later registrations run
* after earlier ones within the same request.
*
* @since 202607
*
* @param Migration $migration The migration to register.
* @return void
*/
public function register( Migration $migration ) {
$this->migrations[] = $migration;
}
/**
* Execute pending migrations.
*
* Short-circuits early when the recorded schema version matches the
* current plugin version — healthy sites never touch the log option.
* Lock losers exit silently and do NOT advance any version flag, so a
* future-bumped lastSchemaVersion can't strand work.
*
* @since 202607
*
* @return void
*/
public function run() {
if ( aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion === aioseoTableOfContents()->version ) {
return;
}
if ( empty( $this->migrations ) ) {
aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion = aioseoTableOfContents()->version;
return;
}
if ( ! aioseoTableOfContents()->core->db->acquireLock( $this->lockName, 0 ) ) {
return;
}
try {
$log = $this->log->read();
$allDone = true;
foreach ( $this->migrations as $migration ) {
$name = $migration->name();
if ( $this->verifySafely( $migration ) ) {
if ( ! isset( $log[ $name ] ) || 1 !== ( $log[ $name ]['status'] ?? 0 ) ) {
$log[ $name ] = $this->successEntry( $migration, $log );
}
continue;
}
try {
$migration->up();
$verified = $this->verifySafely( $migration );
$log[ $name ] = $verified
? $this->successEntry( $migration, $log )
: $this->failureEntry( $migration, $log, 'verify() returned false after up()' );
if ( ! $verified ) {
$allDone = false;
}
} catch ( \Throwable $e ) {
$log[ $name ] = $this->failureEntry( $migration, $log, $e->getMessage() );
$allDone = false;
}
}
$this->log->write( $log );
if ( $allDone ) {
aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion = aioseoTableOfContents()->version;
}
} finally {
// Explicit release shrinks the hold window to the migration work itself.
// acquireLock() also registers a shutdown function as belt-and-braces in
// case execution exits before we reach this point.
aioseoTableOfContents()->core->db->releaseLock( $this->lockName );
}
}
/**
* Wrap verify() so a throwing implementation degrades to "not verified"
* instead of bringing down the runner. The error surfaces via the log's
* failureEntry on the next up()/verify() cycle.
*
* @since 202607
*
* @param Migration $migration The migration to verify.
* @return bool
*/
private function verifySafely( Migration $migration ) {
try {
return (bool) $migration->verify();
} catch ( \Throwable $e ) {
return false;
}
}
/**
* Build a success log entry, preserving the prior attempts counter so
* support can see how many retries it took to land.
*
* @since 202607
*
* @param Migration $migration The migration.
* @param array $log The current log state.
* @return array
*/
private function successEntry( Migration $migration, array $log ) {
$name = $migration->name();
$attempts = isset( $log[ $name ]['attempts'] ) ? (int) $log[ $name ]['attempts'] : 0;
return [
'version' => $migration->version(),
'ran_at' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
'status' => 1,
'attempts' => $attempts + 1,
'last_error' => null
];
}
/**
* Build a failure log entry, incrementing attempts so retry pressure is
* visible in the log.
*
* @since 202607
*
* @param Migration $migration The migration.
* @param array $log The current log state.
* @param string $error Reason for the failure.
* @return array
*/
private function failureEntry( Migration $migration, array $log, $error ) {
$name = $migration->name();
$attempts = isset( $log[ $name ]['attempts'] ) ? (int) $log[ $name ]['attempts'] : 0;
return [
'version' => $migration->version(),
'ran_at' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
'status' => 0,
'attempts' => $attempts + 1,
'last_error' => $error
];
}
}
@@ -0,0 +1,65 @@
<?php
namespace AIOSEO\TableOfContents\Main;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This class contains pre-updates necessary for the main Updates class to run.
*
* @since 1.0.0
*/
class PreUpdates {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
// We don't want an AJAX request check here since the plugin might be installed/activated for the first time via AJAX.
// If that's the case, the cache table needs to be created before the cron job runs.
if ( wp_doing_cron() ) {
return;
}
$lastActiveVersion = aioseoTableOfContents()->internalOptions->internal->lastActiveVersion;
if ( version_compare( $lastActiveVersion, '202607', '<' ) ) {
// Delete the cache table transient BEFORE migration so that
// isCacheTableAvailable() will re-verify the table structure.
delete_transient( 'aioseo_plugin_cache_table_exists' );
$this->createCacheTable();
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
}
/**
* Creates the cache table.
*
* @since 1.0.0
*
* @return void
*/
public function createCacheTable() {
if ( ! function_exists( 'dbDelta' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
// Use dbDelta to create the cache table based on schema definition
$schema = aioseoTableOfContents()->dbSchema->getCacheTableSchema();
dbDelta( $schema );
// Clear any existing cache rows now that the table is guaranteed to exist.
// (Running this before dbDelta errors on a fresh install where the table doesn't exist yet.)
aioseoTableOfContents()->core->db->execute(
"DELETE FROM {$tableName}"
);
// Clear the transient so isCacheTableAvailable() re-checks on the next call.
delete_transient( 'aioseo_plugin_cache_table_exists' );
}
}
@@ -0,0 +1,149 @@
<?php
namespace AIOSEO\TableOfContents\Main;
use AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles update migrations.
*
* @since 1.0.0
*/
class Updates {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
if ( wp_doing_ajax() || wp_doing_cron() ) {
return;
}
add_action( 'init', [ $this, 'runUpdates' ], 1002 );
add_action( 'init', [ $this, 'updateLatestVersion' ], 3000 );
}
/**
* Runs our migrations.
*
* @since 1.0.0
*
* @return void
*/
public function runUpdates() {
$lastActiveVersion = aioseoTableOfContents()->internalOptions->internal->lastActiveVersion;
// Don't run updates if the last active version is the same as the current version.
if ( aioseoTableOfContents()->version === $lastActiveVersion ) {
return;
}
if ( version_compare( $lastActiveVersion, '1.0.0', '<' ) ) {
}
$this->migrateAppearanceDefaults();
// Sync database schema with dbDelta - this will create tables and add missing columns automatically
$this->updateDbSchema();
// Re-sync role capabilities so plugin caps are only granted to administrators,
// stripping them from any other role they were previously added to.
aioseoTableOfContents()->access->removeCapabilities();
}
/**
* Updates the latest version after all migrations and updates have run.
*
* @since 1.0.0
*
* @return void
*/
public function updateLatestVersion() {
if ( aioseoTableOfContents()->internalOptions->internal->lastActiveVersion === aioseoTableOfContents()->version ) {
return;
}
aioseoTableOfContents()->internalOptions->internal->lastActiveVersion = aioseoTableOfContents()->version;
aioseoTableOfContents()->core->db->bustCache();
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
/**
* Preserves the pre-existing appearance behaviour for sites that already had the plugin.
*
* New installs default to a left-aligned title and a +/- collapse toggle. Existing
* installs are migrated to the previous centered title and bracketed show/hide link
* so the update doesn't visibly change their table of contents. Runs once, and only
* fills in settings the user never had (never overrides an explicit choice).
*
* @since 202607.1
*
* @return void
*/
private function migrateAppearanceDefaults() {
if ( aioseoTableOfContents()->internalOptions->internal->migratedAppearanceDefaults ) {
return;
}
// An install counts as pre-existing if it ran an earlier version (lastActiveVersion
// is set) or already saved settings (the option row exists). A brand-new install has
// neither and keeps the new defaults. lastActiveVersion is read before
// updateLatestVersion() runs later on init, so it still holds the prior version here.
$options = get_option( 'toc-options' );
$isExistingInstall = '0.0' !== aioseoTableOfContents()->internalOptions->internal->lastActiveVersion || false !== $options;
if ( $isExistingInstall ) {
if ( ! is_array( $options ) ) {
$options = [];
}
if ( ! array_key_exists( 'heading_alignment', $options ) ) {
$options['heading_alignment'] = 'center';
}
if ( ! array_key_exists( 'toggle_style', $options ) ) {
$options['toggle_style'] = 'brackets';
}
update_option( 'toc-options', $options );
}
aioseoTableOfContents()->internalOptions->internal->migratedAppearanceDefaults = true;
}
/**
* Synchronizes database schema with defined schema using dbDelta.
*
* This method uses WordPress's dbDelta() function to automatically:
* - Create tables that don't exist
* - Add missing columns to existing tables
* - Modify column definitions that have changed
*
* Note: dbDelta CANNOT drop columns or rename columns. Those operations
* must be handled separately with custom SQL in version-gated migrations.
*
* @since 202607
*
* @return void
*/
private function updateDbSchema() {
if ( ! function_exists( 'dbDelta' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
aioseoTableOfContents()->core->db->execute(
"DELETE FROM {$tableName}"
);
// Get all schema definitions and run dbDelta
$schemas = aioseoTableOfContents()->dbSchema->getSchema();
dbDelta( $schemas );
// Clear schema cache so columnExists/tableExists work correctly
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
}
@@ -0,0 +1,459 @@
<?php
namespace AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The base Model class.
*
* @since 1.0.0
*/
#[\AllowDynamicProperties]
class Model implements \JsonSerializable {
/**
* Fields that should be null when saving to the database.
*
* @since 1.0.0
*
* @var array
*/
protected $nullFields = [];
/**
* Fields that should be encoded/decoded on save/get.
*
* @since 1.0.0
*
* @var array
*/
protected $jsonFields = [];
/**
* Fields that should be boolean values.
*
* @since 1.0.0
*
* @var array
*/
protected $booleanFields = [];
/**
* Fields that should be integer values.
*
* @since 1.0.0
*
* @var array
*/
protected $integerFields = [];
/**
* Fields that should be float values.
*
* @since 1.0.0
*
* @var array
*/
protected $floatValues = [];
/**
* Fields that should be hidden when serialized.
*
* @since 1.0.0
*
* @var array
*/
protected $hidden = [];
/**
* The table used in the SQL query.
*
* @since 1.0.0
*
* @var string
*/
protected $table = '';
/**
* The primary key retrieved from the table.
*
* @since 1.0.0
*
* @var string
*/
protected $pk = 'id';
/**
* An array of columns from the DB that we can use.
*
* @since 1.0.0
*
* @var array
*/
private static $columns;
/**
* Class constructor.
*
* @since 1.0.0
*
* @param mixed $var This can be the primary key of the resource, or it could be an array of data to manufacture a resource without a database query.
*/
public function __construct( $var = null ) {
$fields = [];
$skip = [ 'id', 'created', 'updated' ];
foreach ( $this->getColumns() as $column => $value ) {
if ( ! in_array( $column, $skip, true ) ) {
$fields[ $column ] = $value;
}
}
$this->applyKeys( $fields );
// Process straight through if we were given a valid array.
if ( is_array( $var ) || is_object( $var ) ) {
// Apply keys to object.
$this->applyKeys( $var );
if ( $this->exists() ) {
return true;
}
return false;
}
return $this->loadData( $var );
}
/**
* Load the data from the database!
*
* @since 1.0.0
*
* @param mixed $var The primary key to load up the model from the DB.
* @return Model Returns the current object.
*/
protected function loadData( $var = null ) {
if ( null === $var ) {
return false;
}
$query = aioseoTableOfContents()->core->db
->start( $this->table )
->where( $this->pk, $var )
->limit( 1 )
->output( 'ARRAY_A' );
$result = $query->run();
if ( ! $result || $result->nullSet() ) {
return $this;
}
$this->applyKeys( $result->result()[0] );
return $this;
}
/**
* Take the keys from the result array and add them to the Model.
*
* @since 1.0.0
*
* @param array $array The array of keys and values to add to the Model.
* @return void
*/
protected function applyKeys( $array ) {
if ( ! is_object( $array ) && ! is_array( $array ) ) {
throw new \Exception( '$array must either be an object or an array.' );
}
foreach ( (array) $array as $key => $value ) {
$key = trim( $key );
$this->$key = $value;
if ( null === $value && in_array( $key, $this->nullFields, true ) ) {
continue;
}
if ( in_array( $key, $this->jsonFields, true ) ) {
$this->$key = json_decode( (string) $value );
continue;
}
if ( in_array( $key, $this->booleanFields, true ) ) {
$this->$key = (bool) $value;
continue;
}
if ( in_array( $key, $this->integerFields, true ) ) {
$this->$key = (int) $value;
}
}
}
/**
* Let's filter out any properties we cannot save to the database.
*
* @since 1.0.0
*
* @param string $key The table column.
* @return array The array of valid columns for the database query.
*/
protected function filter( $key ) {
$fields = [];
$skip = [ 'created', 'updated' ];
$table = aioseoTableOfContents()->core->db->prefix . $this->table;
$results = aioseoTableOfContents()->core->db->execute( 'SHOW COLUMNS FROM `' . $table . '`', true );
$columns = $results->result();
foreach ( $columns as $col ) {
if ( ! in_array( $col->Field, $skip, true ) && array_key_exists( $col->Field, $key ) ) {
$fields[ $col->Field ] = $key[ $col->Field ];
}
}
return $fields;
}
/**
* Transforms the data to be null if it exists in the nullFields variables.
*
* @since 1.0.0
*
* @param array $data The data array to transform.
* @return array The transformed data.
*/
protected function transform( $data, $set = false ) {
foreach ( $this->nullFields as $field ) {
if ( isset( $data[ $field ] ) && empty( $data[ $field ] ) ) {
$data[ $field ] = null;
}
}
foreach ( $this->booleanFields as $field ) {
if ( isset( $data[ $field ] ) && '' === $data[ $field ] ) {
unset( $data[ $field ] );
} elseif ( isset( $data[ $field ] ) ) {
$data[ $field ] = (bool) $data[ $field ] ? 1 : 0;
}
}
if ( $set ) {
return $data;
}
foreach ( $this->integerFields as $field ) {
if ( isset( $data[ $field ] ) ) {
$data[ $field ] = (int) $data[ $field ];
}
}
foreach ( $this->jsonFields as $field ) {
if ( isset( $data[ $field ] ) && ! aioseoTableOfContents()->helpers->isJsonString( $data[ $field ] ) ) {
if ( is_array( $data[ $field ] ) && aioseoTableOfContents()->helpers->isArrayNumeric( $data[ $field ] ) ) {
$data[ $field ] = array_values( $data[ $field ] );
}
$data[ $field ] = wp_json_encode( $data[ $field ] );
}
}
return $data;
}
/**
* Sets a piece of data to the requested resource.
*
* @since 1.0.0
*
* @return void
*/
public function set() {
$args = func_get_args();
$count = func_num_args();
if ( ! is_array( $args[0] ) && $count < 2 ) {
throw new \Exception( 'The set method must contain at least 2 arguments: key and value. Or an array of data. Only one argument was passed and it was not an array.' );
}
$key = $args[0];
$value = ! empty( $args[1] ) ? $args[1] : null;
if ( false === $key ) {
return false;
}
if ( ! is_array( $key ) ) {
$key = [ $key => $value ];
}
$key = $this->transform( $key, true );
foreach ( $key as $k => $v ) {
if ( ! empty( $k ) ) {
$this->$k = $v;
}
}
}
/**
* Delete the row in the DB.
*
* @since 1.0.0
*
* @return null
*/
public function delete() {
aioseoTableOfContents()->core->db
->delete( $this->table )
->where( $this->pk, $this->id )
->run();
return null;
}
/**
* Saves data to the requested resource.
*
* @since 1.0.0
*
* @return void
*/
public function save() {
$fields = $this->transform( $this->filter( (array) get_object_vars( $this ) ) );
$id = null;
$date = gmdate( 'Y-m-d H:i:s' );
if ( ! empty( $fields ) ) {
$pk = $this->pk;
if ( isset( $this->$pk ) && '' !== $this->$pk ) {
// PK specified.
$pkv = $this->$pk;
$query = aioseoTableOfContents()->core->db
->start( $this->table )
->where( [ $pk => $pkv ] )
->run();
if ( ! $query->nullSet() ) {
// Row exists in database.
$fields['updated'] = $date;
aioseoTableOfContents()->core->db
->update( $this->table )
->set( $fields )
->where( [ $pk => $pkv ] )
->run();
$id = $this->$pk;
} else {
// Row does not exist.
$fields[ $pk ] = $pkv;
$fields['created'] = $date;
$fields['updated'] = $date;
$id = aioseoTableOfContents()->core->db
->insert( $this->table )
->set( $fields )
->run()
->insertId();
if ( $id ) {
$this->$pk = $id;
}
}
} else {
$fields['created'] = $date;
$fields['updated'] = $date;
$id = aioseoTableOfContents()->core->db
->insert( $this->table )
->set( $fields )
->run()
->insertId();
if ( $id ) {
$this->$pk = $id;
}
}
}
$this->reset( $id );
}
/**
* Check if the model exists in the database.
*
* @since 1.0.0
*
* @return bool Whether the model exists.
*/
public function exists() {
return ( ! empty( $this->{$this->pk} ) ) ? true : false;
}
/**
* Resets a resource by forcing internal updates to be applied.
*
* @since 1.0.0
*
* @param string $id The resource ID.
* @return void
*/
public function reset( $id = null ) {
$id = ! empty( $id ) ? $id : $this->{$this->pk};
$this->__construct( $id );
}
/**
* Helper function to remove data we don't want serialized.
*
* @since 1.0.0
*
* @return array An array of data that we are OK with serializing.
*/
#[\ReturnTypeWillChange]
// The attribute above omits a deprecation notice from PHP 8.1 that is thrown because the return type of jsonSerialize() isn't "mixed".
// Once PHP 7.x is our minimum supported version, this can be removed in favour of overriding the return type in the method signature like this -
// public function jsonSerialize() : array
public function jsonSerialize() {
$array = [];
foreach ( $this->getColumns() as $column => $value ) {
if ( in_array( $column, $this->hidden, true ) ) {
continue;
}
$array[ $column ] = isset( $this->$column ) ? $this->$column : null;
}
return $array;
}
/**
* Retrieves the columns for the model.
*
* @since 1.0.0
*
* @return array An array of columns.
*/
public function getColumns() {
if ( empty( self::$columns[ get_called_class() ] ) ) {
self::$columns[ get_called_class() ] = [];
// Let's set the columns that are available by default.
$table = aioseoTableOfContents()->core->db->prefix . $this->table;
$results = aioseoTableOfContents()->core->db->execute( 'SHOW COLUMNS FROM `' . $table . '`', true );
foreach ( $results->result() as $col ) {
self::$columns[ get_called_class() ][ $col->Field ] = $col->Default;
}
if ( ! empty( $this->appends ) ) {
foreach ( $this->appends as $append ) {
self::$columns[ get_called_class() ][ $append ] = null;
}
}
}
return self::$columns[ get_called_class() ];
}
}
@@ -0,0 +1,344 @@
<?php
namespace AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The Notification DB model class.
*
* @since 1.0.0
*/
class Notification extends Model {
/**
* The name of the table in the database, without the prefix.
*
* @since 1.0.0
*
* @var string
*/
protected $table = 'aioseo_table_of_contents_notifications';
/**
* An array of fields to set to null if already empty when saving to the database.
*
* @since 1.0.0
*
* @var array
*/
protected $nullFields = [
'start',
'end',
'notification_id',
'notification_name',
'button1_label',
'button1_action',
'button2_label',
'button2_action'
];
/**
* Fields that should be json encoded on save and decoded on get.
*
* @since 1.0.0
*
* @var array
*/
protected $jsonFields = [ 'level' ];
/**
* Fields that should be boolean values.
*
* @since 1.0.0
*
* @var array
*/
protected $booleanFields = [ 'dismissed' ];
/**
* Fields that should be hidden when serialized.
*
* @var array
*/
protected $hidden = [ 'id' ];
/**
* An array of fields attached to this resource.
*
* @since 1.0.0
*
* @var array
*/
protected $columns = [
'id',
'slug',
'notification_id',
'notification_name',
'title',
'content',
'type',
'level',
'start',
'end',
'button1_label',
'button1_action',
'button2_label',
'button2_action',
'dismissed',
'new',
'created',
'updated'
];
/**
* Returns all notifications.
*
* @since 1.0.0
*
* @param bool $reset Whether or not to reset the new notifications.
* @return array List of notifications.
*/
public static function getNotifications( $reset = true ) {
return [
'active' => self::getAllActiveNotifications(),
'new' => self::getNewNotifications( $reset ),
'dismissed' => self::getAllDismissedNotifications()
];
}
/**
* Returns the active notifications.
*
* @since 1.0.0
*
* @return array List of active notifications.
*/
public static function getAllActiveNotifications() {
$staticNotifications = self::getStaticNotifications();
$notifications = array_values( json_decode( wp_json_encode( self::getActiveNotifications() ), true ) );
return ! empty( $staticNotifications ) ? array_merge( $staticNotifications, $notifications ) : $notifications;
}
/**
* Returns all static notifications.
*
* @since 1.2.0
*
* @return array List of static notifications.
*/
public static function getStaticNotifications() {
$notifications = [ 'review' ];
$staticNotifications = [];
foreach ( $notifications as $notification ) {
switch ( $notification ) {
case 'review':
// If dismissed, don't show again.
$originalDismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', true );
if ( '4' !== $originalDismissed ) {
break;
}
$dismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', true );
if ( '3' === $dismissed ) {
break;
}
if ( ! empty( $dismissed ) && $dismissed > time() ) {
break;
}
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( $activated > strtotime( '-20 days' ) ) {
break;
}
$staticNotifications[] = [
'slug' => 'notification-' . $notification,
'component' => 'notifications-' . $notification . '2',
];
break;
default:
break;
}
}
return $staticNotifications;
}
/**
* Retrieve active notifications.
*
* @since 1.0.0
*
* @return array List of active notifications or empty.
*/
public static function getActiveNotifications() {
return self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 0 )
->whereRaw( "(start <= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR start IS NULL)" )
->whereRaw( "(end >= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR end IS NULL)" )
->orderBy( 'start DESC' )
->orderBy( 'created DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
}
/**
* Returns all new notifications. After retrieving them, this will reset them.
* This means that calling this method twice will result in no results
* the second time. The only exception is to pass false as a reset variable to prevent it.
*
* @since 1.0.0
*
* @param boolean $reset Whether or not to reset the new notifications.
* @return array List of new notifications if any exist.
*/
public static function getNewNotifications( $reset = true ) {
$notifications = self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 0 )
->where( 'new', 1 )
->whereRaw( "(start <= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR start IS NULL)" )
->whereRaw( "(end >= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR end IS NULL)" )
->orderBy( 'start DESC' )
->orderBy( 'created DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
if ( $reset ) {
self::resetNewNotifications();
}
return $notifications;
}
/**
* Resets all new notifications.
*
* @since 1.0.0
*
* @return void
*/
public static function resetNewNotifications() {
aioseoTableOfContents()->core->db
->update( 'aioseo_table_of_contents_notifications' )
->where( 'new', 1 )
->set( 'new', 0 )
->run();
}
/**
* Returns a list of dismissed notifications.
*
* @since 1.0.0
*
* @return array List of dismissed notifications.
*/
public static function getAllDismissedNotifications() {
return array_values( json_decode( wp_json_encode( self::getDismissedNotifications() ), true ) );
}
/**
* Retrieve dismissed notifications.
*
* @since 1.0.0
*
* @return array List of dismissed notifications or empty.
*/
public static function getDismissedNotifications() {
return self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 1 )
->orderBy( 'updated DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
}
/**
* Returns a notification by its name.
*
* @since 1.0.0
*
* @param string $name The notification name.
* @return Notification The notification.
*/
public static function getNotificationByName( $name ) {
return aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'notification_name', $name )
->run()
->model( 'AIOSEO\\TableOfContents\\Models\\Notification' );
}
/**
* Stores a new notification in the DB.
*
* @since 1.0.0
*
* @param array $fields The fields.
* @return Notification $notification The notification.
*/
public static function addNotification( $fields ) {
// Set the dismissed status to false.
$fields['dismissed'] = 0;
$notification = new self();
$notification->set( $fields );
$notification->save();
return $notification;
}
/**
* Deletes a notification by its name.
*
* @since 1.0.0
*
* @param string $name The notification name.
* @return void
*/
public static function deleteNotificationByName( $name ) {
aioseoTableOfContents()->core->db
->delete( 'aioseo_table_of_contents_notifications' )
->where( 'notification_name', $name )
->run();
}
/**
* Filters the notifications based on the targeted plan levels.
*
* @since 1.0.0
*
* @param array $notifications The notifications
* @return array $remainingNotifications The remaining notifications.
*/
public static function filterNotifications( $notifications ) {
$remainingNotifications = [];
foreach ( $notifications as $notification ) {
$levels = $notification->level;
if ( ! is_array( $levels ) ) {
$levels = empty( $notification->level ) ? [ 'all' ] : [ $notification->level ];
}
foreach ( $levels as $level ) {
if ( ! aioseoTableOfContents()->notifications->validateType( $level ) ) {
continue 2;
}
}
$remainingNotifications[] = $notification;
}
return $remainingNotifications;
}
}
@@ -0,0 +1,93 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class that holds all the cache for the options.
*
* @since 1.0.0
*/
class Cache {
/**
* The DB options cache.
*
* @since 1.0.0
*
* @var array
*/
private static $db = [];
/**
* The options cache.
*
* @since 1.0.0
*
* @var array
*/
private static $options = [];
/**
* Sets the cache for the DB option.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @param array $value The value.
* @return void
*/
public function setDb( $name, $value ) {
self::$db[ $name ] = $value;
}
/**
* Gets the cache for the DB option.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @return array The data from the cache.
*/
public function getDb( $name ) {
return ! empty( self::$db[ $name ] ) ? self::$db[ $name ] : [];
}
/**
* Sets the cache for the options.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @param array $value The value.
* @return void
*/
public function setOptions( $name, $value ) {
self::$options[ $name ] = $value;
}
/**
* Gets the cache for the options.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @return array The data from the cache.
*/
public function getOptions( $name ) {
return ! empty( self::$options[ $name ] ) ? self::$options[ $name ] : [];
}
/**
* Resets the DB cache.
*
* @since 1.0.0
*
* @return void
*/
public function resetDb() {
self::$db = [];
}
}
@@ -0,0 +1,119 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits;
/**
* Class that holds all internal options for Table of Contents Plus.
*
* @since 1.0.0
*/
class InternalOptions {
use Traits\Options;
/**
* Holds a list of all the possible deprecated options.
*
* @since 1.0.0
*
* @var array
*/
protected $allDeprecatedOptions = [];
/**
* All the default options.
*
* @since 1.0.0
*
* @var array
*/
protected $defaults = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'internal' => [
'firstActivated' => [ 'type' => 'number', 'default' => 0 ],
'lastActiveVersion' => [ 'type' => 'string', 'default' => '0.0' ],
'lastSchemaVersion' => [ 'type' => 'string', 'default' => '0.0' ],
'migratedAppearanceDefaults' => [ 'type' => 'boolean', 'default' => false ],
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* Class constructor.
*
* @since 1.0.0
*
* @param string $optionsName The options name.
*/
public function __construct( $optionsName = 'aioseo_table_of_contents_options_internal' ) {
$this->optionsName = is_network_admin() ? $optionsName . '_network' : $optionsName;
$this->init();
add_action( 'shutdown', [ $this, 'save' ] );
}
/**
* Initializes the options.
*
* @since 1.0.0
*
* @return void
*/
protected function init() {
// Options from the DB.
$dbOptions = $this->getDbOptions( $this->optionsName );
// Refactor options.
$this->defaultsMerged = array_replace_recursive( $this->defaults, $this->defaultsMerged );
$options = array_replace_recursive(
$this->defaultsMerged,
$this->addValueToValuesArray( $this->defaultsMerged, $dbOptions )
);
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, apply_filters( 'aioseo_table_of_contents_get_options_internal', $options ) );
}
/**
* Get all the deprecated options.
*
* @since 1.0.0
*
* @return void
*/
public function getAllDeprecatedOptions() {
return $this->allDeprecatedOptions;
}
/**
* Sanitizes, then saves the options to the database.
*
* @since 1.0.0
*
* @param array $options An array of options to sanitize, then save.
* @return void
*/
public function sanitizeAndSave( $options ) {
if ( ! is_array( $options ) ) {
return;
}
// Refactor options.
$cachedOptions = aioseoTableOfContents()->core->optionsCache->getOptions( $this->optionsName );
$dbOptions = array_replace_recursive(
$cachedOptions,
$this->addValueToValuesArray( $cachedOptions, $options, [], true )
);
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, $dbOptions );
// Update values.
$this->save( true );
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits;
/**
* Handles the main options.
*
* @since 1.0.0
*/
class Options {
use Traits\Options;
/**
* All the default options.
*
* @since 1.0.0
*
* @var array
*/
protected $defaults = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'general' => [
// Define options here.
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* The Construct method.
*
* @since 1.0.0
*
* @param string $optionsName An array of options.
*/
public function __construct( $optionsName = 'aioseo_table_of_contents_options' ) {
$this->optionsName = $optionsName;
$this->init();
add_action( 'shutdown', [ $this, 'save' ] );
}
/**
* Initializes the options.
*
* @since 1.0.0
*
* @return void
*/
protected function init() {
$options = $this->getTableOfContentsDbOptions();
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, apply_filters( 'aioseo_table_of_contents_get_options', $options ) );
}
/**
* Get the DB options.
*
* @since 1.0.0
*
* @return array An array of options.
*/
public function getTableOfContentsDbOptions() {
// Options from the DB.
$dbOptions = $this->getDbOptions( $this->optionsName );
// Refactor options.
$this->defaultsMerged = array_replace_recursive( $this->defaults, $this->defaultsMerged );
return array_replace_recursive(
$this->defaultsMerged,
$this->addValueToValuesArray( $this->defaultsMerged, $dbOptions )
);
}
/**
* Sanitizes, then saves the options to the database.
*
* @since 1.0.0
*
* @param array $newOptions An array of options to sanitize, then save.
* @return void
*/
public function sanitizeAndSave( $newOptions ) {
$this->init();
if ( ! is_array( $newOptions ) ) {
return;
}
// First, recursively replace the new options into the cached state.
// It's important we use the helper method since we want to replace populated arrays with empty ones if needed (when a setting was cleared out).
$cachedOptions = aioseoTableOfContents()->core->optionsCache->getOptions( $this->optionsName );
$dbOptions = aioseoTableOfContents()->helpers->arrayReplaceRecursive(
$cachedOptions,
$this->addValueToValuesArray( $cachedOptions, $newOptions, [], true )
);
// Now, we must also intersect both arrays to delete any individual keys that were unset.
// We must do this because, while arrayReplaceRecursive will update the values for keys or empty them out,
// it will keys that aren't present in the replacement array unaffected in the target array.
$dbOptions = aioseoTableOfContents()->helpers->arrayIntersectRecursive(
$dbOptions,
$this->addValueToValuesArray( $cachedOptions, $newOptions, [], true ),
'value'
);
if ( isset( $newOptions['advanced']['excludeDomains'] ) ) {
$dbOptions['advanced']['excludeDomains'] = preg_replace( '/\h/', "\n", (string) $newOptions['advanced']['excludeDomains'] );
}
// Update the cache state.
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, $dbOptions );
// Finally, save the new values to the DB.
$this->save( true );
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
<?php
namespace AIOSEO\TableOfContents\Standalone;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Registers the standalone components.
*
* @since 1.0.0
*/
class Standalone {
/**
* The frontend engine instance.
*
* @since 1.0.0
*
* @var Frontend
*/
public $frontend = null;
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
// The global constants (TOC_VERSION, TOC_POSITION_*, etc.) and the toc_get_index() API
// function are part of the plugin's public surface, so they stay global and are loaded
// explicitly (they are not PSR-4 autoloaded like the classes).
require_once __DIR__ . '/globals.php';
require_once __DIR__ . '/functions.php';
$this->frontend = new Frontend();
// Preserve the historical global and class name so themes and snippets that reference
// $toc_plus or the TOC_Plus class keep working.
$GLOBALS['toc_plus'] = $this->frontend; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! class_exists( 'TOC_Plus' ) ) {
class_alias( Frontend::class, 'TOC_Plus' );
}
}
}
@@ -0,0 +1,149 @@
<?php
namespace AIOSEO\TableOfContents\Standalone;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Widget extends \WP_Widget {
public function __construct() {
$widget_options = [
'classname' => 'toc_widget',
'description' => __( 'Display the table of contents in the sidebar with this widget', 'table-of-contents-plus' ),
];
$control_options = [
'width' => 250,
'height' => 350,
'id_base' => 'toc-widget',
];
parent::__construct( 'toc-widget', 'TOC+', $widget_options, $control_options );
}
/**
* Widget output to the public
*/
public function widget( $args, $instance ) {
global $toc_plus, $wp_query;
if ( is_null( $wp_query->post ) ) {
return;
}
$html = '';
$items = '';
$find = [];
$replace = [];
$toc_options = $toc_plus->get_options();
$post = get_post( $wp_query->post->ID );
if ( $toc_plus->is_eligible() ) {
$items = $toc_plus->extract_headings( $find, $replace, wptexturize( do_shortcode( $post->post_content ) ) );
$title = ( array_key_exists( 'title', $instance ) ) ? apply_filters( 'widget_title', $instance['title'] ) : '';
if ( false !== strpos( $title, '%PAGE_TITLE%' ) ) {
$title = str_replace( '%PAGE_TITLE%', get_the_title(), $title );
}
if ( false !== strpos( $title, '%PAGE_NAME%' ) ) {
$title = str_replace( '%PAGE_NAME%', get_the_title(), $title );
}
$hide_inline = $toc_options['show_toc_in_widget_only'];
$css_classes = '';
// bullets?
if ( $toc_options['bullet_spacing'] ) {
$css_classes .= ' have_bullets';
} else {
$css_classes .= ' no_bullets';
}
if ( $items ) {
// before widget (defined by themes)
$html .= $args['before_widget'];
// display the widget title if one was input (before and after titles defined by themes)
if ( $title ) {
$html .= $args['before_title'] . $title . $args['after_title'];
}
// display the list
$html .= '<ul class="toc_widget_list' . $css_classes . '">' . $items . '</ul>';
// after widget (defined by themes)
$html .= $args['after_widget'];
echo wp_kses_post( $html );
}
}
}
/**
* Update the widget settings
*/
public function update( $new_instance, $old_instance ) {
global $toc_plus;
$instance = $old_instance;
// strip tags for title to remove HTML (important for text inputs)
$instance['title'] = wp_strip_all_tags( trim( $new_instance['title'] ) );
// no need to strip tags for the following
//$instance['hide_inline'] = $new_instance['hide_inline'];
$toc_plus->set_show_toc_in_widget_only( $new_instance['hide_inline'] );
$toc_plus->set_show_toc_in_widget_only_post_types( (array) $new_instance['show_toc_in_widget_only_post_types'] );
return $instance;
}
/**
* Displays the widget settings on the widget panel.
*/
public function form( $instance ) {
global $toc_plus;
$toc_options = $toc_plus->get_options();
$defaults = [ 'title' => $toc_options['heading_text'] ];
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title', 'table-of-contents-plus' ); ?>:</label>
<input type="text" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>" style="width: 100%;">
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked( $toc_options['show_toc_in_widget_only'], 1 ); ?> id="<?php echo esc_attr( $this->get_field_id( 'hide_inline' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'hide_inline' ) ); ?>" value="1">
<label for="<?php echo esc_attr( $this->get_field_id( 'hide_inline' ) ); ?>"> <?php esc_html_e( 'Show the table of contents only in the sidebar', 'table-of-contents-plus' ); ?></label>
</p>
<div class="show_toc_in_widget_only_post_types" style="margin: 0 0 25px 25px; display: <?php echo ( 1 === $toc_options['show_toc_in_widget_only'] ) ? 'block' : 'none'; ?>;">
<p><?php esc_html_e( 'For the following content types:', 'table-of-contents-plus' ); ?></p>
<?php
foreach ( get_post_types() as $post_type ) {
// make sure the post type isn't on the exclusion list
if ( ! in_array( $post_type, $toc_plus->get_exclude_post_types(), true ) ) {
echo '<input type="checkbox" value="' . esc_attr( $post_type ) . '" id="' . esc_attr( $this->get_field_id( 'show_toc_in_widget_only_post_types_' . $post_type ) ) . '" name="' . esc_attr( $this->get_field_name( 'show_toc_in_widget_only_post_types' ) ) . '[]"';
if ( in_array( $post_type, $toc_options['show_toc_in_widget_only_post_types'], true ) ) {
echo ' checked="checked"';
}
echo ' /><label for="' . esc_attr( $this->get_field_id( 'show_toc_in_widget_only_post_types_' . $post_type ) ) . '"> ' . esc_html( $post_type ) . '</label><br />';
}
}
?>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#<?php echo esc_js( $this->get_field_id( 'hide_inline' ) ); ?>').click(function() {
$(this).parent().siblings('div.show_toc_in_widget_only_post_types').toggle('fast');
});
});
</script>
<?php
}
}
@@ -0,0 +1,51 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Returns a HTML formatted string of the table of contents without the surrounding UL or OL
* tags to enable the theme editor to supply their own ID and/or classes to the outer list.
*
* There are three optional parameters you can feed this function with:
*
* - $content is the entire content with headings. If blank, will default to the current $post
*
* - $link is the URL to prefix the anchor with. If provided a string, will use it as the prefix.
* If set to true then will try to obtain the permalink from the $post object.
*
* - $apply_eligibility bool, defaults to false. When set to true, will apply the check to
* see if bit of content has the prerequisites needed for a TOC, eg minimum number of headings
* enabled post type, etc.
*/
function toc_get_index( $content = '', $prefix_url = '', $apply_eligibility = false ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
global $wp_query, $toc_plus;
$return = '';
$find = [];
$replace = [];
$proceed = true;
if ( ! $content ) {
$post = get_post( $wp_query->post->ID );
$content = wptexturize( $post->post_content );
}
if ( $apply_eligibility ) {
if ( ! $toc_plus->is_eligible() ) {
$proceed = false;
}
} else {
$toc_plus->set_option( [ 'start' => 0 ] );
}
if ( $proceed ) {
$return = $toc_plus->extract_headings( $find, $replace, $content );
if ( $prefix_url ) {
$return = str_replace( 'href="#', 'href="' . $prefix_url . '#', $return );
}
}
return $return;
}
@@ -0,0 +1,32 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'TOC_VERSION', '202609.1' );
define( 'TOC_POSITION_BEFORE_FIRST_HEADING', 1 );
define( 'TOC_POSITION_TOP', 2 );
define( 'TOC_POSITION_BOTTOM', 3 );
define( 'TOC_POSITION_AFTER_FIRST_HEADING', 4 );
define( 'TOC_POSITION_BEFORE_FIRST_PARAGRAPH', 5 );
define( 'TOC_POSITION_AFTER_FIRST_PARAGRAPH', 6 );
define( 'TOC_MIN_START', 2 );
define( 'TOC_MAX_START', 10 );
define( 'TOC_SMOOTH_SCROLL_OFFSET', 30 );
define( 'TOC_WRAPPING_NONE', 0 );
define( 'TOC_WRAPPING_LEFT', 1 );
define( 'TOC_WRAPPING_RIGHT', 2 );
define( 'TOC_THEME_GREY', 1 );
define( 'TOC_THEME_LIGHT_BLUE', 2 );
define( 'TOC_THEME_WHITE', 3 );
define( 'TOC_THEME_BLACK', 4 );
define( 'TOC_THEME_TRANSPARENT', 99 );
define( 'TOC_THEME_CUSTOM', 100 );
define( 'TOC_DEFAULT_BACKGROUND_COLOUR', '#f9f9f9' );
define( 'TOC_DEFAULT_BORDER_COLOUR', '#aaaaaa' );
define( 'TOC_DEFAULT_TITLE_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_HOVER_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_VISITED_COLOUR', '#' );
define( 'TOC_PLUGIN_PATH', plugins_url( '', AIOSEO_TABLE_OF_CONTENTS_FILE ) );
@@ -0,0 +1,363 @@
<?php
namespace AIOSEO\TableOfContents {
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The main TableOfContents class.
*
* @since 1.0.0
*/
final class TableOfContents {
/**
* Holds the instance of the plugin currently in use.
*
* @since 1.0.0
*
* @var TableOfContents
*/
private static $instance;
/**
* Plugin version for enqueueing, etc.
* The value is retrieved from the AIOSEO_TABLE_OF_CONTENTS_VERSION constant.
*
* @since 1.0.0
*
* @var string
*/
public $version = '';
/**
* Whether we're in a dev environment.
*
* @since 1.0.0
*
* @var bool
*/
public $isDev = false;
/**
* Core class instance.
*
* @since 1.0.0
*
* @var Core\Core
*/
public $core;
/**
* Database Schema class instance.
*
* @since 202607
*
* @var Db\Schema
*/
public $dbSchema;
/**
* InternalOptions class instance.
*
* @since 1.0.0
*
* @var Options\InternalOptions
*/
public $internalOptions;
/**
* Pre updates class instance.
*
* @since 1.0.0
*
* @var Main\PreUpdates
*/
public $preUpdates;
/**
* Helpers class instance.
*
* @since 1.0.0
*
* @var Utils\Helpers
*/
public $helpers;
/**
* Options class instance.
*
* @since 1.0.0
*
* @var Options\Options
*/
public $options;
/**
* Updates class instance.
*
* @since 1.0.0
*
* @var Main\Updates
*/
public $updates;
/**
* Action scheduler class.
*
* @since 1.0.0
*
* @var Utils\ActionScheduler
*/
public $actionScheduler;
/**
* Access class.
*
* @since 1.0.0
*
* @var Utils\Access
*/
public $access;
/**
* Main class instance.
*
* @since 1.0.0
*
* @var Main\Main
*/
public $main;
/**
* API class instance.
*
* @since 1.0.0
*
* @var Api\Api
*/
public $api;
/**
* Standalone class instance.
*
* @since 1.0.0
*
* @var Standalone\Standalone
*/
public $standalone;
/**
* Notifications class instance.
*
* @since 1.0.0
*
* @var Admin\Notifications
*/
public $notifications;
/**
* VueSettings class instance.
*
* @since 1.1.0
*
* @var Utils\VueSettings
*/
public $vueSettings;
/**
* Admin class instance.
*
* @since 1.2.0
*
* @var Admin\Admin
*/
public $admin;
/**
* The main TableOfContents Instance.
*
* Insures that only one instance of TableOfContents exists in memory at any one
* time. Also prevents needing to define globals all over the place.
*
* @since 1.0.0
*
* @return TableOfContents The Table of Contents Plus instance.
*/
public static function instance() {
if ( null === self::$instance || ! self::$instance instanceof self ) {
self::$instance = new self();
self::$instance->init();
}
return self::$instance;
}
/**
* Initialize Table of Contents Plus!
*
* @since 1.0.0
*
* @return void
*/
private function init() {
$this->constants();
$this->includes();
$this->preLoad();
$this->load();
}
/**
* Setup plugin constants.
* All the path/URL related constants are defined in main plugin file.
*
* @since 1.0.0
*
* @return void
*/
private function constants() {
$defaultHeaders = [
'name' => 'Table of Contents Plus',
'version' => 'Version',
];
$pluginData = get_file_data( AIOSEO_TABLE_OF_CONTENTS_FILE, $defaultHeaders );
$constants = [
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME' => plugin_basename( AIOSEO_TABLE_OF_CONTENTS_FILE ),
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME' => 'Table of Contents Plus',
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_URL' => plugin_dir_url( AIOSEO_TABLE_OF_CONTENTS_FILE ),
'AIOSEO_TABLE_OF_CONTENTS_VERSION' => $pluginData['version'],
'AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL' => 'https://aioseo.com/',
'AIOSEO_TABLE_OF_CONTENTS_MARKETING_DOMAIN' => 'aioseo.com'
];
foreach ( $constants as $constant => $value ) {
if ( ! defined( $constant ) ) {
define( $constant, $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.VariableConstantNameFound
}
}
$this->version = AIOSEO_TABLE_OF_CONTENTS_VERSION;
}
/**
* Including the new files with PHP 5.3 style.
*
* @since 1.0.0
*
* @return void
*/
private function includes() {
$dependencies = [
'/vendor/autoload.php',
'/vendor/woocommerce/action-scheduler/action-scheduler.php'
];
foreach ( $dependencies as $path ) {
if ( ! file_exists( AIOSEO_TABLE_OF_CONTENTS_DIR . $path ) ) {
// Something is not right.
status_header( 500 );
wp_die( esc_html__( 'Plugin is missing required dependencies. Please contact support for more information.', 'table-of-contents-plus' ) );
}
require_once AIOSEO_TABLE_OF_CONTENTS_DIR . $path;
}
$this->loadVersion();
}
/**
* Load the version of the plugin we are currently using.
*
* @since 1.0.0
*
* @return void
*/
private function loadVersion() {
if (
! class_exists( '\Dotenv\Dotenv' ) ||
! file_exists( AIOSEO_TABLE_OF_CONTENTS_DIR . '/build/.env' )
) {
return;
}
$dotenv = \Dotenv\Dotenv::createUnsafeImmutable( AIOSEO_TABLE_OF_CONTENTS_DIR, '/build/.env' );
$dotenv->load();
$devPort = strtolower( getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DEV_PORT' ) );
if ( ! empty( $devPort ) ) {
$this->isDev = true;
// Fix SSL certificate invalid in our local environments.
add_filter( 'https_ssl_verify', '__return_false' );
}
}
/**
* Runs before we load the plugin.
*
* @since 1.0.0
*
* @return void
*/
private function preLoad() {
$this->core = new Core\Core();
$this->helpers = new Utils\Helpers();
$this->dbSchema = new Db\Schema();
$this->internalOptions = new Options\InternalOptions();
$this->preUpdates = new Main\PreUpdates();
}
/**
* Load our classes.
*
* @since 1.0.0
*
* @return void
*/
public function load() {
$this->options = new Options\Options();
$this->updates = new Main\Updates();
$this->actionScheduler = new Utils\ActionScheduler();
$this->access = new Utils\Access();
$this->main = new Main\Main();
$this->api = new Api\Api();
$this->standalone = new Standalone\Standalone();
$this->notifications = new Admin\Notifications();
$this->admin = new Admin\Admin();
add_action( 'init', [ $this, 'loadInit' ], 999 );
}
/**
* Things that need to load after init.
*
* @since 1.0.0
*
* @return void
*/
public function loadInit() {
$this->vueSettings = new Utils\VueSettings( '_aioseo_table_of_contents_settings' );
}
}
}
namespace {
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The function which returns the one AIOSEO instance.
*
* @since 1.0.0
*
* @return AIOSEO\TableOfContents\TableOfContents The instance.
*/
function aioseoTableOfContents() {
return AIOSEO\TableOfContents\TableOfContents::instance();
}
}
@@ -0,0 +1,117 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains API specific helper methods.
*
* @since 1.0.0
*/
trait Api {
/**
* Request the remote URL via wp_remote_post and return a json decoded response.
*
* @since 1.0.0
*
* @param array $body The content to retrieve from the remote URL.
* @param array $headers The headers to send to the remote URL.
* @return string|null JSON decoded response on success, false on failure.
*/
public function sendRequest( $url, $body = [], $headers = [] ) {
$body = wp_json_encode( $body );
// Build the headers of the request.
$headers = wp_parse_args(
$headers,
[
'Content-Type' => 'application/json'
]
);
// Setup variable for wp_remote_post.
$requestArgs = [
'headers' => $headers,
'body' => $body,
'timeout' => 20
];
// Perform the query and retrieve the response.
$response = $this->wpRemotePost( $url, $requestArgs );
$responseBody = wp_remote_retrieve_body( $response );
// Bail out early if there are any errors.
if ( ! $responseBody ) {
return null;
}
// Return the json decoded content.
return json_decode( $responseBody );
}
/**
* Sends a request using wp_remote_post.
*
* @since 1.0.0
*
* @param string $url The URL to send the request to.
* @param array $args The args to use in the request.
* @return array|\WP_Error The response as an array or WP_Error on failure.
*/
public function wpRemotePost( $url, $args = [] ) {
return wp_remote_post( $url, array_replace_recursive( $this->getWpApiRequestDefaults(), $args ) );
}
/**
* Sends a request using wp_remote_get.
*
* @since 1.0.0
*
* @param string $url The URL to send the request to.
* @param array $args The args to use in the request.
* @return array|\WP_Error The response as an array or WP_Error on failure.
*/
public function wpRemoteGet( $url, $args = [] ) {
return wp_remote_get( $url, array_replace_recursive( $this->getWpApiRequestDefaults(), $args ) );
}
/**
* Default arguments for wp_remote_get and wp_remote_post.
*
* @since 1.0.0
*
* @return array An array of default arguments for the request.
*/
private function getWpApiRequestDefaults() {
return [
'timeout' => 10,
'headers' => aioseoTableOfContents()->helpers->getApiHeaders(),
'user-agent' => aioseoTableOfContents()->helpers->getApiUserAgent()
];
}
/**
* Returns the headers for internal API requests.
*
* @since 1.0.0
*
* @return array An array of headers.
*/
private function getApiHeaders() {
return [];
}
/**
* Returns the User Agent for internal API requests.
*
* @since 1.0.0
*
* @return string The User Agent.
*/
private function getApiUserAgent() {
return 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ) . '; AIOSEO/TableOfContents/' . AIOSEO_TABLE_OF_CONTENTS_VERSION;
}
}
@@ -0,0 +1,112 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains array specific helper methods.
*
* @since 1.0.0
*/
trait Arrays {
/**
* Checks whether the given array is associative.
* Arrays that only have consecutive, sequential numeric keys are numeric.
* Otherwise they are associative.
*
* @since 1.0.0
*
* @param array $array The array.
* @return bool Whether the array is associative.
*/
public function isArrayAssociative( $array ) {
return 0 < count( array_filter( array_keys( $array ), 'is_string' ) );
}
/**
* Checks whether the given array is numeric.
*
* @since 1.0.0
*
* @param array $array The array.
* @return bool Whether the array is numeric.
*/
public function isArrayNumeric( $array ) {
return ! $this->isArrayAssociative( $array );
}
/**
* Recursively replaces the values from one array with the ones from another.
* This function should act identical to the built-in array_replace_recursive(), with the exception that it also replaces array values with empty arrays.
*
* @since 1.0.0
*
* @param array $targetArray The target array
* @param array $replacementArray The array with values to replace in the target array.
* @return array The modified array.
*/
public function arrayReplaceRecursive( $targetArray, $replacementArray ) {
// In some cases the target array isn't an array yet (due to e.g. race conditions in InternalOptions), so in that case we can just return the replacement array.
if ( ! is_array( $targetArray ) ) {
return $replacementArray;
}
foreach ( $replacementArray as $k => $v ) {
// If the key does not exist yet on the target array, add it.
if ( ! isset( $targetArray[ $k ] ) ) {
$targetArray[ $k ] = $replacementArray[ $k ];
continue;
}
// If the value is an array, only try to recursively replace it if the value isn't empty.
// Otherwise empty arrays will be ignored and won't override the existing value of the target array.
if ( is_array( $v ) && ! empty( $v ) ) {
$targetArray[ $k ] = $this->arrayReplaceRecursive( $targetArray[ $k ], $v );
continue;
}
// Replace with non-array value or empty array.
$targetArray[ $k ] = $v;
}
return $targetArray;
}
/**
* Recursively intersects the two given arrays.
* You can pass in an optional argument (allowedKey) to restrict the intersect to arrays with a specific key.
* This is needed when we are e.g. sanitizing array values before setting/saving them to an option.
*
* @since 1.0.0
*
* @param array $array1 The first array.
* @param array $array2 The second array.
* @param string $allowedKey The only key the method should run for (optional).
* @param string $parentKey The parent key.
* @return array The intersected array.
*/
public function arrayIntersectRecursive( $array1, $array2, $allowedKey = '', $parentKey = '' ) {
if ( ! $allowedKey || $allowedKey === $parentKey ) {
$array1 = array_intersect_assoc( $array1, $array2 );
}
if ( empty( $array1 ) ) {
return [];
}
foreach ( $array1 as $k => $v ) {
if ( is_array( $v ) && isset( $array2[ $k ] ) ) {
$array1[ $k ] = $this->arrayIntersectRecursive( $array1[ $k ], $array2[ $k ], $allowedKey, $k );
}
}
if ( $this->isArrayNumeric( $array1 ) ) {
$array1 = array_values( $array1 );
}
return $array1;
}
}
@@ -0,0 +1,25 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains constant specific helper methods.
*
* @since 1.0.0
*/
trait Constants {
/**
* Returns the plugin menu icon.
*
* @since 1.0.0
*
* @return string The icon as a string.
*/
public function icon() {
return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="6" r="2.8" stroke="white" stroke-width="2.4"/><path d="M16 8.8V26.6M10.4 12.2H21.6" stroke="white" stroke-width="2.6" stroke-linecap="round"/><path d="M7 16.4H4.3a11.7 11.7 0 0 0 23.4 0H25" stroke="white" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>'; // phpcs:ignore Generic.Files.LineLength.MaxExceeded
}
}
@@ -0,0 +1,28 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains date/time specific helper methods.
*
* @since 1.0.0
*/
trait DateTime {
/**
* Returns a MySQL formatted date.
*
* @since 1.0.0
*
* @param int|string $time Any format accepted by strtotime.
* @return false|string The MySQL formatted string.
*/
public function timeToMysql( $time ) {
$time = is_string( $time ) ? strtotime( $time ) : $time;
return date( 'Y-m-d H:i:s', $time ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
}
@@ -0,0 +1,284 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains string specific helper methods.
*
* @since 1.0.0
*/
trait Strings {
/**
* Escapes special regex characters.
*
* @since 1.0.0
*
* @param string $string The string.
* @param string $delimiter The delimiter character.
* @return string The escaped string.
*/
public function escapeRegex( $string, $delimiter = '/' ) {
static $escapeRegex = [];
if ( isset( $escapeRegex[ $string ] ) ) {
return $escapeRegex[ $string ];
}
$escapeRegex[ $string ] = preg_quote( (string) $string, $delimiter );
return $escapeRegex[ $string ];
}
/**
* Escapes special regex characters inside the replacement string.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The escaped string.
*/
public function escapeRegexReplacement( $string ) {
static $escapeRegexReplacement = [];
if ( isset( $escapeRegexReplacement[ $string ] ) ) {
return $escapeRegexReplacement[ $string ];
}
$escapeRegexReplacement[ $string ] = str_replace( '$', '\$', $string );
return $escapeRegexReplacement[ $string ];
}
/**
* preg_replace but with the replacement escaped.
*
* @since 1.0.0
*
* @param string $pattern The pattern to search for.
* @param string $replacement The replacement string.
* @param string $subject The subject to search in.
* @return string The subject with matches replaced.
*/
public function pregReplace( $pattern, $replacement, $subject ) {
$key = $pattern . $replacement . $subject;
static $pregReplace = [];
if ( isset( $pregReplace[ $key ] ) ) {
return $pregReplace[ $key ];
}
// We can use the following pattern for this - (?<!\\)([\/.^$*+?|()[{}\]]{1})
// The pattern above will only escape special characters if they're not escaped yet, which makes it compatible with all our patterns that are already escaped.
// The caveat is that we'd need to first trim off slash delimiters and add them back later - otherwise they'd be escaped as well.
$replacement = $this->escapeRegexReplacement( $replacement );
$pregReplace[ $key ] = preg_replace( $pattern, $replacement, (string) $subject );
return $pregReplace[ $key ];
}
/**
* Returns the index of a substring in a string.
*
* @since 1.0.0
*
* @param string $stack The stack.
* @param string $needle The needle.
* @param int $offset The offset.
* @return int|bool The index where the string starts or false if it does not exist.
*/
public function stringIndex( $stack, $needle, $offset = 0 ) {
$key = $stack . $needle . $offset;
static $stringIndex = [];
if ( isset( $stringIndex[ $key ] ) ) {
return $stringIndex[ $key ];
}
$stringIndex[ $key ] = function_exists( 'mb_strpos' ) ? mb_strpos( $stack, $needle, $offset, get_option( 'blog_charset' ) ) : strpos( $stack, $needle, $offset );
return $stringIndex[ $key ];
}
/**
* Checks if the given string contains the given substring.
*
* @since 1.0.0
*
* @param string $stack The stack.
* @param string $needle The needle.
* @param int $offset The offset.
* @return bool Whether the substring occurs in the main string.
*/
public function stringContains( $stack, $needle, $offset = 0 ) {
$key = $stack . $needle . $offset;
static $stringContains = [];
if ( isset( $stringContains[ $key ] ) ) {
return $stringContains[ $key ];
}
$stringContains[ $key ] = false !== $this->stringIndex( $stack, $needle, $offset );
return $stringContains[ $key ];
}
/**
* Check if a string is JSON encoded or not.
*
* @since 1.0.0
*
* @param string $string The string to check.
* @return bool True if it is JSON or false if not.
*/
public function isJsonString( $string ) {
if ( ! is_string( $string ) ) {
return false;
}
json_decode( $string );
// Return a boolean whether or not the last error matches.
return json_last_error() === JSON_ERROR_NONE;
}
/**
* Returns the string after all HTML entities have been decoded.
*
* @since 1.0.0
*
* @param string $string The string to decode.
* @return string The decoded string.
*/
public function decodeHtmlEntities( $string ) {
static $decodeHtmlEntities = [];
if ( isset( $decodeHtmlEntities[ $string ] ) ) {
return $decodeHtmlEntities[ $string ];
}
// We must manually decode non-breaking spaces since html_entity_decode doesn't do this.
$string = $this->pregReplace( '/&nbsp;/', ' ', $string );
$decodeHtmlEntities[ $string ] = html_entity_decode( (string) $string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
return $decodeHtmlEntities[ $string ];
}
/**
* Returns the string with script tags stripped.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function stripScriptTags( $string ) {
static $stripScriptTags = [];
if ( isset( $stripScriptTags[ $string ] ) ) {
return $stripScriptTags[ $string ];
}
$stripScriptTags[ $string ] = $this->pregReplace( '/<script(.*?)>(.*?)<\/script>/is', '', $string );
return $stripScriptTags[ $string ];
}
/**
* Returns the string with incomplete HTML tags stripped.
* Incomplete tags are not unopened/unclosed pairs but rather single tags that aren't properly formed.
* e.g. <a href='something'
* e.g. href='something' >
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function stripIncompleteHtmlTags( $string ) {
static $stripIncompleteHtmlTags = [];
if ( isset( $stripIncompleteHtmlTags[ $string ] ) ) {
return $stripIncompleteHtmlTags[ $string ];
}
$stripIncompleteHtmlTags[ $string ] = $this->pregReplace( '/(^(?!<).*?(\/>)|<[^>]*?(?!\/>)$)/is', '', $string );
return $stripIncompleteHtmlTags[ $string ];
}
/**
* Trims HTML paragraph from the start/end of the given string.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function trimParagraphTags( $string ) {
$string = preg_replace( '/^<p[^>]*>/', '', (string) $string );
$string = preg_replace( '/<\/p>/', '', (string) $string );
return trim( $string );
}
/**
* Implodes an array into a WHEREIN clause useable string.
*
* @since 1.0.0
*
* @param array $array The array.
* @param bool $outerQuotes Whether outer quotes should be added.
* @return string The imploded array.
*/
public function implodeWhereIn( $array, $outerQuotes = false ) {
// Reset the keys first in case there is no 0 index.
$array = array_values( $array );
if ( ! isset( $array[0] ) ) {
return '';
}
if ( is_numeric( $array[0] ) ) {
return implode( ', ', $array );
}
return $outerQuotes ? "'" . implode( "', '", $array ) . "'" : implode( "', '", $array );
}
/**
* Returns string after converting it to lowercase.
*
* @since 1.0.0
*
* @param string $string The original string.
* @return string The string converted to lowercase.
*/
public function toLowerCase( $string ) {
static $lowerCased = [];
if ( isset( $lowerCased[ $string ] ) ) {
return $lowerCased[ $string ];
}
$lowerCased[ $string ] = function_exists( 'mb_strtolower' ) ? mb_strtolower( $string, $this->getCharset() ) : strtolower( $string );
return $lowerCased[ $string ];
}
/**
* Convert to camelCase.
*
* @since 1.1.0
*
* @param string $string The string to convert.
* @param bool $capitalize Whether to capitalize the first letter.
* @return string The converted string.
*/
public function toCamelCase( $string, $capitalize = false ) {
$string[0] = strtolower( $string[0] );
if ( $capitalize ) {
$string[0] = strtoupper( $string[0] );
}
return preg_replace_callback( '/_([a-z0-9])/', function ( $value ) {
return strtoupper( $value[1] );
}, $string );
}
}
@@ -0,0 +1,47 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains helper methods for other plugins/themes.
*
* @since 1.0.0
*/
trait ThirdParty {
/**
* Checks whether WooCommerce is active.
*
* @since 1.0.0
*
* @return boolean Whether WooCommerce is active.
*/
public function isWooCommerceActive() {
return class_exists( 'woocommerce' );
}
/**
* Checks whether the queried object is the WooCommerce shop page.
*
* @since 1.0.0
*
* @param int $id The post ID to check against (optional).
* @return bool Whether the current page is the WooCommerce shop page.
*/
public function isWooCommerceShopPage( $id = 0 ) {
if ( ! $this->isWooCommerceActive() ) {
return false;
}
if ( ! is_admin() && ! aioseoTableOfContents()->helpers->isAjaxCronRestRequest() && function_exists( 'is_shop' ) ) {
return is_shop();
}
$id = ! $id && ! empty( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : (int) $id; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return $id && wc_get_page_id( 'shop' ) === $id;
}
}
@@ -0,0 +1,178 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Api;
use AIOSEO\TableOfContents\Models;
/**
* Generates the data we need for Vue.
*
* @since 1.0.0
*/
trait Vue {
/**
* The data to pass to Vue.
*
* @since 1.0.0
*
* @var array
*/
private $vueData = [];
/**
* Returns the data for Vue.
*
* @since 1.0.0
*
* @param string $currentPage The current page.
* @return array The data.
*/
public function getVueData( $currentPage = null ) {
global $wp_version;
static $showNotificationsDrawer = null;
if ( null === $showNotificationsDrawer ) {
$showNotificationsDrawer = aioseoTableOfContents()->core->cache->get( 'show_notifications_drawer' ) ? true : false;
// IF this is set to true, let's disable it now so it doesn't pop up again.
if ( $showNotificationsDrawer ) {
aioseoTableOfContents()->core->cache->delete( 'show_notifications_drawer' );
}
}
$this->vueData = [
// The following data is needed on all screens.
'wpVersion' => $wp_version,
'page' => $currentPage,
'screen' => aioseoTableOfContents()->helpers->getCurrentScreen(),
'internalOptions' => aioseoTableOfContents()->internalOptions->all(),
'options' => aioseoTableOfContents()->options->all(),
'settings' => aioseoTableOfContents()->vueSettings->all(),
'tocSettings' => aioseoTableOfContents()->standalone->frontend->get_options(),
'tocPostTypes' => Api\TocSettings::getPostTypes(),
'notifications' => array_merge( Models\Notification::getNotifications( false ), [ 'force' => $showNotificationsDrawer ] ),
'helpPanel' => [],
'urls' => [
'domain' => $this->getSiteDomain(),
'mainSiteUrl' => $this->getSiteUrl(),
'home' => home_url(),
'restUrl' => rest_url(),
'editScreen' => admin_url( 'edit.php' ),
'publicPath' => aioseoTableOfContents()->core->assets->normalizeAssetsHost( plugin_dir_url( AIOSEO_TABLE_OF_CONTENTS_FILE ) ),
'assetsPath' => aioseoTableOfContents()->core->assets->getAssetsPath(),
'marketingSite' => $this->getMarketingSiteUrl(),
'connect' => admin_url( 'index.php?page=table-of-contents-connect' )
],
'isDev' => $this->isDev(),
'isAioseoActive' => function_exists( 'aioseo' ),
'isAioseoInstalled' => file_exists( WP_PLUGIN_DIR . '/all-in-one-seo-pack/all_in_one_seo_pack.php' )
|| file_exists( WP_PLUGIN_DIR . '/all-in-one-seo-pack-pro/all_in_one_seo_pack.php' ),
'isBrokenLinkCheckerActive' => function_exists( 'aioseoBrokenLinkChecker' ),
'isBrokenLinkCheckerInstalled' => file_exists( WP_PLUGIN_DIR . '/broken-link-checker-seo/aioseo-broken-link-checker.php' )
|| file_exists( WP_PLUGIN_DIR . '/aioseo-broken-link-checker/aioseo-broken-link-checker.php' ),
'isSsl' => is_ssl(),
'isMultisite' => is_multisite(),
'isNetworkAdmin' => is_network_admin(),
'mainSite' => is_main_site(),
'hasUrlTrailingSlash' => '/' === user_trailingslashit( '' ),
'nonce' => wp_create_nonce( 'wp_rest' ),
'translations' => $this->getJedLocaleData( 'table-of-contents-plus' )
];
// In multisite, super admins may not have explicit roles on subsites.
// Ensure they have administrator role and capabilities for proper access.
$userData = wp_get_current_user();
$roles = $userData->roles;
$capabilities = $userData->allcaps;
// If the user is a network admin, and doesn't have a user on the subsite, give him admin role/caps.
if ( is_multisite() && is_super_admin() && empty( $roles ) ) {
$roles = [ 'administrator' ];
$adminRole = get_role( 'administrator' );
if ( is_a( $adminRole, 'WP_Role' ) ) {
$capabilities = $adminRole->capabilities;
}
}
$this->vueData['user'] = [
'canManage' => aioseoTableOfContents()->access->canManage(),
'roles' => $roles,
'capabilities' => $capabilities,
'locale' => function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale()
];
switch ( $currentPage ) {
case 'about':
$this->addAboutData();
break;
default:
break;
}
return $this->vueData;
}
/**
* Adds the data for the About Us screen.
*
* @since 1.0.0
*
* @return void
*/
private function addAboutData() {
$this->vueData['plugins'] = $this->getPluginData();
}
/**
* Returns Jed-formatted localization data.
*
* @since 1.0.0
*
* @param string $domain The text domain.
* @return array The information of the locale.
*/
private function getJedLocaleData( $domain ) {
$translations = get_translations_for_domain( $domain );
$locale = [
'' => [
'domain' => $domain,
'lang' => is_admin() && function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale(),
],
];
if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
}
foreach ( $translations->entries as $msgid => $entry ) {
if ( empty( $entry->translations ) || ! is_array( $entry->translations ) ) {
continue;
}
$locale[ $msgid ] = $entry->translations;
}
return $locale;
}
/**
* Returns the marketing site URL.
*
* @since 1.0.0
*
* @return string The marketing site URL.
*/
private function getMarketingSiteUrl() {
if ( defined( 'AIOSEO_MARKETING_SITE_URL' ) && AIOSEO_MARKETING_SITE_URL ) {
return AIOSEO_MARKETING_SITE_URL;
}
return 'https://aioseo.com/';
}
}
@@ -0,0 +1,470 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
use AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all WP related helper methods.
*
* @since 1.0.0
*/
trait Wp {
/**
* Returns all registered post statuses.
*
* @since 1.0.0
*
* @param boolean $statusesOnly Whether or not to only return statuses.
* @return array List of post statuses.
*/
public function getPublicPostStatuses( $statusesOnly = false ) {
$allStatuses = get_post_stati( [ 'show_in_admin_all_list' => true ], 'objects' );
$postStatuses = [];
foreach ( $allStatuses as $status => $data ) {
if (
! $data->public &&
! $data->protected &&
! $data->private
) {
continue;
}
if ( $statusesOnly ) {
$postStatuses[] = $status;
continue;
}
$postStatuses[] = [
'label' => $data->label,
'status' => $status
];
}
return $postStatuses;
}
/**
* Returns a list of public post types with slugs/icons.
*
* @since 1.0.0
*
* @param boolean $namesOnly Whether only the names should be returned.
* @param boolean $hasArchivesOnly Whether or not to only include post types which have archives.
* @param boolean $rewriteType Whether or not to rewrite the type slugs.
* @return array List of public post types.
*/
public function getPublicPostTypes( $namesOnly = false, $hasArchivesOnly = false, $rewriteType = false ) {
$postTypes = [];
$postTypeObjects = get_post_types( [ 'public' => true ], 'objects' );
$woocommerce = class_exists( 'woocommerce' );
foreach ( $postTypeObjects as $postTypeObject ) {
if ( empty( $postTypeObject->label ) ) {
continue;
}
// We don't want to include archives for the WooCommerce shop page.
if (
$hasArchivesOnly &&
(
! $postTypeObject->has_archive ||
( 'product' === $postTypeObject->name && $woocommerce )
)
) {
continue;
}
if ( $namesOnly ) {
$postTypes[] = $postTypeObject->name;
continue;
}
if ( 'attachment' === $postTypeObject->name ) {
// We have to check if the 'init' action has been fired to avoid a PHP notice
// in WP 6.7+ due to loading translations too early.
if ( did_action( 'init' ) ) {
$postTypeObject->label = __( 'Attachments', 'table-of-contents-plus' );
}
}
if ( 'product' === $postTypeObject->name && $woocommerce ) {
$postTypeObject->menu_icon = 'dashicons-products';
}
$name = $postTypeObject->name;
if ( 'type' === $postTypeObject->name && $rewriteType ) {
$name = '_aioseo_type';
}
$postTypes[] = [
'name' => $name,
'label' => ucwords( $postTypeObject->label ),
'singular' => ucwords( $postTypeObject->labels->singular_name ),
'icon' => $postTypeObject->menu_icon,
'hasExcerpt' => post_type_supports( $postTypeObject->name, 'excerpt' ),
'hasArchive' => $postTypeObject->has_archive,
'hierarchical' => $postTypeObject->hierarchical,
'taxonomies' => get_object_taxonomies( $name ),
'slug' => isset( $postTypeObject->rewrite['slug'] ) ? $postTypeObject->rewrite['slug'] : $name
];
}
return apply_filters( 'aioseo_table_of_contents_public_post_types', $postTypes, $namesOnly, $hasArchivesOnly );
}
/**
* Checks if the current user can edit posts of the given post type.
*
* @since 1.0.0
*
* @param string $postType The name of the post type.
* @return bool Whether the user can edit posts of the given post type.
*/
public function canEditPostType( $postType ) {
$capabilities = $this->getPostTypeCapabilities( $postType );
return current_user_can( $capabilities['edit_posts'] );
}
/**
* Returns a list of capabilities for the given post type.
*
* @since 1.0.0
*
* @param string $postType The name of the post type.
* @return array The capabilities.
*/
public function getPostTypeCapabilities( $postType ) {
static $capabilities = [];
if ( isset( $capabilities[ $postType ] ) ) {
return $capabilities[ $postType ];
}
$postTypeObject = get_post_type_object( $postType );
if ( ! is_a( $postTypeObject, 'WP_Post_Type' ) ) {
$capabilities[ $postType ] = [];
return $capabilities[ $postType ];
}
$capabilities[ $postType ] = (array) $postTypeObject->cap;
return $capabilities[ $postType ];
}
/**
* Returns the current post object.
*
* @since 1.0.0
*
* @param int|null $postId The post ID.
* @return \WP_Post|null The post object.
*/
public function getPost( $postId = null ) {
$postId = is_a( $postId, 'WP_Post' ) ? $postId->ID : $postId;
if ( $this->isWooCommerceShopPage( $postId ) ) {
return get_post( wc_get_page_id( 'shop' ) );
}
if ( is_front_page() || is_home() ) {
$showOnFront = 'page' === get_option( 'show_on_front' );
if ( $showOnFront ) {
if ( is_front_page() ) {
$pageOnFront = (int) get_option( 'page_on_front' );
return get_post( $pageOnFront );
} elseif ( is_home() ) {
$pageForPosts = (int) get_option( 'page_for_posts' );
return get_post( $pageForPosts );
}
}
}
// We need to check these conditions and cannot always return get_post() because we'll return the first post on archive pages (dynamic homepage, term pages, etc.).
// https://github.com/awesomemotive/aioseo/issues/2419
if (
$this->isScreenBase( 'post' ) ||
$postId ||
is_singular()
) {
return get_post( $postId );
}
return null;
}
/**
* Returns true if the request is a non-legacy REST API request.
* This function was copied from WooCommerce and improved.
*
* @since 1.0.0
*
* @return bool True if this is a REST API request.
*/
public function isRestApiRequest() {
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return true;
}
global $wp_rewrite;
if ( empty( $wp_rewrite ) ) {
return false;
}
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
return false;
}
$restUrl = wp_parse_url( get_rest_url() );
$restUrl = $restUrl['path'] . ( ! empty( $restUrl['query'] ) ? '?' . $restUrl['query'] : '' );
$isRestApiRequest = ( 0 === strpos( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), $restUrl ) );
return apply_filters( 'aioseo_is_rest_api_request', $isRestApiRequest );
}
/**
* Checks whether the current request is an AJAX, CRON or REST request.
*
* @since 1.0.0
*
* @return bool Wether the request is an AJAX, CRON or REST request.
*/
public function isAjaxCronRestRequest() {
return wp_doing_ajax() || wp_doing_cron() || $this->isRestApiRequest();
}
/**
* Check if the post passed in is a valid post, not a revision or autosave.
*
* @since 1.0.0
*
* @param \WP_Post $post The Post object to check.
* @param array $allowedPostStatuses Allowed post statuses.
* @return bool True if valid, false if not.
*/
public function isValidPost( $post, $allowedPostStatuses = [ 'publish' ] ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return false;
}
if ( ! is_object( $post ) ) {
$post = get_post( $post );
}
// In order to prevent recursion, we are skipping scheduled-action posts.
if (
! is_object( $post ) ||
'scheduled-action' === $post->post_type ||
'revision' === $post->post_type ||
! in_array( $post->post_status, $allowedPostStatuses, true )
) {
return false;
}
return true;
}
/**
* Returns a list of plugins with the active status.
*
* @since 1.0.0
*
* @return array List of plugins with active status.
*/
public function getPluginData() {
static $pluginData = [];
if ( ! empty( $pluginData ) ) {
return $pluginData;
}
$pluginUpgrader = new Utils\PluginUpgraderSilentAjax();
$installedPlugins = array_keys( get_plugins() );
foreach ( $pluginUpgrader->pluginSlugs as $key => $slug ) {
$pluginData[ $key ] = [
'basename' => $slug,
'installed' => in_array( $slug, $installedPlugins, true ),
'activated' => is_plugin_active( $slug ),
'adminUrl' => admin_url( $pluginUpgrader->pluginAdminUrls[ $key ] ),
'canInstall' => $this->canInstall(),
'canActivate' => $this->canActivate(),
'canUpdate' => $this->canUpdate(),
'wpLink' => ! empty( $pluginUpgrader->wpPluginLinks[ $key ] ) ? $pluginUpgrader->wpPluginLinks[ $key ] : null
];
}
return $pluginData;
}
/**
* Installs and activates a given addon or plugin.
*
* @since 1.0.0
*
* @param string $name The addon name/SKU.
* @param bool $network Whether or not we are in a network environment.
* @return bool Whether or not the installation was succesful.
*/
public function installAddon( $name, $network = false ) {
if ( ! $this->canInstall() ) {
return false;
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/template.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
require_once ABSPATH . 'wp-admin/includes/screen.php';
// Set the current screen to avoid undefined notices.
set_current_screen( 'toplevel_page_table-of-contents' );
// Prepare variables.
$url = esc_url_raw(
add_query_arg(
[
'page' => 'table-of-contents-links'
],
admin_url( 'admin.php' )
)
);
// Do not allow WordPress to search/download translations, as this will break JS output.
remove_action( 'upgrader_process_complete', [ 'Language_Pack_Upgrader', 'async_upgrade' ], 20 );
// Create the plugin upgrader with our custom skin.
$installer = new Utils\PluginUpgraderSilentAjax( new Utils\PluginUpgraderSkin() );
// Activate the plugin silently.
$pluginUrl = ! empty( $installer->pluginSlugs[ $name ] ) ? $installer->pluginSlugs[ $name ] : $name;
$activated = activate_plugin( $pluginUrl, '', $network );
if ( ! is_wp_error( $activated ) ) {
return $name;
}
// Using output buffering to prevent the FTP form from being displayed in the screen.
ob_start();
$creds = request_filesystem_credentials( $url, '', false, false, null );
ob_end_clean();
// Check for file system permissions.
$fs = aioseoTableOfContents()->core->fs->noConflict();
$fs->init( $creds );
if ( false === $creds || ! $fs->isWpfsValid() ) {
return false;
}
// Error check.
if ( ! method_exists( $installer, 'install' ) ) {
return false;
}
$installLink = ! empty( $installer->pluginLinks[ $name ] ) ? $installer->pluginLinks[ $name ] : null;
// Check if this is an addon and if we have a download link.
if ( empty( $installLink ) ) {
return false;
}
$installer->install( $installLink );
// Flush the cache and return the newly installed plugin basename.
wp_cache_flush();
$pluginBasename = $installer->plugin_info();
if ( ! $pluginBasename ) {
return false;
}
// Activate the plugin silently.
$activated = activate_plugin( $pluginBasename, '', $network );
if ( is_wp_error( $activated ) ) {
return false;
}
return $pluginBasename;
}
/**
* Determine if plugins can be installed.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be installed.
*/
public function canInstall() {
if ( ! current_user_can( 'install_plugins' ) ) {
return false;
}
// Determine whether file modifications are allowed.
if ( ! wp_is_file_mod_allowed( 'aioseo_table_of_contents_can_install' ) ) {
return false;
}
return true;
}
/**
* Determine if plugins can be updated.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be updated.
*/
public function canUpdate() {
if ( ! current_user_can( 'update_plugins' ) ) {
return false;
}
// Determine whether file modifications are allowed.
if ( ! wp_is_file_mod_allowed( 'aioseo_table_of_contents_can_update' ) ) {
return false;
}
return true;
}
/**
* Determine if plugins can be activated.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be activated.
*/
public function canActivate() {
if ( ! current_user_can( 'activate_plugins' ) ) {
return false;
}
return true;
}
/**
* Returns the charset for the site.
*
* @since 1.0.0
*
* @return string The name of the charset.
*/
public function getCharset() {
static $charset = null;
if ( null !== $charset ) {
return $charset;
}
$charset = get_option( 'blog_charset' );
$charset = $charset ? $charset : 'UTF-8';
return $charset;
}
}
@@ -0,0 +1,47 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all context related helper methods.
* This includes methods to check the context of the current request, but also get WP objects.
*
* @since 1.0.0
*/
trait WpContext {
/**
* Checks whether we're on the given screen.
*
* @since 1.0.0
*
* @param string $screenName The screen name.
* @return boolean Whether we're on the given screen.
*/
public function isScreenBase( $screenName ) {
$screen = $this->getCurrentScreen();
if ( ! $screen || ! isset( $screen->base ) ) {
return false;
}
return $screen->base === $screenName;
}
/**
* Gets current admin screen
*
* @since 1.0.0
*
* @return false|\WP_Screen|null
*/
public function getCurrentScreen() {
if ( ! is_admin() || ! function_exists( 'get_current_screen' ) ) {
return false;
}
return get_current_screen();
}
}
@@ -0,0 +1,78 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains methods related to multisites.
*
* @since 1.0.0
*/
trait WpMultisite {
/**
* Returns the current site.
*
* @since 1.0.0
*
* @return \WP_Site|Object A WP_Site instance of the current site or an object representing the same.
*/
public function getSite() {
if ( is_multisite() ) {
return get_site();
}
return (object) [
'domain' => $this->getSiteDomain(),
'path' => $this->getHomePath()
];
}
/**
* Returns the network ID.
*
* @since 1.0.0
*
* @return int The integer of the blog/site id.
*/
public function getNetworkId() {
if ( is_multisite() ) {
return get_network()->site_id;
}
return get_current_blog_id();
}
/**
* Wrapper for switch_to_blog especially for non-multisite setups.
*
* @since 1.0.0
*
* @param int $blogId The blog ID to switch to.
* @return bool True in all cases.
*/
public function switchToBlog( $blogId ) {
if ( ! is_multisite() ) {
return true;
}
return switch_to_blog( $blogId );
}
/**
* Wrapper for restore_current_blog especially for non-multisite setups.
*
* @since 1.0.0
*
* @return bool Whether we're already on the current blog or not in a multisite environment.
*/
public function restoreCurrentBlog() {
if ( ! is_multisite() ) {
return false;
}
return restore_current_blog();
}
}
@@ -0,0 +1,75 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all WordPress related URL, URI, path, slug, etc. related helper methods.
*
* @since 1.0.0
*/
trait WpUri {
/**
* Returns the site domain.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The site's domain.
*/
public function getSiteDomain( $unfiltered = false ) {
return wp_parse_url( $this->getHomeUrl( $unfiltered ), PHP_URL_HOST );
}
/**
* Returns the site URL.
* NOTE: For multisites inside a sub-directory, this returns the URL for the main site.
* This is intentional.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The site's domain.
*/
public function getSiteUrl( $unfiltered = false ) {
$homeUrl = $this->getHomeUrl( $unfiltered );
return wp_parse_url( $homeUrl, PHP_URL_SCHEME ) . '://' . wp_parse_url( $homeUrl, PHP_URL_HOST );
}
/**
* Retrieve the home path.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The home path.
*/
public function getHomePath( $unfiltered = false ) {
$path = wp_parse_url( $this->getHomeUrl( $unfiltered ), PHP_URL_PATH );
return $path ? trailingslashit( $path ) : '/';
}
/**
* Returns the home URL.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The home URL.
*/
private function getHomeUrl( $unfiltered = false ) {
$homeUrl = home_url();
if ( $unfiltered ) {
// We want to get this value straight from the DB to prevent plugins like WPML from filtering it.
// This will otherwise mess with things like license activation requests and redirects.
$homeUrl = get_option( 'home' );
}
return $homeUrl;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,214 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Access {
/**
* Capabilities for our users.
*
* @since 1.0.0
*
* @var array
*/
protected $capabilities = [
'aioseo_table_of_contents_about_us_page'
];
/**
* Roles we check capabilities against.
*
* @since 1.0.0
*
* @var array
*/
protected $roles = [
'superadmin' => 'superadmin',
'administrator' => 'administrator'
];
/**
* Whether or not we are updating roles.
*
* @since 1.1.0
*
* @var bool
*/
private $isUpdatingRoles = false;
/**
* Adds capabilities into WordPress for the current user.
*
* @since 1.0.0
*
* @return void
*/
public function addCapabilities() {
foreach ( $this->roles as $wpRole => $role ) {
$roleObject = get_role( $wpRole );
if ( ! is_object( $roleObject ) ) {
continue;
}
if ( current_user_can( 'edit_posts' ) || $this->isAdmin() ) {
foreach ( $this->capabilities as $cap ) {
$roleObject->add_cap( $cap );
}
}
}
$this->removeCapabilities();
}
/**
* Removes capabilities for any unknown role.
*
* @since 1.0.0
*
* @return void
*/
public function removeCapabilities() {
$this->isUpdatingRoles = true;
// Clear out capabilities for unknown roles.
$wpRoles = wp_roles();
$allRoles = $wpRoles->roles;
foreach ( $allRoles as $key => $wpRole ) {
$checkRole = is_multisite() ? 'superadmin' : 'administrator';
if ( $checkRole === $key ) {
continue;
}
if ( in_array( $key, $this->roles, true ) ) {
continue;
}
$role = get_role( $key );
if ( empty( $role ) ) {
continue;
}
if ( $this->isAdmin( $key ) ) {
continue;
}
foreach ( $this->capabilities as $capability ) {
if ( $role->has_cap( $capability ) ) {
$role->remove_cap( $capability );
}
}
}
}
/**
* Checks if the current user has the capability.
*
* @since 1.0.0
*
* @param string $capability The capability to check against.
* @param string|null $checkRole A role to check against.
* @return bool Whether or not the user has this capability.
*/
public function hasCapability( $capability, $checkRole = null ) {
// Only admins have access.
if ( $this->isAdmin( $checkRole ) ) {
return true;
}
if (
(
$this->can( 'publish_posts', $checkRole ) ||
$this->can( 'edit_posts', $checkRole )
) &&
false !== strpos( $capability, 'aioseo_table_of_contents_' )
) {
return true;
}
return false;
}
/**
* Gets all the capabilities for the current user.
*
* @since 1.0.0
*
* @param string|null $role A role to check against.
* @return array An array of capabilities.
*/
public function getAllCapabilities( $role = null ) {
$capabilities = [];
foreach ( $this->capabilities as $cap ) {
$capabilities[ $cap ] = $this->hasCapability( $cap, $role );
}
return $capabilities;
}
/**
* If the current user is an admin, or superadmin, they have access to all caps regardless.
*
* @since 1.0.0
*
* @param string|null $role The role to check admin privileges if we have one.
* @return bool Whether not the user/role is an admin.
*/
public function isAdmin( $role = null ) {
if ( $role ) {
if ( ( is_multisite() && 'superadmin' === $role ) || 'administrator' === $role ) {
return true;
}
return false;
}
if ( ( is_multisite() && current_user_can( 'superadmin' ) ) || current_user_can( 'administrator' ) ) {
return true;
}
return false;
}
/**
* Whether the current user (or role) can manage the plugin.
*
* @since 1.0.0
*
* @param string|null $checkRole The role to check.
* @return bool Whether the user/role can manage the plugin.
*/
public function canManage( $checkRole = null ) {
return $this->isAdmin( $checkRole );
}
/**
* Check if the passed in role can publish posts.
*
* @since 1.0.0
*
* @param string $capability The capability to check against.
* @param string $role The role to check.
* @return boolean True if the role can publish.
*/
protected function can( $capability, $role ) {
if ( empty( $role ) ) {
return current_user_can( $capability );
}
$wpRoles = wp_roles();
$allRoles = $wpRoles->roles;
foreach ( $allRoles as $key => $wpRole ) {
if ( $key === $role ) {
$r = get_role( $key );
if ( $r->has_cap( $capability ) ) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,304 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This class makes sure the Action Scheduler tables always exist.
*
* @since 1.0.0
*/
class ActionScheduler {
/**
* The Action Scheduler group.
*
* @since 1.0.0
*
* @var string
*/
private $actionSchedulerGroup = 'aioseo_table_of_contents';
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
add_action( 'action_scheduler_after_execute', [ $this, 'cleanup' ], 1000, 2 );
add_action( 'plugins_loaded', [ $this, 'maybeRecreateTables' ] );
}
/**
* Maybe register the `{$table_prefix}_actionscheduler_{$suffix}` tables with WordPress and create them if needed.
* Hooked into `plugins_loaded` action hook.
*
* @since 1.0.0
*
* @return void
*/
public function maybeRecreateTables() {
if ( ! is_admin() ) {
return;
}
if ( ! apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
return;
}
if (
! class_exists( 'ActionScheduler' ) ||
! class_exists( 'ActionScheduler_HybridStore' ) ||
! class_exists( 'ActionScheduler_StoreSchema' ) ||
! class_exists( 'ActionScheduler_LoggerSchema' )
) {
return;
}
$store = \ActionScheduler::store();
if ( ! is_a( $store, 'ActionScheduler_HybridStore' ) ) {
$store = new \ActionScheduler_HybridStore();
}
$tableList = [
'actionscheduler_actions',
'actionscheduler_logs',
'actionscheduler_groups',
'actionscheduler_claims',
];
foreach ( $tableList as $tableName ) {
if ( ! aioseoTableOfContents()->core->db->tableExists( $tableName ) ) {
add_action( 'action_scheduler/created_table', [ $store, 'set_autoincrement' ], 10, 2 );
$storeSchema = new \ActionScheduler_StoreSchema();
$loggerSchema = new \ActionScheduler_LoggerSchema();
$storeSchema->register_tables( true );
$loggerSchema->register_tables( true );
remove_action( 'action_scheduler/created_table', [ $store, 'set_autoincrement' ] );
break;
}
}
}
/**
* Cleans up the Action Scheduler tables after one of our actions completes.
* Hooked into `action_scheduler_after_execute` action hook.
*
* @since 1.0.0
*
* @param int $actionId The action ID processed.
* @param \ActionScheduler_Action $action Class instance.
* @return void
*/
public function cleanup( $actionId, $action ) {
if (
// Bail if this isn't one of our actions or if we're in a dev environment.
$this->actionSchedulerGroup !== $action->get_group() ||
defined( 'AIOSEO_TABLE_OF_CONTENTS_DEV_VERSION' ) ||
// Bail if the tables don't exist.
! aioseoTableOfContents()->core->db->tableExists( 'actionscheduler_actions' ) ||
! aioseoTableOfContents()->core->db->tableExists( 'actionscheduler_groups' )
) {
return;
}
$prefix = aioseoTableOfContents()->core->db->db->prefix;
// Clean up logs associated with entries in the actions table.
aioseoTableOfContents()->core->db->execute(
"DELETE al FROM {$prefix}actionscheduler_logs as al
JOIN {$prefix}actionscheduler_actions as aa on `aa`.`action_id` = `al`.`action_id`
JOIN {$prefix}actionscheduler_groups as ag on `ag`.`group_id` = `aa`.`group_id`
WHERE `ag`.`slug` = '{$this->actionSchedulerGroup}'
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up actions.
aioseoTableOfContents()->core->db->execute(
"DELETE aa FROM {$prefix}actionscheduler_actions as aa
JOIN {$prefix}actionscheduler_groups as ag on `ag`.`group_id` = `aa`.`group_id`
WHERE `ag`.`slug` = '{$this->actionSchedulerGroup}'
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up logs where there was no group.
aioseoTableOfContents()->core->db->execute(
"DELETE al FROM {$prefix}actionscheduler_logs as al
JOIN {$prefix}actionscheduler_actions as aa on `aa`.`action_id` = `al`.`action_id`
WHERE `aa`.`hook` LIKE '{$this->actionSchedulerGroup}_%'
AND `aa`.`group_id` = 0
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up actions that start with aioseo_ and have no group.
aioseoTableOfContents()->core->db->execute(
"DELETE aa FROM {$prefix}actionscheduler_actions as aa
WHERE `aa`.`hook` LIKE '{$this->actionSchedulerGroup}_%'
AND `aa`.`group_id` = 0
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
}
/**
* Schedules a single action at a specific time in the future.
* @NOTE: This method differs from the one in the main plugin!
*
* @since 1.0.0
* @version 202608.2 Added the $forceSchedule parameter.
*
* @param string $actionName The action name.
* @param int $time The time to add to the current time.
* @param array $args Args passed down to the action.
* @param bool $forceSchedule Whether we should schedule a new action regardless of whether one is already set.
* @return boolean Whether the action was scheduled.
*/
public function scheduleSingle( $actionName, $time, $args = [], $forceSchedule = false ) {
try {
if ( $forceSchedule || empty( $this->getPendingActions( $actionName, $args ) ) ) {
as_schedule_single_action( time() + $time, $actionName, $args, $this->actionSchedulerGroup );
return true;
}
} catch ( \RuntimeException $e ) {
// Nothing needs to happen.
}
return false;
}
/**
* Checks if a given action is already scheduled.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return boolean Whether the action is already scheduled.
*/
public function isScheduled( $actionName, $args = [] ) {
$actions = array_merge(
$this->getRunningActions( $actionName, $args ),
$this->getPendingActions( $actionName, $args )
);
return ! empty( $actions );
}
/**
* Returns the running actions for a given action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return array The actions.
*/
public function getRunningActions( $actionName, $args = [] ) {
$runningArgs = [
'hook' => $actionName,
'status' => \ActionScheduler_Store::STATUS_RUNNING,
'per_page' => 1
];
if ( empty( $args ) ) {
$runningArgs['args'] = $args;
}
$actions = as_get_scheduled_actions( $runningArgs );
return $actions;
}
/**
* Returns the pending actions for a given action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return array The actions.
*/
public function getPendingActions( $actionName, $args = [] ) {
$pendingArgs = [
'hook' => $actionName,
'status' => \ActionScheduler_Store::STATUS_PENDING,
'per_page' => 1
];
if ( empty( $args ) ) {
$pendingArgs['args'] = $args;
}
$actions = as_get_scheduled_actions( $pendingArgs );
return $actions;
}
/**
* Unschedule an action.
*
* @since 1.0.0
*
* @param string $actionName The action name to unschedule.
* @param array $args Args passed down to the action.
* @return void
*/
public function unschedule( $actionName, $args = [] ) {
try {
if ( as_next_scheduled_action( $actionName ) ) {
as_unschedule_action( $actionName, $args, $this->actionSchedulerGroup );
}
} catch ( \Exception $e ) {
// Do nothing.
}
}
/**
* Schedules a recurring action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param int $time The seconds to add to the current time.
* @param int $interval The interval in seconds.
* @param array $args Args passed down to the action.
* @return boolean Whether the action was scheduled.
*/
public function scheduleRecurrent( $actionName, $time, $interval = 60, $args = [] ) {
try {
if ( ! $this->isScheduled( $actionName ) ) {
as_schedule_recurring_action( time() + $time, $interval, $actionName, $args, $this->actionSchedulerGroup );
return true;
}
} catch ( \RuntimeException $e ) {
// Nothing needs to happen.
}
return false;
}
/**
* Schedule a single async action.
*
* @since 1.0.0
*
* @param string $actionName The name of the action.
* @param array $args Any relevant arguments.
* @return void
*/
public function scheduleAsync( $actionName, $args = [] ) {
try {
// Run the task immediately using an async action.
as_enqueue_async_action( $actionName, $args, $this->actionSchedulerGroup );
} catch ( \Exception $e ) {
// Do nothing.
}
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits\Helpers as TraitHelpers;
/**
* Contains helper functions
*
* @since 1.0.0
*/
class Helpers {
use TraitHelpers\Api;
use TraitHelpers\Arrays;
use TraitHelpers\Constants;
use TraitHelpers\DateTime;
use TraitHelpers\Strings;
use TraitHelpers\ThirdParty;
use TraitHelpers\Vue;
use TraitHelpers\Wp;
use TraitHelpers\WpContext;
use TraitHelpers\WpMultisite;
use TraitHelpers\WpUri;
/**
* Checks if we are in a dev environment or not.
*
* @since 1.0.0
*
* @return boolean True if we are, false if not.
*/
public function isDev() {
return aioseoTableOfContents()->isDev || isset( $_REQUEST['aioseo-dev'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
/**
* Generates a UTM URL from the URL and medium/content that are passed in.
*
* @since 1.0.0
*
* @param string $url The URL to parse.
* @param string $medium The UTM medium parameter.
* @param string|null $content The UTM content parameter or null.
* @param boolean $esc Whether or not to escape the URL.
* @return string The new URL.
*/
public function utmUrl( $url, $medium, $content = null, $esc = true ) {
// First, remove any existing utm parameters on the URL.
$url = remove_query_arg( [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_content'
], $url );
// Generate the new arguments.
$args = [
'utm_source' => 'WordPress',
'utm_campaign' => 'toc-plugin',
'utm_medium' => $medium
];
// Content is not used by default.
if ( $content ) {
$args['utm_content'] = $content;
}
// Return the new URL.
$url = add_query_arg( $args, $url );
return $esc ? esc_url( $url ) : $url;
}
/**
* Returns the excluded domains.
*
* @since 1.1.1
*
* @return array The excluded domains.
*/
public function getExcludedDomains() {
if ( ! aioseoTableOfContents()->options->advanced->enable ) {
return [];
}
$excludedDomains = aioseoTableOfContents()->options->advanced->excludeDomains;
if ( ! is_string( $excludedDomains ) ) {
return [];
}
$pattern = '/([\.?!][\r\n\s]+|\r|\n|\s{2,})/u';
return array_map( 'trim', preg_split( $pattern, (string) $excludedDomains, -1, PREG_SPLIT_NO_EMPTY ) );
}
/**
* Checks if the given string is serialized, and if so, unserializes it.
* If the serialized string contains an object, we abort to prevent PHP object injection.
*
* @since 1.2.0
*
* @param string $string The string.
* @return string|array The string or unserialized data.
*/
public function maybeUnserialize( $string ) {
if ( ! is_string( $string ) ) {
return $string;
}
$string = trim( $string );
if ( is_serialized( $string ) && ! $this->stringContains( $string, ';O:' ) ) {
// We want to add extra hardening for PHP versions greater than 5.6.
return version_compare( PHP_VERSION, '7.0', '<' )
? @unserialize( $string )
: @unserialize( $string, [ 'allowed_classes' => false ] ); // phpcs:disable PHPCompatibility.FunctionUse.NewFunctionParameters.unserialize_optionsFound
}
return $string;
}
}
@@ -0,0 +1,222 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use WP_Error;
/** \WP_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
/** \Plugin_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
/**
* In WP 5.3 a PHP 5.6 splat operator (...$args) was added to \WP_Upgrader_Skin::feedback().
* We need to remove all calls to *Skin::feedback() method, as we can't override it in own Skins
* without breaking support for PHP 5.3-5.5.
*
* @internal Please do not use this class outside of core AIOSEO development.
*
* @since 1.0.0
*/
class PluginUpgraderSilentAjax extends \Plugin_Upgrader {
/**
* An array of links to install the plugins from.
*
* @since 1.0.0
*
* @var array
*/
public $pluginLinks = [
'aioseo' => 'https://downloads.wordpress.org/plugins/all-in-one-seo-pack.zip',
'brokenLinkChecker' => 'https://downloads.wordpress.org/plugin/broken-link-checker-seo.zip',
'optinMonster' => 'https://downloads.wordpress.org/plugin/optinmonster.zip',
'wpForms' => 'https://downloads.wordpress.org/plugin/wpforms-lite.zip',
'wpConsent' => 'https://downloads.wordpress.org/plugin/wpconsent-cookies-banner-privacy-suite.zip',
'wpVibe' => 'https://downloads.wordpress.org/plugin/vibe-ai.zip',
'universally' => 'https://downloads.wordpress.org/plugin/universally-language-translation-multilingual-tool.zip',
'miLite' => 'https://downloads.wordpress.org/plugin/google-analytics-for-wordpress.zip',
'emLite' => 'https://downloads.wordpress.org/plugin/google-analytics-dashboard-for-wp.zip',
'wpMail' => 'https://downloads.wordpress.org/plugin/wp-mail-smtp.zip',
'rafflePress' => 'https://downloads.wordpress.org/plugin/rafflepress.zip',
'seedProd' => 'https://downloads.wordpress.org/plugin/coming-soon.zip',
'instagramFeed' => 'https://downloads.wordpress.org/plugin/instagram-feed.zip',
'facebookFeed' => 'https://downloads.wordpress.org/plugin/custom-facebook-feed.zip',
'twitterFeed' => 'https://downloads.wordpress.org/plugin/custom-twitter-feeds.zip',
'youTubeFeed' => 'https://downloads.wordpress.org/plugin/feeds-for-youtube.zip',
'pushEngage' => 'https://downloads.wordpress.org/plugins/pushengage.zip',
'sugarCalendar' => 'https://downloads.wordpress.org/plugins/sugar-calendar-lite.zip',
'wpSimplePay' => 'https://downloads.wordpress.org/plugins/stripe.zip',
'easyDigitalDownloads' => 'https://downloads.wordpress.org/plugins/easy-digital-downloads.zip',
'wpcode' => 'https://downloads.wordpress.org/plugin/insert-headers-and-footers.zip',
'searchWp' => '',
'affiliateWp' => '',
'charitable' => 'https://downloads.wordpress.org/plugin/charitable.zip',
'duplicator' => 'https://downloads.wordpress.org/plugin/duplicator.zip',
'uncannyAutomator' => 'https://downloads.wordpress.org/plugin/uncanny-automator.zip',
'pdfEmbedder' => 'https://downloads.wordpress.org/plugin/pdf-embedder.zip',
'reviewsFeed' => 'https://downloads.wordpress.org/plugin/reviews-feed.zip',
'enviraGallery' => 'https://downloads.wordpress.org/plugin/envira-gallery-lite.zip',
'userFeedback' => 'https://downloads.wordpress.org/plugin/userfeedback-lite.zip',
'activeLayer' => 'https://downloads.wordpress.org/plugin/activelayer-anti-spam-spam-protection-for-forms-comments.zip',
'wpChat' => 'https://downloads.wordpress.org/plugin/smashballoon-wpchat-livechat-customer-support.zip'
];
/**
* An array of links to install the plugins from wordpress.org.
*
* @since 1.0.0
*
* @var array
*/
public $wpPluginLinks = [
'aioseo' => 'https://wordpress.org/plugins/all-in-one-seo-pack/',
'optinMonster' => 'https://wordpress.org/plugin/optinmonster/',
'wpForms' => 'https://wordpress.org/plugin/wpforms-lite/',
'wpConsent' => 'https://wordpress.org/plugins/wpconsent-cookies-banner-privacy-suite/',
'wpVibe' => 'https://wordpress.org/plugins/vibe-ai/',
'universally' => 'https://wordpress.org/plugins/universally-language-translation-multilingual-tool/',
'miLite' => 'https://wordpress.org/plugin/google-analytics-for-wordpress/',
'emLite' => 'https://wordpress.org/plugin/google-analytics-dashboard-for-wp/',
'wpMail' => 'https://wordpress.org/plugin/wp-mail-smtp/',
'rafflePress' => 'https://wordpress.org/plugin/rafflepress/',
'seedProd' => 'https://wordpress.org/plugin/coming-soon/',
'instagramFeed' => 'https://wordpress.org/plugin/instagram-feed/',
'facebookFeed' => 'https://wordpress.org/plugin/custom-facebook-feed/',
'twitterFeed' => 'https://wordpress.org/plugin/custom-twitter-feeds/',
'youTubeFeed' => 'https://wordpress.org/plugin/feeds-for-youtube/',
'pushEngage' => 'https://wordpress.org/plugins/pushengage/',
'sugarCalendar' => 'https://wordpress.org/plugins/sugar-calendar-lite/',
'wpSimplePay' => 'https://wordpress.org/plugins/stripe/',
'searchWp' => 'https://searchwp.com/',
'affiliateWp' => 'https://affiliatewp.com/',
'wpcode' => 'https://wordpress.org/plugins/insert-headers-and-footers/',
'charitable' => 'https://wordpress.org/plugins/charitable/',
'duplicator' => 'https://wordpress.org/plugins/duplicator/',
'uncannyAutomator' => 'https://wordpress.org/plugins/uncanny-automator/',
'pdfEmbedder' => 'https://wordpress.org/plugins/pdf-embedder/',
'reviewsFeed' => 'https://wordpress.org/plugins/reviews-feed/',
'enviraGallery' => 'https://wordpress.org/plugins/envira-gallery-lite/',
'userFeedback' => 'https://wordpress.org/plugins/userfeedback-lite/',
'activeLayer' => 'https://wordpress.org/plugins/activelayer-anti-spam-spam-protection-for-forms-comments/',
'wpChat' => 'https://wordpress.org/plugins/smashballoon-wpchat-livechat-customer-support/'
];
/**
* An array of slugs to check if plugins are activated.
*
* @since 1.0.0
*
* @var array
*/
public $pluginSlugs = [
'aioseo' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'aioseoPro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
'brokenLinkChecker' => 'broken-link-checker-seo/aioseo-broken-link-checker.php',
'optinMonster' => 'optinmonster/optin-monster-wp-api.php',
'wpForms' => 'wpforms-lite/wpforms.php',
'wpFormsPro' => 'wpforms/wpforms.php',
'wpConsent' => 'wpconsent-cookies-banner-privacy-suite/wpconsent.php',
'wpVibe' => 'vibe-ai/vibe-ai.php',
'universally' => 'universally-language-translation-multilingual-tool/universally.php',
'miLite' => 'google-analytics-for-wordpress/googleanalytics.php',
'miPro' => 'google-analytics-premium/googleanalytics-premium.php',
'emLite' => 'google-analytics-dashboard-for-wp/gadwp.php',
'emPro' => 'exactmetrics-premium/exactmetrics-premium.php',
'wpMail' => 'wp-mail-smtp/wp_mail_smtp.php',
'wpMailPro' => 'wp-mail-smtp-pro/wp_mail_smtp.php',
'rafflePress' => 'rafflepress/rafflepress.php',
'rafflePressPro' => 'rafflepress-pro/rafflepress-pro.php',
'seedProd' => 'coming-soon/coming-soon.php',
'seedProdPro' => 'seedprod-coming-soon-pro-5/seedprod-coming-soon-pro-5.php',
'instagramFeed' => 'instagram-feed/instagram-feed.php',
'instagramFeedPro' => 'instagram-feed-pro/instagram-feed.php',
'facebookFeed' => 'custom-facebook-feed/custom-facebook-feed.php',
'facebookFeedPro' => 'custom-facebook-feed-pro/custom-facebook-feed.php',
'twitterFeed' => 'custom-twitter-feeds/custom-twitter-feed.php',
'twitterFeedPro' => 'custom-twitter-feeds-pro/custom-twitter-feed.php',
'youTubeFeed' => 'feeds-for-youtube/youtube-feed.php',
'youTubeFeedPro' => 'youtube-feed-pro/youtube-feed.php',
'pushEngage' => 'pushengage/main.php',
'sugarCalendar' => 'sugar-calendar-lite/sugar-calendar-lite.php',
'sugarCalendarPro' => 'sugar-calendar/sugar-calendar.php',
'wpSimplePay' => 'stripe/stripe-checkout.php',
'wpSimplePayPro' => 'wp-simple-pay-pro-3/simple-pay.php',
'easyDigitalDownloads' => 'easy-digital-downloads/easy-digital-downloads.php',
'easyDigitalDownloadsPro' => 'easy-digital-downloads-pro/easy-digital-downloads.php',
'searchWp' => 'searchwp/index.php',
'affiliateWp' => 'affiliate-wp/affiliate-wp.php',
'wpcode' => 'insert-headers-and-footers/ihaf.php',
'wpcodePro' => 'wpcode-premium/wpcode.php',
'charitable' => 'charitable/charitable.php',
'duplicator' => 'duplicator/duplicator.php',
'uncannyAutomator' => 'uncanny-automator/uncanny-automator.php',
'pdfEmbedder' => 'pdf-embedder/pdf_embedder.php',
'reviewsFeed' => 'reviews-feed/sb-reviews.php',
'enviraGallery' => 'envira-gallery-lite/envira-gallery-lite.php',
'userFeedback' => 'userfeedback-lite/userfeedback.php',
'activeLayer' => 'activelayer-anti-spam-spam-protection-for-forms-comments/activelayer-anti-spam-spam-protection-for-forms-comments.php',
'wpChat' => 'smashballoon-wpchat-livechat-customer-support/wp-chat.php'
];
/**
* An array of links for admin settings.
*
* @since 1.0.0
*
* @var array
*/
public $pluginAdminUrls = [
'aioseo' => 'admin.php?page=aioseo-settings',
'aioseoPro' => 'admin.php?page=aioseo-settings',
'brokenLinkChecker' => 'admin.php?page=broken-link-checker',
'optinMonster' => 'admin.php?page=optin-monster-api-settings',
'wpForms' => 'admin.php?page=wpforms-settings',
'wpFormsPro' => 'admin.php?page=wpforms-settings',
'wpConsent' => 'admin.php?page=wpconsent',
'wpVibe' => 'admin.php?page=vibe-ai',
'universally' => 'admin.php?page=universally_settings',
'miLite' => 'admin.php?page=monsterinsights_settings#/',
'miPro' => 'admin.php?page=monsterinsights_settings#/',
'emLite' => 'admin.php?page=exactmetrics_settings#/',
'emPro' => 'admin.php?page=exactmetrics_settings#/',
'wpMail' => 'admin.php?page=wp-mail-smtp',
'wpMailPro' => 'admin.php?page=wp-mail-smtp',
'seedProd' => 'admin.php?page=seedprod_lite',
'seedProdPro' => 'admin.php?page=seedprod_pro',
'rafflePress' => 'admin.php?page=rafflepress_lite#/settings',
'rafflePressPro' => 'admin.php?page=rafflepress_pro#/settings',
'instagramFeed' => 'admin.php?page=sb-instagram-feed',
'instagramFeedPro' => 'admin.php?page=sb-instagram-feed',
'facebookFeed' => 'admin.php?page=cff-top',
'facebookFeedPro' => 'admin.php?page=cff-top',
'twitterFeed' => 'admin.php?page=ctf-settings',
'twitterFeedPro' => 'admin.php?page=ctf-settings',
'youTubeFeed' => 'admin.php?page=youtube-feed-settings',
'youTubeFeedPro' => 'admin.php?page=youtube-feed-settings',
'pushEngage' => 'admin.php?page=pushengage',
'sugarCalendar' => 'admin.php?page=sugar-calendar',
'sugarCalendarPro' => 'admin.php?page=sugar-calendar',
'wpSimplePay' => 'edit.php?post_type=simple-pay',
'wpSimplePayPro' => 'edit.php?post_type=simple-pay',
'easyDigitalDownloads' => 'edit.php?post_type=download&page=edd-settings',
'easyDigitalDownloadsPro' => 'edit.php?post_type=download&page=edd-settings',
'searchWp' => 'options-general.php?page=searchwp',
'affiliateWp' => 'admin.php?page=affiliate-wp',
'wpcode' => 'admin.php?page=wpcode',
'wpcodePro' => 'admin.php?page=wpcode',
'charitable' => 'admin.php?page=charitable-settings',
'duplicator' => 'admin.php?page=duplicator-settings',
'uncannyAutomator' => 'edit.php?post_type=uo-recipe',
'pdfEmbedder' => 'options-general.php?page=pdf_embedder',
'reviewsFeed' => 'admin.php?page=sbr',
'enviraGallery' => 'edit.php?post_type=envira',
'userFeedback' => 'admin.php?page=userfeedback',
'activeLayer' => 'admin.php?page=activelayer',
'wpChat' => 'admin.php?page=wpchat'
];
}
@@ -0,0 +1,67 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
/**
* The PluginSilentUpgraderSkin class.
*
* @internal Please do not use this class outside of core AIOSEO development.
*
* @since 1.0.0
*/
class PluginUpgraderSkin extends \WP_Upgrader_Skin {
/**
* Empty out the header of its HTML content and only check to see if it has
* been performed or not.
*
* @since 1.0.0
*/
public function header() {}
/**
* Empty out the footer of its HTML contents.
*
* @since 1.0.0
*/
public function footer() {}
/**
* Instead of outputting HTML for errors, just return them.
* AJAX request will just ignore it.
*
* @since 1.0.0
*
* @param array $errors Array of errors with the install process.
* @return void
*/
public function error( $errors ) {
if ( ! empty( $errors ) ) {
wp_send_json_error( $errors );
}
}
/**
* Empty out JavaScript output that calls function to decrement the update counts.
*
* @since 1.0.0
*
* @param string $type Type of update count to decrement.
*/
public function decrement_update_count( $type ) {} // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable, PSR1.Methods.CamelCapsMethodName.NotCamelCaps
/**
* @since 1.0.0
*
* @param string $feedback Message data.
* @param mixed ...$args Optional text replacements.
* @return void
*/
public function feedback( $feedback, ...$args ) {} // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
}
@@ -0,0 +1,166 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Vue Settings for the user.
*
* @since 1.0.0
*/
class VueSettings {
/**
* The name to lookup the settings with.
*
* @since 1.0.0
*
* @var string
*/
private $settingsName = '';
/**
* The settings array.
*
* @since 1.0.0
*
* @var array
*/
private $settings = [];
/**
* All the default settings.
*
* @since 1.0.0
*
* @var array
*/
private $defaults = [
'toggledRadio' => [],
'tablePagination' => []
];
/**
* Class constructor.
*
* @since 1.0.0
*
* @param string $settings List of settings.
*/
public function __construct( $settings = '_aioseo_table_of_contents_settings' ) {
$this->settingsName = $settings;
$userMeta = get_user_meta( get_current_user_id(), $settings, true );
$this->settings = ! empty( $userMeta ) ? array_replace_recursive( $this->defaults, $userMeta ) : $this->defaults;
}
/**
* Retrieves all settings.
*
* @since 1.0.0
*
* @return array List of settings.
*/
public function all() {
return array_replace_recursive( $this->defaults, $this->settings );
}
/**
* Retrieve a setting or null if missing.
*
* @since 1.0.0
*
* @param string $name The name of the property that is missing on the class.
* @param array $arguments The arguments passed into the method.
* @return mixed The value from the settings or default/null.
*/
public function __call( $name, $arguments = [] ) {
$value = isset( $this->settings[ $name ] ) ? $this->settings[ $name ] : ( ! empty( $arguments[0] ) ? $arguments[0] : $this->getDefault( $name ) );
return $value;
}
/**
* Retrieve a setting or null if missing.
*
* @since 1.0.0
*
* @param string $name The name of the property that is missing on the class.
* @return mixed The value from the settings or default/null.
*/
public function __get( $name ) {
$value = isset( $this->settings[ $name ] ) ? $this->settings[ $name ] : $this->getDefault( $name );
return $value;
}
/**
* Sets the settings value and saves to the database.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @param mixed $value The value to set.
* @return void
*/
public function __set( $name, $value ) {
$this->settings[ $name ] = $value;
$this->update();
}
/**
* Checks if an settings is set or returns null if not.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @return mixed True or null.
*/
public function __isset( $name ) {
return isset( $this->settings[ $name ] ) ? false === empty( $this->settings[ $name ] ) : null;
}
/**
* Unsets the settings value and saves to the database.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @return void
*/
public function __unset( $name ) {
if ( ! isset( $this->settings[ $name ] ) ) {
return;
}
unset( $this->settings[ $name ] );
$this->update();
}
/**
* Gets the default value for a setting.
*
* @since 1.0.0
*
* @param string $name The settings name.
* @return mixed The default value.
*/
public function getDefault( $name ) {
return isset( $this->defaults[ $name ] ) ? $this->defaults[ $name ] : null;
}
/**
* Updates the settings in the database.
*
* @since 1.0.0
*
* @return void
*/
public function update() {
update_user_meta( get_current_user_id(), $this->settingsName, $this->settings );
}
}
@@ -0,0 +1,26 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! function_exists( 'aioseo_table_of_contents_is_plugin_disabled' ) ) {
/**
* Disable the plugin if triggered externally.
*
* @since 1.0.0
*
* @return bool True if the plugin should be disabled.
*/
function aioseo_table_of_contents_is_plugin_disabled() {
if ( ! defined( 'AIOSEO_DEV_VERSION' ) && ! isset( $_REQUEST['aioseo-dev'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
return false;
}
if ( ! isset( $_REQUEST['aioseo-disable-table-of-contents'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
return false;
}
return true;
}
}
@@ -0,0 +1,199 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// phpcs:disable Generic.Arrays.DisallowLongArraySyntax.Found
if ( ! function_exists( 'aioseo_table_of_contents_php_notice' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_php_notice() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - Opening HTML link tag, 4 - Closing HTML link tag.
__( 'Your site is running an %1$sinsecure version%2$s of PHP that is no longer supported. Please contact your web hosting provider to update your PHP version or switch to a %3$srecommended WordPress hosting company%4$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'<a href="https://www.wpbeginner.com/wordpress-hosting/" target="_blank" rel="noopener noreferrer">',
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The short plugin name ("AIOSEO"), 4 - Opening HTML link tag, 5 - Closing HTML link tag.
__( '%1$sNote:%2$s %3$s plugin is disabled on your site until you fix the issue. %4$sRead more for additional information.%5$s', 'table-of-contents-plus' ),
'<strong>',
'</strong>',
'AIOSEO',
'<a href="https://aioseo.com/docs/supported-php-version/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-php-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}
if ( ! function_exists( 'aioseo_table_of_contents_php_notice_deprecated' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_php_notice_deprecated() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The plugin short name ("AIOSEO"), 4 - Opening HTML link tag, 5 - Closing HTML link tag.
__( 'Your site is running an %1$soutdated version%2$s of PHP that is no longer supported and may cause issues with %3$s. Please contact your web hosting provider to update your PHP version or switch to a %4$srecommended WordPress hosting company%5$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'<strong>AIOSEO</strong>',
'<a href="https://www.wpbeginner.com/wordpress-hosting/" target="_blank" rel="noopener noreferrer">',
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// phpcs:ignore Generic.Files.LineLength.MaxExceeded
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The PHP version, 4 - The current year, 5 - The short plugin name ("AIOSEO"), 6 - Opening HTML link tag, 7 - Closing HTML link tag.
__( '%1$sNote:%2$s Support for PHP %3$s will be discontinued in %4$s. After this, if no further action is taken, %5$s functionality will be disabled. %6$sRead more for additional information.%7$s', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
PHP_VERSION,
gmdate( 'Y' ),
'AIOSEO',
'<a href="https://aioseo.com/docs/supported-php-version/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-php-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}
if ( ! function_exists( 'aioseo_table_of_contents_wordpress_notice' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_wordpress_notice() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The plugin name ("All in One SEO").
__( 'Your site is running an %1$sinsecure version%2$s of WordPress that is no longer supported. Please update your site to the latest version of WordPress in order to continue using %3$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'All in One SEO'
),
array(
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// phpcs:ignore Generic.Files.LineLength.MaxExceeded
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The short plugin name ("AIOSEO"), 4 - The WordPress version, 5 - The current year, 6 - Opening HTML link tag, 7 - Closing HTML link tag.
__( '%1$sNote:%2$s %3$s will be discontinuing support for WordPress versions older than version %4$s by the end of %5$s. %6$sRead more for additional information.%7$s', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'AIOSEO',
'6.0',
gmdate( 'Y' ),
'<a href="https://aioseo.com/docs/update-wordpress/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-wordpress-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}
@@ -0,0 +1,188 @@
/*!
* jQuery Smooth Scroll - v1.6.0 - 2015-12-26
* https://github.com/kswedberg/jquery-smooth-scroll
* Copyright (c) 2015 Karl Swedberg
* Licensed MIT
*/
!function(a){"function"==typeof define&&define.amd?
// AMD. Register as an anonymous module.
define(["jquery"],a):a("object"==typeof module&&module.exports?require("jquery"):jQuery)}(function(a){function b(a){return a.replace(/(:|\.|\/)/g,"\\$1")}var c="1.6.0",d={},e={exclude:[],excludeWithin:[],offset:0,
// one of 'top' or 'left'
direction:"top",
// if set, bind click events through delegation
// supported since jQuery 1.4.2
delegateSelector:null,
// jQuery set of elements you wish to scroll (for $.smoothScroll).
// if null (default), $('html, body').firstScrollable() is used.
scrollElement:null,
// only use if you want to override default behavior
scrollTarget:null,
// fn(opts) function to be called before scrolling occurs.
// `this` is the element(s) being scrolled
beforeScroll:function(){},
// fn(opts) function to be called after scrolling occurs.
// `this` is the triggering element
afterScroll:function(){},easing:"swing",speed:400,
// coefficient for "auto" speed
autoCoefficient:2,
// $.fn.smoothScroll only: whether to prevent the default click action
preventDefault:!0},f=function(b){var c=[],d=!1,e=b.dir&&"left"===b.dir?"scrollLeft":"scrollTop";
// If no scrollable elements, fall back to <body>,
// if it's in the jQuery collection
// (doing this because Safari sets scrollTop async,
// so can't set it to 1 and immediately get the value.)
// Use the first scrollable element if we're calling firstScrollable()
return this.each(function(){var b=a(this);if(this!==document&&this!==window)
// if scroll(Top|Left) === 0, nudge the element 1px and see if it moves
// then put it back, of course
return!document.scrollingElement||this!==document.documentElement&&this!==document.body?void(b[e]()>0?c.push(this):(b[e](1),d=b[e]()>0,d&&c.push(this),b[e](0))):(c.push(document.scrollingElement),!1)}),c.length||this.each(function(){"BODY"===this.nodeName&&(c=[this])}),"first"===b.el&&c.length>1&&(c=[c[0]]),c};a.fn.extend({scrollable:function(a){var b=f.call(this,{dir:a});return this.pushStack(b)},firstScrollable:function(a){var b=f.call(this,{el:"first",dir:a});return this.pushStack(b)},smoothScroll:function(c,d){if(c=c||{},"options"===c)return d?this.each(function(){var b=a(this),c=a.extend(b.data("ssOpts")||{},d);a(this).data("ssOpts",c)}):this.first().data("ssOpts");var e=a.extend({},a.fn.smoothScroll.defaults,c),f=function(c){var d=this,f=a(this),g=a.extend({},e,f.data("ssOpts")||{}),h=e.exclude,i=g.excludeWithin,j=0,k=0,l=!0,m={},n=a.smoothScroll.filterPath(location.pathname),o=a.smoothScroll.filterPath(d.pathname),p=location.hostname===d.hostname||!d.hostname,q=g.scrollTarget||o===n,r=b(d.hash);if(g.scrollTarget||p&&q&&r){for(;l&&j<h.length;)f.is(b(h[j++]))&&(l=!1);for(;l&&k<i.length;)f.closest(i[k++]).length&&(l=!1)}else l=!1;l&&(g.preventDefault&&c.preventDefault(),a.extend(m,g,{scrollTarget:g.scrollTarget||r,link:d}),a.smoothScroll(m))};return null!==c.delegateSelector?this.undelegate(c.delegateSelector,"click.smoothscroll").delegate(c.delegateSelector,"click.smoothscroll",f):this.unbind("click.smoothscroll").bind("click.smoothscroll",f),this}}),a.smoothScroll=function(b,c){if("options"===b&&"object"==typeof c)return a.extend(d,c);var e,f,g,h,i,j=0,k="offset",l="scrollTop",m={},n={};"number"==typeof b?(e=a.extend({link:null},a.fn.smoothScroll.defaults,d),g=b):(e=a.extend({link:null},a.fn.smoothScroll.defaults,b||{},d),e.scrollElement&&(k="position","static"===e.scrollElement.css("position")&&e.scrollElement.css("position","relative"))),l="left"===e.direction?"scrollLeft":l,e.scrollElement?(f=e.scrollElement,/^(?:HTML|BODY)$/.test(f[0].nodeName)||(j=f[l]())):f=a("html, body").firstScrollable(e.direction),e.beforeScroll.call(f,e),g="number"==typeof b?b:c||a(e.scrollTarget)[k]()&&a(e.scrollTarget)[k]()[e.direction]||0,m[l]=g+j+e.offset,h=e.speed,"auto"===h&&(i=Math.abs(m[l]-f[l]()),h=i/e.autoCoefficient),n={duration:h,easing:e.easing,complete:function(){e.afterScroll.call(e.link,e)}},e.step&&(n.step=e.step),f.length?f.stop().animate(m,n):e.afterScroll.call(e.link,e)},a.smoothScroll.version=c,a.smoothScroll.filterPath=function(a){return a=a||"",a.replace(/^\//,"").replace(/(?:index|default).[a-zA-Z]{3,4}$/,"").replace(/\/$/,"")},
// default options
a.fn.smoothScroll.defaults=e});
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie=function(a,b,c){if(arguments.length>1&&String(b)!=="[object Object]"){c=jQuery.extend({},c);if(b===null||b===undefined){c.expires=-1}if(typeof c.expires==="number"){var d=c.expires,e=c.expires=new Date;e.setDate(e.getDate()+d)}b=String(b);return document.cookie=[encodeURIComponent(a),"=",c.raw?b:encodeURIComponent(b),c.expires?"; expires="+c.expires.toUTCString():"",c.path?"; path="+c.path:"",c.domain?"; domain="+c.domain:"",c.secure?"; secure":""].join("")}c=b||{};var f,g=c.raw?function(a){return a}:decodeURIComponent;return(f=(new RegExp("(?:^|; )"+encodeURIComponent(a)+"=([^;]*)")).exec(document.cookie))?g(f[1]):null}
jQuery(document).ready(function($) {
if ( typeof tocplus != 'undefined' ) {
$.fn.shrinkTOCWidth = function() {
$(this).css({
width: 'auto',
display: 'table'
});
if ( /MSIE 7\./.test(navigator.userAgent) )
$(this).css('width', '');
}
if ( tocplus.smooth_scroll == 1 ) {
var target = hostname = pathname = qs = hash = null;
// only bind to links generated by the plugin, not every anchor on the page
$(document).on('click', '#toc_container a, ul.toc_widget_list a', function(event) {
hostname = $(this).prop('hostname');
pathname = $(this).prop('pathname');
qs = $(this).prop('search');
hash = $(this).prop('hash');
// ie strips out the preceeding / from pathname
if ( pathname.length > 0 ) {
if ( pathname.charAt(0) != '/' ) {
pathname = '/' + pathname;
}
}
if ( (window.location.hostname == hostname) && (window.location.pathname == pathname) && (window.location.search == qs) && (hash !== '') ) {
// escape jquery selector chars, but keep the #
var hash_selector = hash.replace(/([ !"$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g, '\\$1');
// check if element exists with id=__
if ( $( hash_selector ).length > 0 )
target = hash;
else {
// must be an anchor (a name=__)
anchor = hash;
anchor = anchor.replace('#', '');
target = 'a[name="' + anchor + '"]';
// verify it exists
if ( $(target).length == 0 )
target = '';
}
// check offset setting
if (typeof tocplus.smooth_scroll_offset != 'undefined') {
offset = -1 * tocplus.smooth_scroll_offset;
}
else {
if ($('#wpadminbar').length > 0) {
if ($('#wpadminbar').is(':visible'))
offset = -30; // admin bar exists, give it the default
else
offset = 0; // there is an admin bar but it's hidden, so no offset!
}
else
offset = 0; // no admin bar, so no offset!
}
if ( target ) {
$.smoothScroll({
scrollTarget: target,
offset: offset
});
}
}
});
}
if ( typeof tocplus.visibility_show != 'undefined' ) {
var invert = ( typeof tocplus.visibility_hide_by_default != 'undefined' ) ? true : false ;
var cookie_set = ( $.cookie ) ? !!$.cookie('tocplus_hidetoc') : false;
var hidden = ( invert ) ? ! cookie_set : cookie_set;
// the cookie is scoped to the current page so toggling one TOC doesn't affect other pages
var save_state = function( is_hidden ) {
if ( ! $.cookie )
return;
// clean up the legacy site-wide cookie so it can't override the per-page state
$.cookie('tocplus_hidetoc', null, { path: '/' });
if ( is_hidden != invert )
$.cookie('tocplus_hidetoc', '1', { expires: 30, path: window.location.pathname });
else
$.cookie('tocplus_hidetoc', null, { path: window.location.pathname });
};
var toggle_style = ( typeof tocplus.toggle_style != 'undefined' ) ? tocplus.toggle_style : 'brackets';
var toggle_label = hidden ? tocplus.visibility_show : tocplus.visibility_hide;
// The label is admin and shortcode supplied, and WP_Scripts::localize() has already
// decoded its HTML entities by the time it reaches us, so it can only be assigned
// as text or via .attr() - never concatenated into an HTML string.
var toggle_link = $('<a></a>').attr('href', '#');
var toggle_wrap = $('<span></span>').addClass('toc_toggle');
if ( 'brackets' === toggle_style ) {
toggle_wrap.addClass('toc_toggle_brackets')
.append( $('<span></span>').addClass('toc_brackets').text('[') )
.append( toggle_link.text( toggle_label ) )
.append( $('<span></span>').addClass('toc_brackets').text(']') );
} else {
// Plus/minus and caret render a glyph (styled in CSS off the container's
// .contracted state); the label lives on aria-label for screen readers.
toggle_wrap.addClass('toc_toggle_icon').addClass('toc_toggle_' + toggle_style)
.append(
toggle_link.attr({ 'role': 'button', 'aria-label': toggle_label })
.append( $('<span></span>').addClass('toc_toggle_indicator').attr('aria-hidden', 'true') )
);
}
$('#toc_container .toc_title').append( document.createTextNode(' ') ).append( toggle_wrap );
if ( hidden ) {
$('ul.toc_list').hide();
$('#toc_container').addClass('contracted').shrinkTOCWidth();
}
$('span.toc_toggle a').click(function(event) {
event.preventDefault();
// track state via the container class rather than the label text,
// which breaks when translation plugins rewrite the DOM
var hide = ! $('#toc_container').hasClass('contracted');
var label = hide ? tocplus.visibility_show : tocplus.visibility_hide;
if ( 'brackets' === toggle_style ) {
$(this).text( label );
} else {
$(this).attr( 'aria-label', label );
}
save_state( hide );
if ( hide ) {
$('ul.toc_list').hide('fast');
$('#toc_container').addClass('contracted').shrinkTOCWidth();
} else {
$('#toc_container').css('width', tocplus.width).removeClass('contracted');
$('ul.toc_list').show('fast');
}
});
}
}
});
File diff suppressed because one or more lines are too long
@@ -0,0 +1,160 @@
#toc_container ul,#toc_container li {
margin:0;
padding:0;
list-style-position:inside;
}
#toc_container.no_bullets ul,
#toc_container.no_bullets li,
#toc_container.no_bullets ul li,
.toc_widget_list.no_bullets,
.toc_widget_list.no_bullets li {
background:none;
list-style-type:none;
list-style:none;
}
#toc_container.have_bullets li {
padding-left:12px;
}
#toc_container.toc_numbered ul {
list-style:none;
}
#toc_container ul ul {
margin-left:1.5em;
}
#toc_container {
background:#f9f9f9;
border:1px solid #aaa;
padding:10px;
margin-bottom:1em;
width:auto;
display:table;
font-size:95%;
}
#toc_container.toc_light_blue {
background:#edf6ff;
}
#toc_container.toc_white {
background:#fff;
}
#toc_container.toc_black {
background:#000;
}
#toc_container.toc_transparent {
background:none transparent;
}
#toc_container .toc_title {
text-align:left;
font-weight:700;
margin:0;
padding:0;
}
#toc_container.toc_title_center .toc_title {
text-align:center;
}
#toc_container.toc_title_right .toc_title {
text-align:right;
}
#toc_container.toc_black .toc_title {
color:#aaa;
}
#toc_container.toc_black a,
#toc_container.toc_black a:visited {
color:#fff;
}
#toc_container.toc_black a:hover {
color:#fff;
}
#toc_container span.toc_toggle {
font-weight:400;
font-size:90%;
}
#toc_container .toc_toggle_icon a {
text-decoration:none;
line-height:1;
}
#toc_container .toc_toggle_indicator {
display:inline-block;
line-height:1;
}
/* The border lives on the focusable <a> so the focus outline hugs the visible box. */
#toc_container .toc_toggle_plus_minus a {
display:inline-flex;
align-items:center;
justify-content:center;
width:1.3em;
height:1.3em;
border:1px solid currentColor;
border-radius:3px;
vertical-align:middle;
}
#toc_container .toc_toggle_plus_minus .toc_toggle_indicator {
font-size:0.8em;
}
#toc_container .toc_toggle_indicator::before {
font-weight:700;
}
#toc_container .toc_toggle_plus_minus .toc_toggle_indicator::before {
content:'\2212';
}
#toc_container.contracted .toc_toggle_plus_minus .toc_toggle_indicator::before {
content:'\002B';
}
#toc_container .toc_toggle_caret .toc_toggle_indicator::before {
content:'\25BE';
}
#toc_container.contracted .toc_toggle_caret .toc_toggle_indicator::before {
content:'\25B8';
}
#toc_container .toc_title + ul.toc_list {
margin-top:1em;
}
.toc_wrap_left {
float:left;
margin-right:10px;
}
.toc_wrap_right {
float:right;
margin-left:10px;
}
#toc_container a {
text-decoration:none;
text-shadow:none;
}
#toc_container a:hover {
text-decoration:underline;
}
.toc_sitemap_posts_letter {
font-size:1.5em;
font-style:italic;
}
@@ -0,0 +1 @@
#toc_container li,#toc_container ul{margin:0;padding:0;list-style-position:inside}#toc_container.no_bullets li,#toc_container.no_bullets ul,#toc_container.no_bullets ul li,.toc_widget_list.no_bullets,.toc_widget_list.no_bullets li{background:0 0;list-style-type:none;list-style:none}#toc_container.have_bullets li{padding-left:12px}#toc_container.toc_numbered ul{list-style:none}#toc_container ul ul{margin-left:1.5em}#toc_container{background:#f9f9f9;border:1px solid #aaa;padding:10px;margin-bottom:1em;width:auto;display:table;font-size:95%}#toc_container.toc_light_blue{background:#edf6ff}#toc_container.toc_white{background:#fff}#toc_container.toc_black{background:#000}#toc_container.toc_transparent{background:none transparent}#toc_container .toc_title{text-align:left;font-weight:700;margin:0;padding:0}#toc_container.toc_title_center .toc_title{text-align:center}#toc_container.toc_title_right .toc_title{text-align:right}#toc_container.toc_black .toc_title{color:#aaa}#toc_container.toc_black a,#toc_container.toc_black a:visited{color:#fff}#toc_container.toc_black a:hover{color:#fff}#toc_container span.toc_toggle{font-weight:400;font-size:90%}#toc_container .toc_toggle_icon a{text-decoration:none;line-height:1}#toc_container .toc_toggle_indicator{display:inline-block;line-height:1}#toc_container .toc_toggle_plus_minus a{display:inline-flex;align-items:center;justify-content:center;width:1.3em;height:1.3em;border:1px solid currentColor;border-radius:3px;vertical-align:middle}#toc_container .toc_toggle_plus_minus .toc_toggle_indicator{font-size:.8em}#toc_container .toc_toggle_indicator::before{font-weight:700}#toc_container .toc_toggle_plus_minus .toc_toggle_indicator::before{content:'\2212'}#toc_container.contracted .toc_toggle_plus_minus .toc_toggle_indicator::before{content:'\002B'}#toc_container .toc_toggle_caret .toc_toggle_indicator::before{content:'\25BE'}#toc_container.contracted .toc_toggle_caret .toc_toggle_indicator::before{content:'\25B8'}#toc_container .toc_title+ul.toc_list{margin-top:1em}.toc_wrap_left{float:left;margin-right:10px}.toc_wrap_right{float:right;margin-left:10px}#toc_container a{text-decoration:none;text-shadow:none}#toc_container a:hover{text-decoration:underline}.toc_sitemap_posts_letter{font-size:1.5em;font-style:italic}
@@ -0,0 +1,27 @@
{
"name": "awesomemotive/aioseo-table-of-contents-plus",
"description": "A powerful yet user friendly plugin that automatically creates a table of contents.",
"config": {
"bin-dir": "bin",
"preferred-install": "dist",
"platform": {
"php": "7.0"
},
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"autoload": {
"psr-4": {
"AIOSEO\\TableOfContents\\": "app/"
}
},
"require": {
"woocommerce/action-scheduler": "3.9.2"
},
"require-dev": {
"instituteweb/composer-scripts": "^1.1",
"vlucas/phpdotenv": "^5.4.1",
"wp-coding-standards/wpcs": "^3.0"
}
}
@@ -0,0 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=[window.__aioseoDynamicImportPreload__("js/AboutUs.B7-4Dk3Z.js"),window.__aioseoDynamicImportPreload__("js/_plugin-vue_export-helper.D5TAAMQM.js"),window.__aioseoDynamicImportPreload__("js/translations.BwNKZNiM.js"),window.__aioseoDynamicImportPreload__("css/translations.CoGMWdmt.css"),window.__aioseoDynamicImportPreload__("css/AboutUs.DHBBvFxy.css"),window.__aioseoDynamicImportPreload__("js/Main.B-Oq671r.js"),window.__aioseoDynamicImportPreload__("js/Index.B1EysQKR.js"),window.__aioseoDynamicImportPreload__("js/preload-helper.BW7egqpS.js"),window.__aioseoDynamicImportPreload__("css/Index.BFKgrYhJ.css")])))=>i.map(i=>d[i]);
import{H as e,R as t,b as n,c as r,n as i,t as a,w as o}from"./js/_plugin-vue_export-helper.D5TAAMQM.js";import{a as s,n as c,r as l,s as u,t as d}from"./js/preload-helper.BW7egqpS.js";var f={},p={class:`table-of-contents-plus-app`};function m(r,i){let a=e(`router-view`);return t(),n(`div`,p,[o(a)])}var h=a(f,[[`render`,m]]),g=[{path:`/:pathMatch(.*)*`,redirect:`/about-us`},{path:`/about-us`,name:`about-us`,component:(e=>()=>c(Object.assign({"../views/AboutUs.vue":()=>d(()=>import(`./js/AboutUs.B7-4Dk3Z.js`),__vite__mapDeps([0,1,2,3,4]),import.meta.url),"../views/Main.vue":()=>d(()=>import(`./js/Main.B-Oq671r.js`),__vite__mapDeps([5,1,0,2,3,4,6,7,8]),import.meta.url)}),`../views/${e}.vue`,3))(`Main`),meta:{access:`aioseo_table_of_contents_about_us_page`,name:r(`About Us`,`table-of-contents-plus`)}}],_=u(h);_=s(_);var v=l(g,_);v.app=_,_.use(v),i(_,v),_.mount(`#table-of-contents-plus-app`);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{H as e,K as t,R as n,W as r,t as i,v as a}from"./_plugin-vue_export-helper.D5TAAMQM.js";import o from"./AboutUs.B7-4Dk3Z.js";import{t as s}from"./Index.B1EysQKR.js";var c={components:{AboutUs:o,CoreMain:s}};function l(i,o,s,c,l,u){let d=e(`core-main`);return n(),a(d,{showSaveButton:!1},{default:t(()=>[(n(),a(r(i.$route.name)))]),_:1})}var u=i(c,[[`render`,l]]);export{u as default};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=[window.__aioseoDynamicImportPreload__("js/Settings.I0t6Uaq_.js"),window.__aioseoDynamicImportPreload__("js/_plugin-vue_export-helper.D5TAAMQM.js"),window.__aioseoDynamicImportPreload__("js/preload-helper.BW7egqpS.js"),window.__aioseoDynamicImportPreload__("js/translations.BwNKZNiM.js"),window.__aioseoDynamicImportPreload__("css/translations.CoGMWdmt.css"),window.__aioseoDynamicImportPreload__("js/Index.B1EysQKR.js"),window.__aioseoDynamicImportPreload__("css/Index.BFKgrYhJ.css"),window.__aioseoDynamicImportPreload__("css/Settings.BprgNO0L.css")])))=>i.map(i=>d[i]);
import{H as e,R as t,b as n,c as r,n as i,t as a,w as o}from"./js/_plugin-vue_export-helper.D5TAAMQM.js";import{a as s,n as c,r as l,s as u,t as d}from"./js/preload-helper.BW7egqpS.js";var f={},p={class:`table-of-contents-plus-app`};function m(r,i){let a=e(`router-view`);return t(),n(`div`,p,[o(a)])}var h=a(f,[[`render`,m]]),g=`table-of-contents-plus`,_=e=>()=>c(Object.assign({"../views/Settings.vue":()=>d(()=>import(`./js/Settings.I0t6Uaq_.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)}),`../views/${e}.vue`,3),v=[{name:`display`,label:r(`Display`,g)},{name:`appearance`,label:r(`Appearance`,g)},{name:`behavior`,label:r(`Behavior`,g)},{name:`advanced`,label:r(`Advanced`,g)}],y=!!(window.aioseoTableOfContents&&window.aioseoTableOfContents.isBrokenLinkCheckerActive),b=[{path:`/:pathMatch(.*)*`,redirect:`/display`},...v.map(e=>({path:`/${e.name}`,name:e.name,component:_(`Settings`),meta:{access:`aioseo_table_of_contents_settings_page`,name:e.label}})),...y?[]:[{path:`/broken-link-checker`,name:`broken-link-checker`,component:_(`Settings`),meta:{access:`aioseo_table_of_contents_settings_page`,name:r(`Broken Link Checker`,g),hideSaveButton:!0}}]],x=u(h);x=s(x);var S=l(b,x);S.app=x,x.use(S),i(x,S),x.mount(`#table-of-contents-plus-app`);
@@ -0,0 +1,20 @@
<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M155.389 26.5151C160.077 25.1197 165.062 25.1197 169.749 26.5151C188.868 32.2066 212.116 39.3939 229.621 45.0774C237.998 47.7974 242.816 57.8341 242.816 69.3301C242.816 135.762 230.134 194.654 166.462 229.539C164.05 230.861 161.089 230.861 158.676 229.539C95.0036 194.654 82.3203 135.762 82.3203 69.3301C82.3204 57.834 87.1401 47.7973 95.5175 45.0774C113.023 39.3939 136.271 32.2066 155.389 26.5151Z" fill="url(#paint0_linear_370_4049)"/>
<path d="M92.9722 188.675C95.9556 194.157 94.1282 200.456 89.3854 203.099C84.6426 205.742 78.6419 204.357 75.65 199.266C54.911 163.27 46.1818 120.381 46.8958 79.0302C47.5503 66.8248 65.612 66.7568 66.1814 79.1322C66.4874 118.409 73.3551 154.43 92.9807 188.684L92.9722 188.675Z" fill="url(#paint1_linear_370_4049)"/>
<path d="M28.802 182.19C18.849 154.881 12.6952 131.668 13.2052 103.127C13.2477 100.908 13.9617 98.7155 15.4151 97.041C20.8889 90.7258 33.0943 93.9982 33.0943 104.266C34.1398 129.161 38.4066 152.025 47.5266 175.237C51.496 186.627 33.6298 194.149 28.802 182.19Z" fill="url(#paint2_linear_370_4049)"/>
<path d="M151.139 160.637C148.246 160.637 145.498 159.376 143.615 157.186L120.044 131.506C116.467 127.353 116.935 121.081 121.098 117.504C125.252 113.927 131.523 114.405 135.1 118.559L151.148 135.48L193.659 89.0496C197.236 84.8958 203.498 84.4183 207.661 87.9954C211.815 91.5725 212.292 97.8347 208.715 101.998L158.68 157.186C156.797 159.376 154.049 160.646 151.157 160.646L151.139 160.637Z" fill="white"/>
<defs>
<linearGradient id="paint0_linear_370_4049" x1="162.568" y1="24.3912" x2="162.568" y2="231.609" gradientUnits="userSpaceOnUse">
<stop offset="0.480769" stop-color="#10B981"/>
<stop offset="1" stop-color="#008A5C"/>
</linearGradient>
<linearGradient id="paint1_linear_370_4049" x1="70.6388" y1="69.8634" x2="70.6388" y2="204.411" gradientUnits="userSpaceOnUse">
<stop offset="0.480769" stop-color="#10B981"/>
<stop offset="1" stop-color="#008A5C"/>
</linearGradient>
<linearGradient id="paint2_linear_370_4049" x1="30.6366" y1="93.8218" x2="30.6366" y2="188.26" gradientUnits="userSpaceOnUse">
<stop offset="0.480769" stop-color="#10B981"/>
<stop offset="1" stop-color="#008A5C"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

@@ -0,0 +1,3 @@
<svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M40.0005 66.6666C54.7279 66.6666 66.6668 54.7277 66.6668 40.0003C66.6668 25.2729 54.7279 13.334 40.0005 13.334C25.2731 13.334 13.3342 25.2729 13.3342 40.0003C13.3342 54.7277 25.2731 66.6666 40.0005 66.6666ZM35.7544 23.0938C35.3932 22.5433 34.724 22.2859 34.1105 22.5026C33.4116 22.7495 32.7281 23.0399 32.0639 23.3719C31.4809 23.6635 31.1884 24.3293 31.3168 24.9788L31.774 27.2927C31.8917 27.8882 31.6487 28.4927 31.1873 28.8767C30.458 29.4835 29.7848 30.1697 29.1817 30.9291C28.8068 31.4011 28.2153 31.6513 27.6312 31.5333L25.3629 31.0751C24.7257 30.9463 24.0739 31.2475 23.7905 31.8439C23.6304 32.1809 23.4793 32.5249 23.3375 32.8757C23.1958 33.2266 23.0655 33.5794 22.9465 33.9336C22.7358 34.5605 22.9903 35.2429 23.5313 35.6097L25.4573 36.9154C25.9532 37.2516 26.2002 37.8545 26.1403 38.459C26.0439 39.4315 26.0478 40.4024 26.1462 41.3573C26.2085 41.9615 25.9635 42.5652 25.4688 42.9032L23.5465 44.2164C23.007 44.5849 22.7547 45.2677 22.9671 45.8937C23.2091 46.6069 23.4937 47.3044 23.8191 47.9821C24.1048 48.577 24.7574 48.8755 25.3938 48.7445L27.6615 48.278C28.2451 48.1579 28.8375 48.4059 29.2138 48.8767C29.8085 49.6207 30.4809 50.3077 31.2251 50.9231C31.6877 51.3057 31.9329 51.9093 31.8172 52.5053L31.3682 54.8199C31.242 55.4701 31.5372 56.1352 32.1216 56.4244C32.4519 56.5878 32.789 56.742 33.1328 56.8866C33.4767 57.0312 33.8224 57.1641 34.1695 57.2856C35.1851 57.641 36.6065 56.3688 37.6573 55.4281C38.1755 54.9643 38.4952 54.3079 38.4986 53.605C38.4986 53.6013 38.4986 53.5975 38.4986 53.5937L38.4986 49.7232C38.4986 49.6822 38.5002 49.6415 38.5033 49.6013C35.3994 48.8441 33.0918 45.9948 33.0918 42.5955V38.4856C33.0918 38.1732 33.3399 37.9199 33.6461 37.9199H35.5686V33.8762C35.5686 33.3178 36.0121 32.8652 36.5593 32.8652C37.1064 32.8652 37.55 33.3178 37.55 33.8762V37.9199H42.7513V33.8762C42.7513 33.3178 43.1949 32.8652 43.742 32.8652C44.2892 32.8652 44.7328 33.3178 44.7328 33.8762V37.9199H46.6553C46.9614 37.9199 47.2096 38.1732 47.2096 38.4856V42.5955C47.2096 46.1023 44.7538 49.0237 41.5014 49.6668C41.5021 49.6855 41.5024 49.7043 41.5024 49.7232L41.5024 53.5771C41.5024 54.2935 41.8316 54.9619 42.3654 55.4274C43.4349 56.3602 44.8809 57.6212 45.8905 57.2645C46.5894 57.0176 47.2729 56.7273 47.9371 56.3952C48.5201 56.1037 48.8126 55.4378 48.6842 54.7884L48.227 52.4744C48.1093 51.8788 48.3523 51.2744 48.8137 50.8904C49.5429 50.2835 50.2161 49.5974 50.8193 48.838C51.1942 48.366 51.7857 48.1158 52.3698 48.2338L54.6381 48.6921C55.2753 48.8208 55.9271 48.5196 56.2105 47.9232C56.3706 47.5862 56.5217 47.2423 56.6634 46.8914C56.8051 46.5405 56.9355 46.1878 57.0545 45.8336C57.2652 45.2066 57.0107 44.5242 56.4697 44.1574L54.5436 42.8517C54.0477 42.5155 53.8007 41.9126 53.8606 41.3082C53.957 40.3356 53.9531 39.3647 53.8547 38.4098C53.7925 37.8056 54.0374 37.202 54.5322 36.864L56.4545 35.5508C56.994 35.1822 57.2462 34.4994 57.0338 33.8734C56.7919 33.1602 56.5073 32.4627 56.1819 31.785C55.8962 31.1901 55.2436 30.8917 54.6072 31.0226L52.3396 31.4892C51.7559 31.6093 51.1635 31.3613 50.7872 30.8905C50.1925 30.1464 49.5201 29.4594 48.7759 28.844C48.3133 28.4614 48.0681 27.8578 48.1838 27.2618L48.6328 24.9472C48.759 24.297 48.4638 23.6319 47.8793 23.3428C47.5491 23.1794 47.212 23.0252 46.8682 22.8806C46.5243 22.736 46.1786 22.603 45.8315 22.4815C45.2171 22.2665 44.5484 22.5262 44.1889 23.0783L42.9093 25.0436C42.5798 25.5496 41.989 25.8016 41.3966 25.7405C40.4435 25.6421 39.492 25.6461 38.5562 25.7465C37.9641 25.8101 37.3725 25.5601 37.0413 25.0553L35.7544 23.0938Z" fill="#005AE0"/>
</svg>

After

Width:  |  Height:  |  Size: 3.6 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.9 KiB

@@ -0,0 +1,12 @@
<svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_5838_38071)">
<path d="M66.6659 40.0009C66.6659 54.7344 54.723 66.6659 40.0009 66.6659C25.2789 66.6659 13.3359 54.7344 13.3359 40.0009C13.3359 25.2674 25.2789 13.3359 40.0009 13.3359C54.723 13.3359 66.6659 25.2674 66.6659 40.0009Z" fill="#F99E36"/>
<path d="M50.4777 26.0538C48.468 23.8145 46.4354 22.9302 44.7473 23.5388C44.4258 23.6767 44.1272 23.8489 43.8631 24.0786L38.9825 28.1782L26.2127 38.9154L23.4681 41.2236C22.5495 42.0045 22.2049 43.2792 22.6184 44.4161L23.1696 45.909L23.7208 47.4018C24.1342 48.5387 25.2251 49.2966 26.4309 49.2966L53.0615 49.2852C53.4175 49.2852 54.095 49.1014 54.095 49.1014C55.7831 48.4928 56.7592 46.4946 56.8511 43.4974C56.9429 40.8102 56.3228 37.5259 55.1285 34.2416C53.9228 30.9573 52.2691 28.0519 50.4777 26.0538ZM49.6738 39.2485L47.7331 33.9315C49.203 33.3918 50.8222 34.1497 51.3619 35.6196C51.9016 37.0895 51.1437 38.7202 49.6738 39.2485ZM44.5521 24.7446C44.5177 24.7791 44.4717 24.802 44.4373 24.8365C42.4276 26.5246 42.4506 32.1171 44.6325 38.0771C46.1598 42.2801 48.3991 45.6563 50.5006 47.2755L26.4194 47.287C26.0635 47.287 25.7304 47.0573 25.6041 46.7243L25.0529 45.2314L42.9903 38.6858V38.6743C40.7281 32.4846 41.4515 26.4672 44.5521 24.7446Z" fill="white"/>
<path d="M45.3663 49.0662C45.2056 51.8567 42.8974 53.8204 40.0609 53.8548C40.0379 53.8548 40.0264 53.8548 40.0035 53.8548C37.1555 53.8548 34.8014 51.8797 34.6406 49.0547H36.6732C36.8799 50.7083 38.2924 51.8682 40.0035 51.8682H40.0379C41.7031 51.8682 43.0811 50.6624 43.3223 49.0662" fill="white"/>
</g>
<defs>
<clipPath id="clip0_5838_38071">
<rect width="80" height="80" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.8 KiB

@@ -0,0 +1,12 @@
<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_60_1563)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.80567 97.1853C11.9117 97.1853 15.2404 100.514 15.2404 104.62V199.594C15.2404 222.534 33.8368 241.131 56.7767 241.131H153.977C158.083 241.131 161.412 244.459 161.412 248.565C161.412 252.671 158.083 256 153.977 256H56.7767C25.6247 256 0.370972 230.746 0.370972 199.594V104.62C0.370972 100.514 3.6996 97.1853 7.80567 97.1853Z" fill="#F78442"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M178.805 0H178.463V62.3268C178.463 70.5226 185.106 77.1665 193.302 77.1665H255.629V76.8242L178.805 0Z" fill="#F78442"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M160.655 69.7466V0L59.7447 3.05176e-05C43.3532 3.05176e-05 30.0653 13.288 30.0653 29.6795V195.884C30.0653 212.276 43.3533 225.564 59.7448 225.564H225.95C242.341 225.564 255.629 212.276 255.629 195.884L255.629 94.9741H185.882C171.95 94.9741 160.655 83.6794 160.655 69.7466ZM61.4499 43.1689C57.6571 43.1689 54.5823 46.2436 54.5823 50.0365C54.5823 53.8293 57.6571 56.9041 61.4499 56.9041H128.877C132.67 56.9041 135.744 53.8293 135.744 50.0365C135.744 46.2436 132.67 43.1689 128.877 43.1689H61.4499ZM61.4499 81.8771C57.6571 81.8771 54.5823 84.9518 54.5823 88.7447C54.5823 92.5375 57.6571 95.6122 61.4499 95.6122H128.877C132.67 95.6122 135.744 92.5375 135.744 88.7447C135.744 84.9518 132.67 81.8771 128.877 81.8771H61.4499ZM170.448 182.15V138.781H199.634V146.341H179.768V156.675H197.697V164.235H179.768V182.15H170.448ZM126.352 182.15H141.978C146.455 182.15 150.3 181.282 153.514 179.545C156.743 177.809 159.218 175.317 160.94 172.07C162.676 168.823 163.544 164.941 163.544 160.423C163.544 155.92 162.676 152.052 160.94 148.819C159.218 145.586 156.757 143.108 153.557 141.386C150.358 139.649 146.541 138.781 142.107 138.781H126.352V182.15ZM141.59 174.294H135.671V146.637H141.612C144.367 146.637 146.684 147.117 148.564 148.077C150.444 149.037 151.857 150.534 152.804 152.567C153.766 154.6 154.246 157.219 154.246 160.423C154.246 163.656 153.766 166.296 152.804 168.343C151.857 170.376 150.437 171.88 148.542 172.854C146.663 173.814 144.345 174.294 141.59 174.294ZM87.1091 182.15V138.781H104.5C107.843 138.781 110.692 139.409 113.045 140.666C115.398 141.908 117.192 143.638 118.426 145.854C119.674 148.056 120.298 150.597 120.298 153.477C120.298 156.357 119.667 158.899 118.404 161.101C117.142 163.303 115.312 165.019 112.916 166.247C110.534 167.475 107.65 168.089 104.263 168.089H96.4288V182.15H87.1091ZM96.4288 146.278V160.741H102.757C104.55 160.741 106.028 160.437 107.191 159.83C108.367 159.209 109.242 158.355 109.816 157.268C110.405 156.167 110.699 154.903 110.699 153.477C110.699 152.037 110.405 150.781 109.816 149.708C109.242 148.621 108.367 147.781 107.191 147.188C106.014 146.581 104.522 146.278 102.714 146.278H96.4288Z" fill="#2A2D4C"/>
</g>
<defs>
<clipPath id="clip0_60_1563">
<rect width="256" height="256" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,10 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="128" height="128" transform="translate(128 5.59506e-06) rotate(90)" fill="url(#paint0_linear_2818_6236)"/>
<path d="M106.668 70.5313C106.668 70.7714 106.682 70.9973 106.696 71.2374C106.908 74.2183 107.289 97.9103 68.1133 113.832C66.7995 114.355 65.4148 114.609 64.0303 114.609C62.6461 114.624 61.2478 114.369 59.9483 113.832C20.7724 97.9103 21.1534 74.2183 21.3653 71.2374C21.3935 70.9973 21.3936 70.7714 21.3936 70.5313L21.1954 38.3057C21.1672 33.9828 23.7246 30.0409 27.6944 28.2891L59.5948 14.2745C61.0074 13.653 62.5189 13.3566 64.0303 13.3565C65.5419 13.3565 67.0541 13.6529 68.4669 14.2745L100.353 28.2891C104.322 30.0409 106.88 33.9686 106.852 38.3057L106.668 70.5313ZM41.6465 89.3262C42.0588 89.1716 42.0588 88.5912 41.6465 88.4366L39.9327 87.8057C39.8041 87.7542 39.701 87.6512 39.6495 87.5225L39.0186 85.8087C38.864 85.3966 38.2847 85.3967 38.1299 85.8087L37.4981 87.5225C37.4465 87.6512 37.3436 87.7542 37.2149 87.8057L35.501 88.4366C35.0891 88.5913 35.0891 89.1716 35.501 89.3262L37.2149 89.9571C37.3436 90.0086 37.4466 90.1116 37.4981 90.2403L38.1299 91.9542C38.2847 92.3659 38.864 92.3661 39.0186 91.9542L39.6495 90.2403C39.701 90.1116 39.804 90.0087 39.9327 89.9571L41.6465 89.3262ZM50.0665 74.1407C51.024 73.1831 51.0894 71.6477 50.2237 70.6114C45.4753 64.971 42.3268 59.2651 41.0938 54.3331C39.9001 57.232 39.2315 60.4065 39.2315 63.7383C39.2315 69.6803 41.3299 75.137 44.8057 79.4131L50.0665 74.1407ZM62.9083 61.2462C65.7546 58.3866 65.4002 53.6119 62.0948 51.2901L62.1075 51.2901C54.7622 46.1484 48.6236 45.0068 46.6426 46.9346L46.5899 46.9874C44.3337 49.3222 46.157 57.3763 53.6075 66.5059C54.5913 67.6996 56.4016 67.7783 57.4903 66.6895L62.9083 61.2462ZM72.7198 86.9952C67.9845 85.5916 62.5673 82.4436 57.2549 77.7872C56.2187 76.8821 54.6573 76.9474 53.6866 77.918L53.7003 77.9317L48.5313 83.1124C52.7813 86.536 58.186 88.5831 64.0626 88.5831C67.1057 88.5831 70.0176 88.0052 72.7198 86.9952ZM79.6729 44.4298C75.4098 40.9799 69.9922 38.9073 64.0762 38.9073C60.2461 38.9073 56.6257 39.799 53.3858 41.3467C58.3704 42.5273 64.1946 45.7811 69.9268 50.7657C70.9631 51.6705 72.5236 51.6044 73.4942 50.6339L79.6729 44.4298ZM80.709 81.6827C82.9781 79.3344 81.1288 71.2279 73.5997 62.046C72.6159 60.8523 70.8056 60.7742 69.7169 61.876L69.7032 61.876L61.1251 70.4942C60.0496 71.5697 60.1146 73.3531 61.2686 74.337C70.2801 82.0368 78.3213 84.0046 80.6563 81.7354L80.709 81.6827ZM88.9063 63.751C88.9062 57.8353 86.8336 52.4178 83.3838 48.1417L77.1407 54.4122C76.1831 55.3697 76.1173 56.9042 76.9962 57.9405L76.9835 57.9532C81.9286 63.7903 85.1421 69.7195 86.3096 74.7696C87.9623 71.451 88.9063 67.7123 88.9063 63.751ZM95.2637 38.4796C95.9963 38.2044 95.9962 37.1746 95.2637 36.8995L92.2159 35.7764C91.9869 35.6848 91.8036 35.5015 91.712 35.2725L90.5899 32.2257C90.315 31.4925 89.2838 31.4925 89.0088 32.2257L87.8858 35.2725C87.7941 35.5015 87.6109 35.6848 87.3819 35.7764L84.335 36.8995C83.6019 37.1744 83.6019 38.2046 84.335 38.4796L87.3819 39.6026C87.611 39.6942 87.7941 39.8775 87.8858 40.1065L89.0088 43.1534C89.2838 43.8865 90.315 43.8865 90.5899 43.1534L91.712 40.1065C91.8036 39.8775 91.9869 39.6943 92.2159 39.6026L95.2637 38.4796Z" fill="white"/>
<defs>
<linearGradient id="paint0_linear_2818_6236" x1="19.1359" y1="8.68687e-07" x2="88.2553" y2="138.3" gradientUnits="userSpaceOnUse">
<stop offset="0.159115" stop-color="#9718E7"/>
<stop offset="1" stop-color="#5A2ED4"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

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