upskill-event-manager/wordpress-dev/bin/deploy-zoho-fix.sh

787 lines
30 KiB
Bash
Executable file

#\!/bin/bash
# Zoho CRM Integration Fix Deployment Script
# This script runs the cleanup and then deploys the Zoho fix
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Load environment variables
source "$(dirname "$0")/../.env"
# Check if environment variables are loaded
if [ -z "$UPSKILL_STAGING_IP" ] || [ -z "$UPSKILL_STAGING_SSH_USER" ]; then
echo -e "${RED}Error: Missing required environment variables${NC}"
echo "Please ensure .env file exists and contains UPSKILL_STAGING_IP and UPSKILL_STAGING_SSH_USER"
exit 1
fi
# Set variables
REMOTE_HOST="${UPSKILL_STAGING_IP}"
REMOTE_USER="${UPSKILL_STAGING_SSH_USER}"
REMOTE_PASS="${UPSKILL_STAGING_PASS}"
REMOTE_PATH="/home/974670.cloudwaysapps.com/uberrxmprk/public_html"
PLUGINS_PATH="${REMOTE_PATH}/wp-content/plugins"
MAIN_PLUGIN="hvac-community-events"
echo -e "${YELLOW}=== Zoho CRM Integration Fix Deployment ===${NC}"
echo -e "${YELLOW}Target: ${REMOTE_USER}@${REMOTE_HOST}:${PLUGINS_PATH}/${MAIN_PLUGIN}${NC}"
# Step 1: Run the cleanup script first
echo -e "${YELLOW}Step 1: Running plugin cleanup...${NC}"
"$(dirname "$0")/cleanup-hvac-plugins.sh"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Plugin cleanup failed. Aborting deployment.${NC}"
exit 1
fi
echo -e "${GREEN}Plugin cleanup completed successfully.${NC}"
# Step 2: Create directories for Zoho files
echo -e "${YELLOW}Step 2: Creating required directories...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" <<EOSSH
mkdir -p $PLUGINS_PATH/$MAIN_PLUGIN/includes/zoho
mkdir -p $PLUGINS_PATH/$MAIN_PLUGIN/includes/admin
mkdir -p $PLUGINS_PATH/$MAIN_PLUGIN/includes/logs
mkdir -p $PLUGINS_PATH/$MAIN_PLUGIN/assets/js
mkdir -p $PLUGINS_PATH/$MAIN_PLUGIN/assets/css
chmod -R 755 $PLUGINS_PATH/$MAIN_PLUGIN/includes/logs
EOSSH
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to create required directories. Aborting deployment.${NC}"
exit 1
fi
echo -e "${GREEN}Required directories created successfully.${NC}"
# Step 3: Create and upload Zoho config file
echo -e "${YELLOW}Step 3: Creating and uploading Zoho config file...${NC}"
ZOHO_CONFIG=$(mktemp)
cat > "$ZOHO_CONFIG" << 'EOPHP'
<?php
/**
* Zoho CRM Configuration
*
* This file contains the necessary constants for Zoho CRM integration.
* Enhanced with environment variable loading and debugging.
*/
// Load environment variables from .env file
function load_env_from_dotenv() {
// Look for .env file in plugin directory and up to 3 levels up
$search_dirs = [
dirname(dirname(dirname(__FILE__))), // Plugin directory
dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins
dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // WordPress root
];
foreach ($search_dirs as $dir) {
$env_file = $dir . '/.env';
if (file_exists($env_file)) {
$lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos($line, '=') \!== false && strpos($line, '#') \!== 0) {
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
// Remove quotes if present
if (strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value) - 1) {
$value = substr($value, 1, -1);
} elseif (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value) - 1) {
$value = substr($value, 1, -1);
}
putenv("$name=$value");
$_ENV[$name] = $value;
}
}
return true;
}
}
return false;
}
// Try to load environment variables
$env_loaded = load_env_from_dotenv();
// Hard-code Zoho credentials for staging if not found in environment
if (\!getenv('ZOHO_CLIENT_ID')) {
putenv('ZOHO_CLIENT_ID=1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS');
$_ENV['ZOHO_CLIENT_ID'] = '1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS';
}
if (\!getenv('ZOHO_CLIENT_SECRET')) {
putenv('ZOHO_CLIENT_SECRET=36913615664649dbf9198884bfd1096f7573c9ce2b');
$_ENV['ZOHO_CLIENT_SECRET'] = '36913615664649dbf9198884bfd1096f7573c9ce2b';
}
// Log directory setup
$log_dir = dirname(dirname(__FILE__)) . '/logs';
if (\!file_exists($log_dir)) {
mkdir($log_dir, 0755, true);
}
// OAuth Client Credentials
define('ZOHO_CLIENT_ID', getenv('ZOHO_CLIENT_ID') ?: '1000.Z0HOF1VMMJ9W2QWSU57GVQYEAVUSKS');
define('ZOHO_CLIENT_SECRET', getenv('ZOHO_CLIENT_SECRET') ?: '36913615664649dbf9198884bfd1096f7573c9ce2b');
define('ZOHO_REDIRECT_URI', 'https://wordpress-974670-5399585.cloudwaysapps.com/oauth/callback');
// API Endpoints
define('ZOHO_ACCOUNTS_URL', 'https://accounts.zoho.com');
define('ZOHO_API_BASE_URL', 'https://www.zohoapis.com/crm/v2');
// Scopes
define('ZOHO_SCOPES', 'ZohoCRM.settings.all,ZohoCRM.modules.all,ZohoCRM.users.all,ZohoCRM.org.all');
// Optional - Refresh Token (if already obtained)
define('ZOHO_REFRESH_TOKEN', getenv('ZOHO_REFRESH_TOKEN') ?: '');
// Debug Settings - Enhanced for better logging
define('ZOHO_DEBUG_MODE', true);
define('ZOHO_LOG_FILE', $log_dir . '/zoho-debug.log');
// Add diagnostic information to log
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$timestamp = date('Y-m-d H:i:s');
$debug_info = "[$timestamp] Zoho CRM Configuration loaded\n";
$debug_info .= "[$timestamp] .env file loaded: " . ($env_loaded ? 'Yes' : 'No') . "\n";
$debug_info .= "[$timestamp] Client ID exists: " . (\!empty(ZOHO_CLIENT_ID) ? 'Yes' : 'No') . "\n";
$debug_info .= "[$timestamp] Client ID value: " . (ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
$debug_info .= "[$timestamp] Client Secret exists: " . (\!empty(ZOHO_CLIENT_SECRET) ? 'Yes' : 'No') . "\n";
$debug_info .= "[$timestamp] Client Secret value: " . (ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
$debug_info .= "[$timestamp] Refresh Token exists: " . (\!empty(ZOHO_REFRESH_TOKEN) ? 'Yes' : 'No') . "\n";
$debug_info .= "[$timestamp] Refresh Token value: " . (ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'EMPTY') . "\n";
$debug_info .= "[$timestamp] Log file path: " . ZOHO_LOG_FILE . "\n";
if (function_exists('get_site_url')) {
$debug_info .= "[$timestamp] WordPress site URL: " . get_site_url() . "\n";
$debug_info .= "[$timestamp] Staging mode: " . (strpos(get_site_url(), 'upskillhvac.com') === false ? 'Yes' : 'No') . "\n";
} else {
$debug_info .= "[$timestamp] WordPress functions not available\n";
}
// Check for environment variables directly
$debug_info .= "[$timestamp] Environment variables:\n";
$debug_info .= "[$timestamp] - _ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? 'Set' : 'Not set') . "\n";
$debug_info .= "[$timestamp] - _ENV['ZOHO_CLIENT_SECRET']: " . (isset($_ENV['ZOHO_CLIENT_SECRET']) ? 'Set' : 'Not set') . "\n";
$debug_info .= "[$timestamp] - _ENV['ZOHO_REFRESH_TOKEN']: " . (isset($_ENV['ZOHO_REFRESH_TOKEN']) ? 'Set' : 'Not set') . "\n";
// Log configuration details
error_log($debug_info, 3, ZOHO_LOG_FILE);
}
EOPHP
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$ZOHO_CONFIG" "$REMOTE_USER@$REMOTE_HOST:$PLUGINS_PATH/$MAIN_PLUGIN/includes/zoho/zoho-config.php"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to upload Zoho config file. Aborting deployment.${NC}"
rm "$ZOHO_CONFIG"
exit 1
fi
rm "$ZOHO_CONFIG"
echo -e "${GREEN}Zoho config file uploaded successfully.${NC}"
# Step 4: Create and upload diagnostics file
echo -e "${YELLOW}Step 4: Creating and uploading diagnostics file...${NC}"
DIAGNOSTICS_FILE=$(mktemp)
cat > "$DIAGNOSTICS_FILE" << 'EOPHP'
<?php
/**
* Zoho CRM Integration Diagnostics
*
* This file provides diagnostic tools for troubleshooting Zoho CRM integration issues.
* Access via URL with security parameter: ?run_diagnostics=true
*/
// Security check - only run diagnostics when explicitly requested
if (\!isset($_GET['run_diagnostics']) || $_GET['run_diagnostics'] \!== 'true') {
die('Diagnostics not enabled. Add ?run_diagnostics=true to the URL to run diagnostics.');
}
// Set headers for plain text output
header('Content-Type: text/plain');
echo "==========================================\n";
echo "HVAC Community Events - Zoho CRM Diagnostics\n";
echo "==========================================\n";
echo "Timestamp: " . date('Y-m-d H:i:s') . "\n\n";
// Find the WordPress installation
function find_wordpress_root() {
$dir = __DIR__;
while ($dir \!== '/' && \!file_exists($dir . '/wp-config.php')) {
$dir = dirname($dir);
}
return file_exists($dir . '/wp-config.php') ? $dir : false;
}
// Try to bootstrap WordPress
$wp_root = find_wordpress_root();
if ($wp_root) {
echo "WordPress installation found at: $wp_root\n";
// Try to bootstrap WordPress
if (file_exists($wp_root . '/wp-load.php')) {
echo "Loading WordPress...\n";
require_once $wp_root . '/wp-load.php';
echo "WordPress loaded successfully.\n";
} else {
echo "Error: wp-load.php not found\!\n";
}
} else {
echo "Error: WordPress installation not found\!\n";
}
echo "\n";
echo "==========================================\n";
echo "Environment Information\n";
echo "==========================================\n";
// PHP Version
echo "PHP Version: " . phpversion() . "\n";
// WordPress Version (if available)
if (function_exists('get_bloginfo')) {
echo "WordPress Version: " . get_bloginfo('version') . "\n";
}
// Server Information
echo "Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "\n";
echo "Request URI: " . $_SERVER['REQUEST_URI'] . "\n";
echo "\n";
echo "==========================================\n";
echo "Plugin Information\n";
echo "==========================================\n";
// Plugin Path
$plugin_dir = dirname(dirname(dirname(__FILE__)));
echo "Plugin Directory: $plugin_dir\n";
// Check if plugin is active
if (function_exists('is_plugin_active')) {
echo "Plugin Active: " . (is_plugin_active('hvac-community-events/hvac-community-events.php') ? 'Yes' : 'No') . "\n";
}
echo "\n";
echo "==========================================\n";
echo "Zoho CRM Configuration\n";
echo "==========================================\n";
// Check if Zoho config file exists
$zoho_config_path = $plugin_dir . '/includes/zoho/zoho-config.php';
if (file_exists($zoho_config_path)) {
echo "Zoho Config File: Found\n";
// Include the config file
require_once $zoho_config_path;
// Check for required constants
echo "ZOHO_CLIENT_ID defined: " . (defined('ZOHO_CLIENT_ID') ? 'Yes' : 'No') . "\n";
echo "ZOHO_CLIENT_ID value: " . (defined('ZOHO_CLIENT_ID') && ZOHO_CLIENT_ID ? substr(ZOHO_CLIENT_ID, 0, 5) . '...' : 'EMPTY') . "\n";
echo "ZOHO_CLIENT_SECRET defined: " . (defined('ZOHO_CLIENT_SECRET') ? 'Yes' : 'No') . "\n";
echo "ZOHO_CLIENT_SECRET value: " . (defined('ZOHO_CLIENT_SECRET') && ZOHO_CLIENT_SECRET ? substr(ZOHO_CLIENT_SECRET, 0, 5) . '...' : 'EMPTY') . "\n";
echo "ZOHO_REFRESH_TOKEN defined: " . (defined('ZOHO_REFRESH_TOKEN') ? 'Yes' : 'No') . "\n";
echo "ZOHO_REFRESH_TOKEN value: " . (defined('ZOHO_REFRESH_TOKEN') && ZOHO_REFRESH_TOKEN ? substr(ZOHO_REFRESH_TOKEN, 0, 5) . '...' : 'EMPTY') . "\n";
echo "ZOHO_REDIRECT_URI defined: " . (defined('ZOHO_REDIRECT_URI') ? 'Yes' : 'No') . "\n";
echo "ZOHO_REDIRECT_URI value: " . (defined('ZOHO_REDIRECT_URI') ? ZOHO_REDIRECT_URI : 'UNDEFINED') . "\n";
echo "ZOHO_DEBUG_MODE defined: " . (defined('ZOHO_DEBUG_MODE') ? 'Yes' : 'No') . "\n";
echo "ZOHO_DEBUG_MODE value: " . (defined('ZOHO_DEBUG_MODE') ? (ZOHO_DEBUG_MODE ? 'true' : 'false') : 'UNDEFINED') . "\n";
echo "ZOHO_LOG_FILE defined: " . (defined('ZOHO_LOG_FILE') ? 'Yes' : 'No') . "\n";
echo "ZOHO_LOG_FILE value: " . (defined('ZOHO_LOG_FILE') ? ZOHO_LOG_FILE : 'UNDEFINED') . "\n";
echo "ZOHO_LOG_FILE exists: " . (defined('ZOHO_LOG_FILE') && file_exists(ZOHO_LOG_FILE) ? 'Yes' : 'No') . "\n";
echo "ZOHO_LOG_FILE writable: " . (defined('ZOHO_LOG_FILE') && is_writable(dirname(ZOHO_LOG_FILE)) ? 'Yes' : 'No') . "\n";
} else {
echo "Zoho Config File: Not Found\! Expected at $zoho_config_path\n";
}
echo "\n";
echo "==========================================\n";
echo "Environment Variables\n";
echo "==========================================\n";
// Check for environment variables
echo "ZOHO_CLIENT_ID environment variable: " . (getenv('ZOHO_CLIENT_ID') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_CLIENT_SECRET environment variable: " . (getenv('ZOHO_CLIENT_SECRET') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_REFRESH_TOKEN environment variable: " . (getenv('ZOHO_REFRESH_TOKEN') ? 'Set' : 'Not Set') . "\n";
// Check for _ENV array variables
echo "_ENV['ZOHO_CLIENT_ID']: " . (isset($_ENV['ZOHO_CLIENT_ID']) ? 'Set' : 'Not Set') . "\n";
echo "_ENV['ZOHO_CLIENT_SECRET']: " . (isset($_ENV['ZOHO_CLIENT_SECRET']) ? 'Set' : 'Not Set') . "\n";
echo "_ENV['ZOHO_REFRESH_TOKEN']: " . (isset($_ENV['ZOHO_REFRESH_TOKEN']) ? 'Set' : 'Not Set') . "\n";
// Check .env file
$env_file_paths = [
$plugin_dir . '/.env',
dirname($plugin_dir) . '/.env',
dirname(dirname($plugin_dir)) . '/.env',
dirname(dirname(dirname($plugin_dir))) . '/.env',
];
foreach ($env_file_paths as $env_path) {
echo "\nChecking for .env file at: $env_path\n";
if (file_exists($env_path)) {
echo ".env file exists: Yes\n";
echo ".env file readable: " . (is_readable($env_path) ? 'Yes' : 'No') . "\n";
if (is_readable($env_path)) {
$env_contents = file_get_contents($env_path);
echo "ZOHO_CLIENT_ID in .env: " . (strpos($env_contents, 'ZOHO_CLIENT_ID') \!== false ? 'Yes' : 'No') . "\n";
echo "ZOHO_CLIENT_SECRET in .env: " . (strpos($env_contents, 'ZOHO_CLIENT_SECRET') \!== false ? 'Yes' : 'No') . "\n";
echo "ZOHO_REFRESH_TOKEN in .env: " . (strpos($env_contents, 'ZOHO_REFRESH_TOKEN') \!== false ? 'Yes' : 'No') . "\n";
}
// Try to load .env file
if (function_exists('load_env_from_dotenv')) {
echo "Loading .env file with load_env_from_dotenv()...\n";
$result = load_env_from_dotenv();
echo "Result: " . ($result ? 'Success' : 'Failed') . "\n";
// Check variables after loading
echo "ZOHO_CLIENT_ID after loading: " . (getenv('ZOHO_CLIENT_ID') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_CLIENT_SECRET after loading: " . (getenv('ZOHO_CLIENT_SECRET') ? 'Set' : 'Not Set') . "\n";
echo "ZOHO_REFRESH_TOKEN after loading: " . (getenv('ZOHO_REFRESH_TOKEN') ? 'Set' : 'Not Set') . "\n";
} else {
echo "load_env_from_dotenv() function not available\!\n";
}
break;
} else {
echo ".env file exists: No\n";
}
}
echo "\n";
echo "==========================================\n";
echo "Log File Contents (if available)\n";
echo "==========================================\n";
if (defined('ZOHO_LOG_FILE') && file_exists(ZOHO_LOG_FILE) && is_readable(ZOHO_LOG_FILE)) {
echo "Log file found at: " . ZOHO_LOG_FILE . "\n";
echo "Log file size: " . filesize(ZOHO_LOG_FILE) . " bytes\n";
echo "Last 50 lines of log file:\n";
$log_lines = file(ZOHO_LOG_FILE);
$last_lines = array_slice($log_lines, -50);
echo "-------------------------\n";
foreach ($last_lines as $line) {
echo $line;
}
echo "-------------------------\n";
} else {
echo "Log file not found or not readable.\n";
}
echo "\n";
echo "==========================================\n";
echo "Diagnostics completed at " . date('Y-m-d H:i:s') . "\n";
echo "==========================================\n";
// Exit to prevent any further output
exit();
EOPHP
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$DIAGNOSTICS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGINS_PATH/$MAIN_PLUGIN/includes/zoho/diagnostics.php"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to upload diagnostics file. Aborting deployment.${NC}"
rm "$DIAGNOSTICS_FILE"
exit 1
fi
rm "$DIAGNOSTICS_FILE"
echo -e "${GREEN}Diagnostics file uploaded successfully.${NC}"
# Step 5: Create and upload CSS file
echo -e "${YELLOW}Step 5: Creating and uploading CSS file...${NC}"
CSS_FILE=$(mktemp)
cat > "$CSS_FILE" << 'EOCSS'
/* Debug Information Styling */
.hvac-zoho-debug-info {
margin-top: 15px;
padding: 15px;
background: #f9f9f9;
border: 1px solid #ddd;
border-left: 4px solid #dc3232;
}
.hvac-zoho-debug-info details summary {
cursor: pointer;
font-weight: bold;
color: #0073aa;
padding: 5px;
background: #f0f0f0;
}
.hvac-zoho-debug-info pre {
margin: 10px 0;
padding: 10px;
background: #f0f0f0;
border: 1px solid #ddd;
overflow: auto;
max-height: 300px;
}
EOCSS
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$CSS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGINS_PATH/$MAIN_PLUGIN/assets/css/zoho-admin.css"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to upload CSS file. Aborting deployment.${NC}"
rm "$CSS_FILE"
exit 1
fi
rm "$CSS_FILE"
echo -e "${GREEN}CSS file uploaded successfully.${NC}"
# Step 6: Update class-zoho-admin.php if it exists
echo -e "${YELLOW}Step 6: Updating admin class if it exists...${NC}"
# Create a PHP script to update the admin class
UPDATE_ADMIN_SCRIPT=$(mktemp)
cat > "$UPDATE_ADMIN_SCRIPT" << 'EOPHP'
<?php
// Get admin class file path
$admin_path = __DIR__ . '/wp-content/plugins/hvac-community-events/includes/admin/class-zoho-admin.php';
// Check if file exists
if (\!file_exists($admin_path)) {
echo "Admin class file not found at $admin_path. Skipping update.\n";
exit(0);
}
// Create backup
$backup_path = $admin_path . '.bak.' . date('YmdHis');
if (\!copy($admin_path, $backup_path)) {
echo "Failed to create backup of admin class. Aborting update.\n";
exit(1);
}
// Read file content
$content = file_get_contents($admin_path);
// Check if already patched
if (strpos($content, 'ZOHO_DEBUG_MODE') \!== false) {
echo "Admin class already patched with enhanced error reporting. Skipping update.\n";
exit(0);
}
// Find test_connection method
$pattern = '/public function test_connection\(\) {(.*?)}/s';
if (preg_match($pattern, $content, $matches)) {
// Create replacement
$replacement = "public function test_connection() {
// Enable debug logging
if (\!defined('ZOHO_DEBUG_MODE')) {
define('ZOHO_DEBUG_MODE', true);
}
// Create a temporary log file if needed
if (\!defined('ZOHO_LOG_FILE')) {
\$log_dir = HVAC_CE_PLUGIN_DIR . 'includes/logs';
if (\!file_exists(\$log_dir)) {
mkdir(\$log_dir, 0755, true);
}
define('ZOHO_LOG_FILE', \$log_dir . '/zoho-debug.log');
}
// Log the request
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
\$log_message = \"[\" . date('Y-m-d H:i:s') . \"] Testing Zoho CRM connection\\n\";
if (defined('ZOHO_LOG_FILE')) {
error_log(\$log_message, 3, ZOHO_LOG_FILE);
}
}
// Check nonce for security
check_ajax_referer('hvac_zoho_admin_nonce', 'nonce');
// Get Zoho CRM Auth instance
\$zoho_auth = HVAC_Zoho_CRM_Auth::get_instance();
// Test the connection
\$response = \$zoho_auth->get_modules();
// Enhanced error handling and detailed response
if (\$response && \!isset(\$response['error'])) {
wp_send_json_success(array(
'message' => 'Connection successful\!',
'modules' => isset(\$response['modules']) ? count(\$response['modules']) . ' modules available' : 'No modules found'
));
} else {
\$error_message = isset(\$response['error']) ? \$response['error'] : 'Unknown error';
\$error_code = isset(\$response['code']) ? \$response['code'] : '';
\$error_details = isset(\$response['details']) ? \$response['details'] : '';
// Log the error
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
\$log_message = \"[\" . date('Y-m-d H:i:s') . \"] Connection test failed: \$error_message\\n\";
\$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Error code: \$error_code\\n\";
\$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Details: \$error_details\\n\";
\$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Raw response: \" . json_encode(\$response) . \"\\n\";
if (defined('ZOHO_LOG_FILE')) {
error_log(\$log_message, 3, ZOHO_LOG_FILE);
}
}
// Send detailed error data back to frontend
wp_send_json_error(array(
'message' => 'Connection failed',
'error' => \$error_message,
'code' => \$error_code,
'details' => \$error_details,
'raw' => json_encode(\$response)
));
}
}";
// Replace the method
$content = preg_replace($pattern, $replacement, $content);
// Save the updated file
if (file_put_contents($admin_path, $content)) {
echo "Admin class updated successfully with enhanced error reporting.\n";
} else {
echo "Failed to update admin class.\n";
exit(1);
}
} else {
echo "Could not find test_connection method in admin class. Manual update may be required.\n";
}
EOPHP
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$UPDATE_ADMIN_SCRIPT" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/update-admin-class.php"
ADMIN_UPDATE_RESULT=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php update-admin-class.php")
echo "$ADMIN_UPDATE_RESULT"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/update-admin-class.php"
rm "$UPDATE_ADMIN_SCRIPT"
# Step 7: Update class-zoho-crm-auth.php if it exists
echo -e "${YELLOW}Step 7: Updating auth class if it exists...${NC}"
# Create a PHP script to update the auth class
UPDATE_AUTH_SCRIPT=$(mktemp)
cat > "$UPDATE_AUTH_SCRIPT" << 'EOPHP'
<?php
// Get auth class file path
$auth_path = __DIR__ . '/wp-content/plugins/hvac-community-events/includes/zoho/class-zoho-crm-auth.php';
// Check if file exists
if (\!file_exists($auth_path)) {
echo "Auth class file not found at $auth_path. Skipping update.\n";
exit(0);
}
// Create backup
$backup_path = $auth_path . '.bak.' . date('YmdHis');
if (\!copy($auth_path, $backup_path)) {
echo "Failed to create backup of auth class. Aborting update.\n";
exit(1);
}
// Read file content
$content = file_get_contents($auth_path);
// Check if already patched
if (strpos($content, 'load_env_from_dotenv') \!== false) {
echo "Auth class already patched with environment loading. Skipping update.\n";
exit(0);
}
// Add getter methods at the end of the class if not present
if (strpos($content, 'get_client_id') === false) {
// Find the end of the class
$pattern = '/}(\s*)$/';
$replacement = "
/**
* Get client ID
*
* @return string
*/
public function get_client_id() {
return \$this->client_id;
}
/**
* Get client secret
*
* @return string
*/
public function get_client_secret() {
return \$this->client_secret;
}
/**
* Get refresh token
*
* @return string
*/
public function get_refresh_token() {
return \$this->refresh_token;
}
}\$1";
$content = preg_replace($pattern, $replacement, $content);
}
// Find constructor to add environment loading
$pattern = '/public function __construct\(\) {/';
$replacement = "public function __construct() {
// Load environment variables from .env if available
if (function_exists('load_env_from_dotenv')) {
load_env_from_dotenv();
}";
$content = preg_replace($pattern, $replacement, $content);
// Save the updated file
if (file_put_contents($auth_path, $content)) {
echo "Auth class updated successfully to load environment variables.\n";
} else {
echo "Failed to update auth class.\n";
exit(1);
}
EOPHP
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$UPDATE_AUTH_SCRIPT" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/update-auth-class.php"
AUTH_UPDATE_RESULT=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php update-auth-class.php")
echo "$AUTH_UPDATE_RESULT"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/update-auth-class.php"
rm "$UPDATE_AUTH_SCRIPT"
# Step 8: Create and upload JS file
echo -e "${YELLOW}Step 8: Creating and uploading JS file...${NC}"
JS_FILE=$(mktemp)
cat > "$JS_FILE" << 'EOJS'
jQuery(document).ready(function($) {
$('#hvac-zoho-test-connection').on('click', function(e) {
e.preventDefault();
var $button = $(this);
var $result = $('#hvac-zoho-test-connection-result');
$button.prop('disabled', true);
$result.html('<div class="notice notice-info"><p>Testing connection...</p></div>');
$.ajax({
url: hvac_zoho_admin.ajax_url,
type: 'POST',
data: {
action: 'hvac_zoho_test_connection',
nonce: hvac_zoho_admin.nonce
},
success: function(response) {
$button.prop('disabled', false);
$result.empty();
if (response.success) {
var successHtml = '<div class="notice notice-success">';
successHtml += '<p><strong>' + response.data.message + '</strong></p>';
if (response.data.modules) {
successHtml += '<p>' + response.data.modules + '</p>';
}
successHtml += '</div>';
$result.html(successHtml);
} else {
$result.html('<div class="notice notice-error"><p>Connection test failed. Please check the logs.</p></div>');
}
},
error: function(response) {
$button.prop('disabled', false);
$result.empty();
// Create detailed error display
var errorHtml = '<div class="notice notice-error">';
errorHtml += '<p><strong>' + (response.data ? response.data.message : 'Connection failed') + ':</strong> ' +
(response.data ? response.data.error : 'Unknown error') + '</p>';
// Add error code if available
if (response.data && response.data.code) {
errorHtml += '<p><strong>Error Code:</strong> ' + response.data.code + '</p>';
}
// Add debugging info
errorHtml += '<div class="hvac-zoho-debug-info">';
// Add details if available
if (response.data && response.data.details) {
errorHtml += '<p><strong>Details:</strong> ' + response.data.details + '</p>';
}
// Add raw response data if available
if (response.data && response.data.raw) {
try {
errorHtml += '<details>';
errorHtml += '<summary>Raw Response Data (click to expand)</summary>';
errorHtml += '<pre>' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + '</pre>';
errorHtml += '</details>';
} catch (e) {
errorHtml += '<p>Raw response data is available but could not be parsed: ' + e.message + '</p>';
}
}
errorHtml += '</div>'; // Close debug info div
errorHtml += '</div>'; // Close notice div
$result.html(errorHtml);
}
});
});
});
EOJS
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no "$JS_FILE" "$REMOTE_USER@$REMOTE_HOST:$PLUGINS_PATH/$MAIN_PLUGIN/assets/js/zoho-admin.js"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to upload JS file. Aborting deployment.${NC}"
rm "$JS_FILE"
exit 1
fi
rm "$JS_FILE"
echo -e "${GREEN}JS file uploaded successfully.${NC}"
# Step 9: Clear WordPress cache
echo -e "${YELLOW}Step 9: Clearing WordPress cache...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && wp cache flush"
# Summary
echo -e "${GREEN}=== Zoho CRM Integration Fix Deployed Successfully\! ===${NC}"
echo -e "${YELLOW}The following steps were completed:${NC}"
echo -e "1. Cleaned up duplicate HVAC plugins"
echo -e "2. Created required directories"
echo -e "3. Added environment variable loading in zoho-config.php"
echo -e "4. Enhanced error reporting in class-zoho-admin.php"
echo -e "5. Added getter methods in class-zoho-crm-auth.php"
echo -e "6. Created a diagnostics tool for troubleshooting"
echo -e "7. Added debug styling to CSS"
echo -e "8. Enhanced error display in JS"
echo -e "9. Cleared WordPress cache"
echo -e "${YELLOW}You can now test the Zoho CRM integration in the WordPress admin panel.${NC}"
echo -e "${YELLOW}Go to Events > Zoho CRM Sync and click the 'Test Connection' button.${NC}"
echo -e "${YELLOW}If issues persist, run the diagnostics tool at:${NC}"
echo -e "${YELLOW}https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true${NC}"
exit 0