PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / trunk
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO vtrunk
2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.10.0 1.11.0 1.12.0 All 46 releases
thinkrank / thinkrank.php

thinkrank.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO trunk, at thinkrank.php

545 lines 17.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Plugin Name: ThinkRank
5 * Plugin URI: https://thinkrank.ai/
6 * Description: AI-native SEO plugin for WordPress. Automate and enhance your SEO with cutting-edge AI while maintaining editorial control.
7 * Version: 2.5.0
8 * Author: WPDeveloper
9 * Author URI: https://wpdeveloper.com/
10 * License: GPL v2 or later
11 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
12 * Text Domain: thinkrank
13 * Domain Path: /languages
14 * Requires at least: 6.0
15 * Requires PHP: 7.4
16 *
17 * @package ThinkRank
18 * @version 2.5.0
19 * @since 1.0.0
20 */
21
22 declare(strict_types=1);
23
24 // Prevent direct access
25 if (!defined('ABSPATH')) {
26 exit;
27 }
28
29 // Define plugin constants
30 define('THINKRANK_VERSION', '2.5.0');
31 define('THINKRANK_PLUGIN_FILE', __FILE__);
32 define('THINKRANK_PLUGIN_DIR', plugin_dir_path(__FILE__));
33 define('THINKRANK_PLUGIN_URL', plugin_dir_url(__FILE__));
34 define('THINKRANK_PLUGIN_BASENAME', plugin_basename(__FILE__));
35
36 // Minimum requirements check
37 if (version_compare(PHP_VERSION, '7.4', '<')) {
38 add_action('admin_notices', function () {
39 echo '<div class="notice notice-error"><p>';
40 echo esc_html__('ThinkRank requires PHP 7.4 or higher. Please upgrade your PHP version.', 'thinkrank');
41 echo '</p></div>';
42 });
43 return;
44 }
45
46 if (version_compare(get_bloginfo('version'), '6.0', '<')) {
47 add_action('admin_notices', function () {
48 echo '<div class="notice notice-error"><p>';
49 echo esc_html__('ThinkRank requires WordPress 6.0 or higher. Please upgrade your WordPress installation.', 'thinkrank');
50 echo '</p></div>';
51 });
52 return;
53 }
54
55 // Autoloader
56 require_once THINKRANK_PLUGIN_DIR . 'includes/class-autoloader.php';
57
58 /**
59 * Bundled AI Building Blocks (Abilities API + MCP Adapter).
60 *
61 * Loaded through the Jetpack Autoloader so that if the same libraries are also
62 * shipped by another plugin — or land in WordPress core — the newest copy wins
63 * and loads once, with no fatal class collisions. This lets ThinkRank serve its
64 * MCP endpoint out of the box, without requiring the standalone MCP Adapter and
65 * Abilities API plugins. See docs/mcp-server.md for the update procedure.
66 */
67 $thinkrank_mcp_runtime = THINKRANK_PLUGIN_DIR . 'dependencies/vendor/autoload_packages.php';
68 if (is_readable($thinkrank_mcp_runtime)) {
69 require_once $thinkrank_mcp_runtime;
70 }
71 unset($thinkrank_mcp_runtime);
72
73 /**
74 * Main ThinkRank Plugin Class
75 *
76 * Follows Single Responsibility Principle - only handles plugin initialization
77 *
78 * @since 1.0.0
79 */
80 final class ThinkRank {
81
82 /**
83 * Plugin instance (Singleton Pattern)
84 *
85 * @var ThinkRank|null
86 */
87 private static ?ThinkRank $instance = null;
88
89 /**
90 * Plugin components
91 *
92 * @var array
93 */
94 private array $components = [];
95
96 /**
97 * Get plugin instance (Singleton Pattern)
98 *
99 * @return ThinkRank
100 */
101 public static function get_instance(): ThinkRank {
102 if (null === self::$instance) {
103 self::$instance = new self();
104 }
105 return self::$instance;
106 }
107
108 /**
109 * Private constructor to prevent direct instantiation
110 */
111 private function __construct() {
112 $this->init_autoloader();
113 $this->init_hooks();
114 }
115
116 /**
117 * Prevent cloning
118 */
119 private function __clone() {
120 }
121
122 /**
123 * Prevent unserialization
124 *
125 * @throws \Exception On failure.
126 */
127 public function __wakeup() {
128 throw new \Exception('Cannot unserialize singleton');
129 }
130
131 /**
132 * Initialize autoloader
133 *
134 * @return void
135 */
136 private function init_autoloader(): void {
137 ThinkRank\Core\Autoloader::register();
138 }
139
140 /**
141 * Initialize WordPress hooks
142 *
143 * @return void
144 */
145 private function init_hooks(): void {
146 register_activation_hook(__FILE__, [$this, 'activate']);
147 register_deactivation_hook(__FILE__, [$this, 'deactivate']);
148
149 add_action('plugins_loaded', [$this, 'init']);
150 add_filter('plugin_action_links_' . THINKRANK_PLUGIN_BASENAME, [$this, 'add_action_links']);
151 }
152
153 /**
154 * Add a "Dashboard" link to the plugin action links on the Plugins page.
155 *
156 * @param array $links Existing plugin action links.
157 * @return array
158 */
159 public function add_action_links(array $links): array {
160 $dashboard_link = sprintf(
161 '<a href="%s">%s</a>',
162 esc_url(admin_url('admin.php?page=thinkrank')),
163 esc_html__('Dashboard', 'thinkrank')
164 );
165
166 array_unshift($links, $dashboard_link);
167
168 return $links;
169 }
170
171 /**
172 * Initialize plugin components
173 *
174 * @return void
175 */
176 public function init(): void {
177 try {
178 $this->maybe_update_database();
179 $this->register_sitemap_cron_listeners();
180 $this->register_brand_visibility_cron();
181 $this->load_components();
182 $this->init_components();
183 $this->load_template_functions();
184
185 do_action('thinkrank_loaded');
186 } catch (\Exception $e) {
187 $this->handle_error($e);
188 }
189 }
190
191 /**
192 * Register the sitemap regeneration WP-Cron listeners.
193 *
194 * Runs on plugins_loaded (via init()), so the callbacks exist on every
195 * request — including WP-Cron, which never fires rest_api_init and therefore
196 * never builds the Sitemap REST endpoint (whose constructor would otherwise
197 * be the only place the scheduled regeneration hooks get a listener). The
198 * generator is built lazily inside the callback so this stays cheap on the
199 * vast majority of requests where no regeneration is due.
200 *
201 * @return void
202 */
203 private function register_sitemap_cron_listeners(): void {
204 add_action('thinkrank_regenerate_sitemap', static function () {
205 (new ThinkRank\SEO\Sitemap_Generator())->auto_regenerate_sitemap();
206 });
207 add_action('thinkrank_regenerate_sitemap_settings', static function () {
208 (new ThinkRank\SEO\Sitemap_Generator())->regenerate_sitemap_from_settings();
209 });
210
211 add_action('shutdown', [$this, 'maybe_take_over_sitemap_regeneration'], 100);
212 }
213
214 /**
215 * Rebuild the sitemap in-request when WP-Cron has not delivered.
216 *
217 * WP-Cron only runs when a request arrives, so with DISABLE_WP_CRON set, a
218 * host blocking loopback requests, or very little traffic, the scheduled
219 * regeneration never fires and the sitemap silently stops updating (#629).
220 * Once the event is overdue by the generator's grace period, an admin, REST
221 * or WP-CLI request takes the work over so the site converges on its own.
222 *
223 * Front-end requests are deliberately excluded: this runs on `shutdown`,
224 * after the response, but generation on a large site is not free and a
225 * visitor should never pay for it. Admin traffic is what a site with broken
226 * cron reliably still has — the sitemap goes stale right after someone
227 * publishes something, and that someone is in wp-admin.
228 *
229 * @since 2.2.1
230 * @return void
231 */
232 public function maybe_take_over_sitemap_regeneration(): void {
233 // is_admin() is true for admin-ajax.php and REST_REQUEST for public
234 // core routes, both of which anonymous front-end traffic reaches — so
235 // without the logged-in test a visitor could still pay for the rebuild
236 // this method documents as never being theirs to pay for. WP-CLI has no
237 // user, and is trusted by definition.
238 $eligible = (defined('WP_CLI') && WP_CLI)
239 || (
240 is_user_logged_in()
241 && (
242 is_admin()
243 || (defined('REST_REQUEST') && REST_REQUEST)
244 )
245 );
246
247 if (!$eligible) {
248 return;
249 }
250
251 // Cheap autoloaded-option read, so the vast majority of requests stop
252 // here without building the generator.
253 if (!ThinkRank\SEO\Sitemap_Generator::has_overdue_regeneration()) {
254 return;
255 }
256
257 // `shutdown` runs after the output buffers are flushed, but flushed is
258 // not delivered: on FPM the connection stays open until the process
259 // ends, so without this the browser — or the REST call the sitemap
260 // screen just made — waits out the whole generation. Hand the response
261 // back first, then rebuild.
262 $this->close_request();
263
264 // Read-only construction: the auto-generation hooks are pointless this
265 // late in the request and would only add duplicate callbacks.
266 (new ThinkRank\SEO\Sitemap_Generator(false))->run_overdue_regeneration();
267 }
268
269 /**
270 * Deliver the response and let the request keep working without the client.
271 *
272 * A no-op on SAPIs that cannot do it, where the caller simply pays for the
273 * work as before.
274 *
275 * @since 2.2.1
276 * @return void
277 */
278 private function close_request(): void {
279 if (defined('WP_CLI') && WP_CLI) {
280 return;
281 }
282
283 if (function_exists('fastcgi_finish_request')) {
284 fastcgi_finish_request();
285 return;
286 }
287
288 if (function_exists('litespeed_finish_request')) {
289 litespeed_finish_request();
290 }
291 }
292
293 /**
294 * Register the Brand Visibility run-drain listener.
295 *
296 * Runs on plugins_loaded (via init()) rather than from the REST endpoint,
297 * because the ticks that drain a run are WP-Cron requests — they never
298 * reach rest_api_init, so registering the listener there would mean a run
299 * starts and then never progresses.
300 *
301 * @return void
302 */
303 private function register_brand_visibility_cron(): void {
304 add_action(ThinkRank\AI\Brand_Visibility_Runner::TICK_HOOK, static function () {
305 (new ThinkRank\AI\Brand_Visibility_Runner())->tick();
306 });
307
308 // Safety net: a tick killed by a fatal or a worker timeout never
309 // reaches its own reschedule, which would strand the run. The
310 // watchdog re-arms the drain and unschedules itself when idle.
311 add_filter('cron_schedules', [ThinkRank\AI\Brand_Visibility_Runner::class, 'add_cron_interval']); // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected
312 add_action(ThinkRank\AI\Brand_Visibility_Runner::WATCHDOG_HOOK, static function () {
313 (new ThinkRank\AI\Brand_Visibility_Runner())->watchdog();
314 });
315 }
316
317 /**
318 * Check if database schema needs updating and run migrations
319 *
320 * Standard WordPress pattern: compare stored db_version against current,
321 * run dbDelta if stale. This handles schema changes (new tables, new columns)
322 * without requiring plugin deactivation/reactivation.
323 *
324 * @since 1.10.0
325 * @return void
326 */
327 private function maybe_update_database(): void {
328 $schema = new ThinkRank\Database\Database_Schema();
329 if ($schema->needs_update()) {
330 $schema->create_tables();
331 }
332 }
333
334 /**
335 * Load plugin components (Dependency Injection Container pattern)
336 *
337 * @return void
338 */
339 private function load_components(): void {
340 $this->components = [
341 'database' => new ThinkRank\Core\Database(),
342 'settings' => new ThinkRank\Core\Settings(),
343 'role_manager' => new ThinkRank\Core\Role_Manager(),
344 'security_headers' => new ThinkRank\Core\Security_Headers(),
345 'asset_optimizer' => new ThinkRank\Core\Asset_Optimizer(),
346 'usage_tracker' => new ThinkRank\Core\Usage_Tracker_Manager(),
347 'api' => new ThinkRank\API\Manager(),
348 'admin' => new ThinkRank\Admin\Manager(),
349 'blocks' => new ThinkRank\Editor\Blocks_Manager(),
350 'elementor' => new ThinkRank\Editor\Elementor_Manager(),
351 'bricks_elements' => new ThinkRank\Editor\Bricks_Elements_Manager(),
352 'beaver_modules' => new ThinkRank\Editor\Beaver_Modules_Manager(),
353 'ai' => new ThinkRank\AI\Manager(),
354 'frontend_seo' => new ThinkRank\Frontend\SEO_Manager(),
355 'seo_notice' => new ThinkRank\Admin\SEO_Notice(),
356 'search_visibility_notice' => new ThinkRank\Admin\Search_Visibility_Notice(),
357 'performance_collector' => new ThinkRank\SEO\Performance_Data_Collector(),
358 'instant_indexing' => new ThinkRank\SEO\Instant_Indexing_Manager(),
359 'instant_indexing_reconciler' => new ThinkRank\SEO\Instant_Indexing_Reconciler(),
360 'author_archives' => new ThinkRank\SEO\Author_Archives_Manager(),
361 'seo_analyzer' => new ThinkRank\SEO\SEO_Analyzer(),
362 'email_report' => new ThinkRank\SEO\Email_Report_Manager(),
363 'google_oauth' => new ThinkRank\Integrations\Google_OAuth_Proxy(),
364 'multilingual' => new ThinkRank\Integrations\Multilingual_Manager(),
365 'ai_traffic' => new ThinkRank\SEO\Ai_Traffic_Tracker(),
366 'auto_ai' => new ThinkRank\SEO\Auto_Ai_Optimizer(),
367 'analytics' => new ThinkRank\SEO\Analytics_Manager(),
368 'abilities' => new ThinkRank\Abilities\Abilities_Registrar(),
369 'mcp' => new ThinkRank\Mcp\Mcp_Manager(),
370 ];
371 }
372
373 /**
374 * Initialize all components
375 *
376 * @return void
377 */
378 private function init_components(): void {
379 foreach ($this->components as $component) {
380 if (method_exists($component, 'init')) {
381 $component->init();
382 }
383 }
384 }
385
386 /**
387 * Load template functions for themes
388 *
389 * @return void
390 */
391 private function load_template_functions(): void {
392 require_once THINKRANK_PLUGIN_DIR . 'includes/frontend/template-functions.php';
393 }
394
395 /**
396 * Get component instance
397 *
398 * @param string $component Component name
399 * @return object|null
400 */
401 public function get_component(string $component): ?object {
402 return $this->components[$component] ?? null;
403 }
404
405 /**
406 * Shared Analytics Manager instance (lazy)
407 *
408 * @var ThinkRank\SEO\Analytics_Manager|null
409 */
410 private ?ThinkRank\SEO\Analytics_Manager $analytics_manager = null;
411
412 /**
413 * Get the shared Analytics Manager, with Google clients initialized.
414 *
415 * Consumers (including the Pro plugin, which probes for this accessor)
416 * should use this instead of constructing their own Analytics_Manager:
417 * each fresh construction re-reads/decrypts settings and re-initializes
418 * the Google API clients.
419 *
420 * @since 1.18.0
421 * @return ThinkRank\SEO\Analytics_Manager
422 */
423 public function get_analytics_manager(): ThinkRank\SEO\Analytics_Manager {
424 if ($this->analytics_manager === null) {
425 // Reuse the registered component. Constructing a second instance
426 // here would work, but only the registered one has had init() run
427 // on it, so the token-refresh cron would be scheduled against a
428 // different object than the one callers actually use.
429 $component = $this->components['analytics'] ?? null;
430
431 $this->analytics_manager = $component instanceof ThinkRank\SEO\Analytics_Manager
432 ? $component
433 : new ThinkRank\SEO\Analytics_Manager();
434
435 // init() defers initialize_clients() to the `init` hook; callers
436 // that arrive earlier still need working clients.
437 $this->analytics_manager->initialize_clients();
438 }
439 return $this->analytics_manager;
440 }
441
442 /**
443 * Plugin activation
444 *
445 * @return void
446 */
447 public function activate(): void {
448 try {
449 $activator = new ThinkRank\Core\Activator();
450 $activator->activate();
451
452 // Flush rewrite rules
453 flush_rewrite_rules();
454 } catch (\Exception $e) {
455 $this->handle_error($e);
456 wp_die(
457 esc_html__('ThinkRank activation failed. Please check your server logs.', 'thinkrank'),
458 esc_html__('Plugin Activation Error', 'thinkrank'),
459 ['back_link' => true]
460 );
461 }
462 }
463
464 /**
465 * Plugin deactivation
466 *
467 * @return void
468 */
469 public function deactivate(): void {
470 try {
471 $deactivator = new ThinkRank\Core\Deactivator();
472 $deactivator->deactivate();
473
474 // Flush rewrite rules
475 flush_rewrite_rules();
476 } catch (\Exception $e) {
477 $this->handle_error($e);
478 }
479 }
480
481 /**
482 * Handle errors consistently
483 *
484 * Logs errors and surfaces them via _doing_it_wrong() when
485 * WP_DEBUG is enabled, helping developers diagnose issues.
486 *
487 * @param \Exception $e Exception to handle
488 * @return void
489 */
490 private function handle_error(\Exception $e): void {
491 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
492 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
493 error_log('ThinkRank: ' . $e->getMessage());
494 }
495
496 if (defined('WP_DEBUG') && WP_DEBUG) {
497 _doing_it_wrong(
498 __METHOD__,
499 esc_html($e->getMessage()),
500 esc_html(THINKRANK_VERSION)
501 );
502 }
503 }
504
505 /**
506 * Get plugin version
507 *
508 * @return string
509 */
510 public function get_version(): string {
511 return THINKRANK_VERSION;
512 }
513
514 /**
515 * Get plugin directory path
516 *
517 * @return string
518 */
519 public function get_plugin_dir(): string {
520 return THINKRANK_PLUGIN_DIR;
521 }
522
523 /**
524 * Get plugin URL
525 *
526 * @return string
527 */
528 public function get_plugin_url(): string {
529 return THINKRANK_PLUGIN_URL;
530 }
531 }
532
533 /**
534 * Initialize the plugin
535 *
536 * @return ThinkRank
537 */
538 // phpcs:ignore Universal.Files.SeparateFunctionsFromOO.Mixed -- plugin bootstrap: the accessor belongs next to the class it returns.
539 function thinkrank(): ThinkRank {
540 return ThinkRank::get_instance();
541 }
542
543 // Start the plugin
544 thinkrank();
545