';
echo esc_html__('Care Book Block Ultimate requires PHP 8.1 or higher. Please upgrade your PHP version.', 'care-book-ultimate');
echo '
';
});
return;
}
// Check if Composer autoloader exists
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
add_action('admin_notices', function() {
echo '';
echo esc_html__('Care Book Block Ultimate: Please run "composer install" to install dependencies.', 'care-book-ultimate');
echo '
';
});
return;
}
// Load Composer autoloader
require_once __DIR__ . '/vendor/autoload.php';
/**
* Main Plugin Class
*
* Implements security-first architecture with modern PHP 8.3 features
*
* @since 1.0.0
*/
final class CareBookUltimate
{
private static ?self $instance = null;
private array $services = [];
/**
* Plugin initialization
*
* @since 1.0.0
*/
private function __construct()
{
$this->initializePlugin();
}
/**
* Singleton pattern implementation
*
* @return self
* @since 1.0.0
*/
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Prevent cloning
*
* @return void
* @since 1.0.0
*/
private function __clone() {}
/**
* Prevent unserialization
*
* @return void
* @since 1.0.0
*/
public function __wakeup()
{
throw new \Exception('Cannot unserialize singleton');
}
/**
* Initialize plugin components
*
* @return void
* @since 1.0.0
*/
private function initializePlugin(): void
{
// Security check - verify WordPress environment
if (!$this->isWordPressEnvironment()) {
return;
}
// Hook into WordPress initialization
add_action('init', [$this, 'initialize']);
add_action('plugins_loaded', [$this, 'loadTextDomain']);
// Plugin lifecycle hooks
register_activation_hook(__FILE__, [$this, 'activate']);
register_deactivation_hook(__FILE__, [$this, 'deactivate']);
register_uninstall_hook(__FILE__, [self::class, 'uninstall']);
// Health monitoring hook
add_action('wp_loaded', [$this, 'performHealthCheck']);
}
/**
* Verify WordPress environment security
*
* @return bool
* @since 1.0.0
*/
private function isWordPressEnvironment(): bool
{
return defined('ABSPATH') &&
defined('WPINC') &&
function_exists('add_action') &&
function_exists('wp_verify_nonce');
}
/**
* Initialize plugin after WordPress is loaded
*
* @return void
* @since 1.0.0
*/
public function initialize(): void
{
// Check KiviCare compatibility
if (!$this->checkKiviCareCompatibility()) {
return;
}
// Initialize core components
$this->initializeCore();
$this->initializeAdmin();
$this->initializeIntegrations();
}
/**
* Check KiviCare plugin compatibility
*
* @return bool
* @since 1.0.0
*/
private function checkKiviCareCompatibility(): bool
{
if (!is_plugin_active('kivicare/kivicare.php')) {
add_action('admin_notices', function() {
echo '';
echo esc_html__('Care Book Block Ultimate requires KiviCare plugin to be installed and activated.', 'care-book-ultimate');
echo '
';
});
return false;
}
return true;
}
/**
* Initialize core components with enterprise-grade performance optimization
*
* @return void
* @since 1.0.0
*/
private function initializeCore(): void
{
// Initialize performance optimization system
$this->initializePerformanceSystem();
// Database migration
$migration = new \CareBook\Ultimate\Database\Migration();
add_action('init', [$migration, 'createTables'], 5);
do_action('care_book_ultimate_core_initialized', $this);
}
/**
* Initialize enterprise-grade performance optimization system
*
* @return void
* @since 1.0.0
*/
private function initializePerformanceSystem(): void
{
// Core performance components
$cacheManager = \CareBook\Ultimate\Cache\CacheManager::getInstance();
$memoryManager = \CareBook\Ultimate\Performance\MemoryManager::getInstance();
$queryOptimizer = new \CareBook\Ultimate\Performance\QueryOptimizer($cacheManager);
$responseOptimizer = new \CareBook\Ultimate\Performance\ResponseOptimizer($cacheManager);
// Advanced CSS injection with performance optimization
$cssInjectionService = new \CareBook\Ultimate\Services\CssInjectionService($cacheManager);
// Performance monitoring and tracking
$performanceTracker = new \CareBook\Ultimate\Monitoring\PerformanceTracker(
$cacheManager,
$queryOptimizer,
$memoryManager,
$responseOptimizer
);
// Store service instances
$this->services = [
'cache_manager' => $cacheManager,
'memory_manager' => $memoryManager,
'query_optimizer' => $queryOptimizer,
'response_optimizer' => $responseOptimizer,
'css_injection_service' => $cssInjectionService,
'performance_tracker' => $performanceTracker
];
// Start performance monitoring session
if (defined('WP_DEBUG') && WP_DEBUG) {
$sessionId = 'session_' . uniqid();
$this->services['performance_tracker']->startMonitoring($sessionId, [
'page_type' => $this->determinePageType(),
'user_role' => $this->getCurrentUserRole()
]);
}
// Register performance optimization hooks
$this->registerPerformanceHooks();
do_action('care_book_ultimate_performance_initialized', $this->services);
}
/**
* Register performance optimization hooks
*
* @return void
* @since 1.0.0
*/
private function registerPerformanceHooks(): void
{
// CSS injection optimization
add_action('wp_enqueue_scripts', [$this, 'optimizeStylesheetLoading'], 1);
add_action('wp_head', [$this, 'injectCriticalCss'], 1);
// AJAX optimization
add_action('wp_ajax_care_book_*', [$this, 'optimizeAjaxResponse'], 1);
add_action('wp_ajax_nopriv_care_book_*', [$this, 'optimizeAjaxResponse'], 1);
// Memory management
add_action('shutdown', [$this, 'performMemoryCleanup'], 999);
// Performance monitoring
add_action('wp_footer', [$this, 'recordPagePerformance'], 999);
}
/**
* Optimize stylesheet loading with critical CSS inlining
*
* @return void
* @since 1.0.0
*/
public function optimizeStylesheetLoading(): void
{
if (!$this->isKiviCarePage()) {
return;
}
$cssService = $this->services['css_injection_service'];
$restrictions = $this->getActiveRestrictions();
// Inject optimized CSS for current restrictions
$cssService->injectRestrictionCss($restrictions, [
'page_type' => $this->determinePageType(),
'critical_only' => true,
'enable_fouc_prevention' => true
]);
}
/**
* Inject critical CSS in document head
*
* @return void
* @since 1.0.0
*/
public function injectCriticalCss(): void
{
if (!$this->isKiviCarePage()) {
return;
}
$cssService = $this->services['css_injection_service'];
$restrictions = $this->getActiveRestrictions();
// Generate and inject critical CSS
$criticalCss = $cssService->generateCriticalCss($restrictions, [
'viewport_width' => 1200,
'above_fold_only' => true
]);
if (!empty($criticalCss)) {
echo "\n";
}
}
/**
* Optimize AJAX responses
*
* @return void
* @since 1.0.0
*/
public function optimizeAjaxResponse(): void
{
$responseOptimizer = $this->services['response_optimizer'];
// Start response optimization
ob_start();
// Register shutdown function to optimize response
register_shutdown_function(function() use ($responseOptimizer) {
$response = ob_get_clean();
if (!empty($response)) {
$data = json_decode($response, true);
if ($data !== null) {
$optimizedResponse = $responseOptimizer->optimizeResponse($data, [
'use_cache' => true,
'compress' => true,
'remove_nulls' => true
]);
echo json_encode($optimizedResponse);
} else {
echo $response; // Fallback for non-JSON responses
}
}
});
}
/**
* Perform memory cleanup
*
* @return void
* @since 1.0.0
*/
public function performMemoryCleanup(): void
{
$memoryManager = $this->services['memory_manager'];
// Check memory status and perform cleanup if needed
$memoryStatus = $memoryManager->checkMemoryStatus();
if ($memoryStatus['target_exceeded']) {
$memoryManager->optimizeMemoryUsage([
'clean_pools' => true,
'force_gc' => true,
'clear_caches' => false // Keep caches for performance
]);
}
}
/**
* Record page performance metrics
*
* @return void
* @since 1.0.0
*/
public function recordPagePerformance(): void
{
if (!defined('WP_DEBUG') || !WP_DEBUG) {
return;
}
$performanceTracker = $this->services['performance_tracker'];
// Record key performance metrics
$performanceTracker->recordMetric('page_load_time', $this->calculatePageLoadTime());
$performanceTracker->recordMetric('memory_usage', memory_get_usage(true));
$performanceTracker->recordMetric('memory_peak', memory_get_peak_usage(true));
// Record cache performance
$cacheMetrics = $this->services['cache_manager']->getMetrics();
$performanceTracker->recordMetric('cache_hit_ratio', $cacheMetrics['hit_rate']);
// Inject client-side performance tracking
$this->injectClientPerformanceTracking();
}
/**
* Get service instance by name
*
* @param string $serviceName Service name
* @return object|null Service instance
* @since 1.0.0
*/
public function getService(string $serviceName): ?object
{
return $this->services[$serviceName] ?? null;
}
/**
* Get performance dashboard data
*
* @return array Performance dashboard data
* @since 1.0.0
*/
public function getPerformanceDashboard(): array
{
if (!isset($this->services['performance_tracker'])) {
return ['error' => 'Performance tracking not initialized'];
}
return $this->services['performance_tracker']->getPerformanceDashboard([
'time_range' => 3600, // Last hour
'include_recommendations' => true
]);
}
/**
* Helper methods for performance optimization
*/
private function isKiviCarePage(): bool
{
return is_admin() ||
(function_exists('is_plugin_active') && is_plugin_active('kivicare/kivicare.php')) ||
strpos($_SERVER['REQUEST_URI'] ?? '', 'kivicare') !== false;
}
private function determinePageType(): string
{
if (is_admin()) {
return 'admin';
}
if (strpos($_SERVER['REQUEST_URI'] ?? '', 'appointment') !== false) {
return 'appointment_form';
}
return 'general';
}
private function getCurrentUserRole(): string
{
if (!is_user_logged_in()) {
return 'guest';
}
$user = wp_get_current_user();
return !empty($user->roles) ? $user->roles[0] : 'subscriber';
}
private function getActiveRestrictions(): array
{
// This would normally query the database for active restrictions
// Simplified for now
return [];
}
private function calculatePageLoadTime(): float
{
return (microtime(true) - ($_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true))) * 1000;
}
private function injectClientPerformanceTracking(): void
{
echo "";
}
/**
* Initialize admin components
*
* @return void
* @since 1.0.0
*/
private function initializeAdmin(): void
{
if (!is_admin()) {
return;
}
$services = $this->getServiceInstances();
// Initialize AJAX handler
$ajaxHandler = new \CareBook\Ultimate\Admin\AjaxHandler(
$services['repository'],
$services['security'],
$services['css_service']
);
// Initialize admin interface
$adminInterface = new \CareBook\Ultimate\Admin\AdminInterface(
$services['repository'],
$services['security'],
$services['css_service'],
$services['cache_manager'],
$ajaxHandler
);
$adminInterface->initialize();
do_action('care_book_ultimate_admin_initialized', $adminInterface);
}
/**
* Initialize KiviCare integrations
*
* @return void
* @since 1.0.0
*/
private function initializeIntegrations(): void
{
$services = $this->getServiceInstances();
// Initialize KiviCare hook manager
$hookManager = new \CareBook\Ultimate\Integrations\KiviCare\HookManager(
$services['repository'],
$services['security'],
$services['css_service']
);
$hookManager->initialize();
// Hook into restriction changes for cache invalidation
add_action('care_book_ultimate_restriction_created', [$hookManager, 'clearCache']);
add_action('care_book_ultimate_restriction_updated', [$hookManager, 'clearCache']);
add_action('care_book_ultimate_restriction_deleted', [$hookManager, 'clearCache']);
do_action('care_book_ultimate_integrations_initialized', $hookManager);
}
/**
* Load plugin text domain for translations
*
* @return void
* @since 1.0.0
*/
public function loadTextDomain(): void
{
load_plugin_textdomain(
'care-book-ultimate',
false,
dirname(CARE_BOOK_ULTIMATE_PLUGIN_BASENAME) . '/languages'
);
}
/**
* Plugin activation hook
*
* @return void
* @since 1.0.0
*/
public function activate(): void
{
// Security check for activation
if (!current_user_can('activate_plugins')) {
return;
}
// Check plugin requirements
if (!$this->checkSystemRequirements()) {
deactivate_plugins(CARE_BOOK_ULTIMATE_PLUGIN_BASENAME);
wp_die(
esc_html__('Care Book Block Ultimate: System requirements not met. Please check PHP version, MySQL version and required plugins.', 'care-book-ultimate'),
'Plugin Activation Error',
['back_link' => true]
);
}
// Database migration will be handled here
// Initial settings creation
// Capability registration
do_action('care_book_ultimate_activated');
// Clear any caches
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
}
/**
* Plugin deactivation hook
*
* @return void
* @since 1.0.0
*/
public function deactivate(): void
{
// Security check
if (!current_user_can('activate_plugins')) {
return;
}
// Clear caches and transients
$this->clearPluginCache();
// Remove scheduled hooks
wp_clear_scheduled_hook('care_book_ultimate_health_check');
do_action('care_book_ultimate_deactivated');
}
/**
* Plugin uninstall hook
*
* @return void
* @since 1.0.0
*/
public static function uninstall(): void
{
// Security check
if (!current_user_can('activate_plugins')) {
return;
}
// Check uninstall permission
if (!defined('WP_UNINSTALL_PLUGIN')) {
return;
}
// Database cleanup will be handled here
// Options cleanup
// Transients cleanup
do_action('care_book_ultimate_uninstalled');
}
/**
* Check system requirements
*
* @return bool
* @since 1.0.0
*/
private function checkSystemRequirements(): bool
{
global $wpdb;
// PHP version check
if (version_compare(PHP_VERSION, '8.1', '<')) {
return false;
}
// WordPress version check
if (version_compare(get_bloginfo('version'), '6.0', '<')) {
return false;
}
// MySQL version check
$mysql_version = $wpdb->db_version();
if (version_compare($mysql_version, '8.0', '<')) {
return false;
}
return true;
}
/**
* Perform health check
*
* @return void
* @since 1.0.0
*/
public function performHealthCheck(): void
{
// System health monitoring
// Integration status check
// Performance metrics collection
do_action('care_book_ultimate_health_check');
}
/**
* Clear plugin cache
*
* @return void
* @since 1.0.0
*/
private function clearPluginCache(): void
{
// Clear WordPress transients
delete_transient('care_booking_restrictions');
delete_transient('care_booking_doctors_blocked');
delete_transient('care_booking_services_blocked');
// Clear any object cache
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
}
/**
* Store service instances for dependency injection
*
* @param array $services Service instances
* @return void
* @since 1.0.0
*/
private function storeServiceInstances(array $services): void
{
$this->services = array_merge($this->services, $services);
}
/**
* Get service instances
*
* @return array Service instances
* @since 1.0.0
*/
private function getServiceInstances(): array
{
return $this->services;
}
/**
* Get specific service instance
*
* @param string $service Service name
* @return mixed Service instance or null
* @since 1.0.0
*/
public function getService(string $service): mixed
{
return $this->services[$service] ?? null;
}
}
// Initialize plugin
CareBookUltimate::getInstance();
// Action hooks for extensibility
do_action('care_book_ultimate_loaded');