#\!/bin/bash
# Direct remote script creation for Zoho fixes
# This script directly creates the files on the remote server
# 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"
PLUGIN_PATH="${REMOTE_PATH}/wp-content/plugins/hvac-community-events"
echo -e "${YELLOW}=== Deploying Zoho CRM Integration Fixes ===${NC}"
echo -e "${YELLOW}Target: ${REMOTE_USER}@${REMOTE_HOST}:${PLUGIN_PATH}${NC}"
# Create a remote script to make all the changes
echo -e "${YELLOW}Creating remote script to fix Zoho integration...${NC}"
# Connect to the remote server and create the script
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "cat > $REMOTE_PATH/fix-zoho.php" << 'EOPHP'
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 in the file
$new_content = preg_replace($pattern, $replacement, $zoho_admin_content, -1, $count);
if ($count > 0) {
$patched = true;
if (file_put_contents($zoho_admin_path, $new_content)) {
echo "Updated class-zoho-admin.php successfully\n";
} else {
echo "Failed to update class-zoho-admin.php\n";
}
}
}
if (\!$patched) {
// Create a new file
echo "Creating a new class-zoho-admin.php file...\n";
$zoho_admin_content = <<<'EOT'
admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('hvac_zoho_admin_nonce'),
'testing_connection' => __('Testing connection...', 'hvac-community-events'),
'connection_success' => __('Connection successful\!', 'hvac-community-events'),
'connection_error' => __('Connection failed', 'hvac-community-events')
));
}
/**
* Render admin page
*/
public function render_admin_page() {
?>
get_client_id();
$client_secret = $zoho_auth->get_client_secret();
$refresh_token = $zoho_auth->get_refresh_token();
if (empty($client_id) || empty($client_secret) || empty($refresh_token)) {
echo '
';
_e('Zoho CRM credentials are not fully configured. Please check your zoho-config.php file and .env file.', 'hvac-community-events');
echo '
';
if (empty($client_id)) {
echo '
ZOHO_CLIENT_ID is missing or empty.
';
}
if (empty($client_secret)) {
echo '
ZOHO_CLIENT_SECRET is missing or empty.
';
}
if (empty($refresh_token)) {
echo '
ZOHO_REFRESH_TOKEN is missing or empty.
';
}
echo '
';
} else {
echo '
';
_e('Zoho CRM credentials are configured.', 'hvac-community-events');
echo '
';
}
?>
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)
));
}
}
}
// Initialize the admin class
new HVAC_Zoho_Admin();
EOT;
if (file_put_contents($zoho_admin_path, $zoho_admin_content)) {
echo "Created class-zoho-admin.php successfully\n";
} else {
echo "Failed to create class-zoho-admin.php\n";
}
}
} else {
echo "class-zoho-admin.php already patched\n";
}
// Create or update class-zoho-crm-auth.php
$zoho_auth_path = $plugin_path . '/includes/zoho/class-zoho-crm-auth.php';
echo "\nUpdating class-zoho-crm-auth.php...\n";
// Backup existing file if it exists
if (file_exists($zoho_auth_path)) {
$backup_path = $zoho_auth_path . '.bak.' . date('YmdHis');
if (copy($zoho_auth_path, $backup_path)) {
echo "Created backup at $backup_path\n";
} else {
echo "Failed to create backup of class-zoho-crm-auth.php\n";
}
}
// Create enhanced class-zoho-crm-auth.php
$zoho_auth_content = <<<'EOT'
refresh_token = defined('ZOHO_REFRESH_TOKEN') ? ZOHO_REFRESH_TOKEN : '';
$this->client_id = defined('ZOHO_CLIENT_ID') ? ZOHO_CLIENT_ID : '';
$this->client_secret = defined('ZOHO_CLIENT_SECRET') ? ZOHO_CLIENT_SECRET : '';
$this->api_base_url = defined('ZOHO_API_BASE_URL') ? ZOHO_API_BASE_URL : '';
}
/**
* Get access token
*
* @return string
*/
public function get_access_token() {
// If we already have an access token, return it
if (\!empty($this->access_token)) {
return $this->access_token;
}
// If we don't have credentials, return false
if (empty($this->refresh_token) || empty($this->client_id) || empty($this->client_secret)) {
// Log error
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$log_message = "[" . date('Y-m-d H:i:s') . "] Missing credentials for token generation\n";
$log_message .= "[" . date('Y-m-d H:i:s') . "] Refresh token: " . (\!empty($this->refresh_token) ? 'Present' : 'Missing') . "\n";
$log_message .= "[" . date('Y-m-d H:i:s') . "] Client ID: " . (\!empty($this->client_id) ? 'Present' : 'Missing') . "\n";
$log_message .= "[" . date('Y-m-d H:i:s') . "] Client Secret: " . (\!empty($this->client_secret) ? 'Present' : 'Missing') . "\n";
if (defined('ZOHO_LOG_FILE')) {
error_log($log_message, 3, ZOHO_LOG_FILE);
}
}
return array(
'error' => 'Missing credentials',
'code' => 'missing_credentials',
'details' => 'Refresh token, client ID, or client secret is missing'
);
}
// Get access token using refresh token
$accounts_url = defined('ZOHO_ACCOUNTS_URL') ? ZOHO_ACCOUNTS_URL : 'https://accounts.zoho.com';
$token_url = $accounts_url . '/oauth/v2/token';
$token_url .= '?refresh_token=' . urlencode($this->refresh_token);
$token_url .= '&client_id=' . urlencode($this->client_id);
$token_url .= '&client_secret=' . urlencode($this->client_secret);
$token_url .= '&grant_type=refresh_token';
$args = array(
'method' => 'POST',
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(),
'cookies' => array()
);
// Log token request
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$log_message = "[" . date('Y-m-d H:i:s') . "] Requesting access token\n";
$log_message .= "[" . date('Y-m-d H:i:s') . "] URL: " . $token_url . "\n";
if (defined('ZOHO_LOG_FILE')) {
error_log($log_message, 3, ZOHO_LOG_FILE);
}
}
$response = wp_remote_post($token_url, $args);
// Log response
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$log_message = "[" . date('Y-m-d H:i:s') . "] Token response code: " . wp_remote_retrieve_response_code($response) . "\n";
if (is_wp_error($response)) {
$log_message .= "[" . date('Y-m-d H:i:s') . "] Token error: " . $response->get_error_message() . "\n";
} else {
$log_message .= "[" . date('Y-m-d H:i:s') . "] Token response: " . wp_remote_retrieve_body($response) . "\n";
}
if (defined('ZOHO_LOG_FILE')) {
error_log($log_message, 3, ZOHO_LOG_FILE);
}
}
// Check for errors
if (is_wp_error($response)) {
return array(
'error' => $response->get_error_message(),
'code' => 'wp_error'
);
}
// Parse response
$body = json_decode(wp_remote_retrieve_body($response), true);
// Check for errors in response
if (isset($body['error'])) {
return array(
'error' => isset($body['error']) ? $body['error'] : 'Unknown error',
'code' => isset($body['error']) ? $body['error'] : 'unknown_error',
'details' => isset($body['error_description']) ? $body['error_description'] : ''
);
}
// Set access token and return it
if (isset($body['access_token'])) {
$this->access_token = $body['access_token'];
return $this->access_token;
}
// If we get here, something went wrong
return array(
'error' => 'Failed to get access token',
'code' => 'no_access_token',
'details' => 'Response did not contain an access token',
'raw_response' => $body
);
}
/**
* Make API request
*
* @param string $endpoint API endpoint
* @param string $method HTTP method
* @param array $data Request data
* @return array|WP_Error
*/
public function make_api_request($endpoint, $method = 'GET', $data = array()) {
// Enhanced error logging
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$log_message = "[" . date('Y-m-d H:i:s') . "] API Request: $method $endpoint\n";
$log_message .= "[" . date('Y-m-d H:i:s') . "] Data: " . json_encode($data) . "\n";
if (defined('ZOHO_LOG_FILE')) {
error_log($log_message, 3, ZOHO_LOG_FILE);
}
}
// Get access token
$access_token = $this->get_access_token();
// Check for errors
if (is_array($access_token) && isset($access_token['error'])) {
return $access_token;
}
// Build URL
$url = $this->api_base_url . '/' . ltrim($endpoint, '/');
// Build args
$args = array(
'method' => $method,
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(
'Authorization' => 'Zoho-oauthtoken ' . $access_token,
'Content-Type' => 'application/json'
),
'body' => '',
'cookies' => array()
);
// Add data to request
if (\!empty($data)) {
if ($method == 'GET') {
$url = add_query_arg($data, $url);
} else {
$args['body'] = json_encode($data);
}
}
// Make request
$response = wp_remote_request($url, $args);
// Enhanced error logging
if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
$log_message = "[" . date('Y-m-d H:i:s') . "] API Response Code: " . wp_remote_retrieve_response_code($response) . "\n";
if (is_wp_error($response)) {
$log_message .= "[" . date('Y-m-d H:i:s') . "] API Error: " . $response->get_error_message() . "\n";
} else {
$response_body = wp_remote_retrieve_body($response);
$log_message .= "[" . date('Y-m-d H:i:s') . "] API Response Body: " . substr($response_body, 0, 1000) . (strlen($response_body) > 1000 ? '...' : '') . "\n";
}
if (defined('ZOHO_LOG_FILE')) {
error_log($log_message, 3, ZOHO_LOG_FILE);
}
}
// Check for errors
if (is_wp_error($response)) {
return array(
'error' => $response->get_error_message(),
'code' => 'wp_error'
);
}
// Parse response
$body = json_decode(wp_remote_retrieve_body($response), true);
// Check response code
$response_code = wp_remote_retrieve_response_code($response);
if ($response_code < 200 || $response_code >= 300) {
return array(
'error' => isset($body['message']) ? $body['message'] : 'API error',
'code' => isset($body['code']) ? $body['code'] : $response_code,
'details' => isset($body['details']) ? $body['details'] : 'Response code: ' . $response_code
);
}
return $body;
}
/**
* Get modules
*
* @return array
*/
public function get_modules() {
return $this->make_api_request('settings/modules');
}
/**
* Get records from a module
*
* @param string $module Module name
* @param array $params Query parameters
* @return array
*/
public function get_records($module, $params = array()) {
return $this->make_api_request($module, 'GET', $params);
}
/**
* 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;
}
}
EOT;
if (file_put_contents($zoho_auth_path, $zoho_auth_content)) {
echo "Created class-zoho-crm-auth.php successfully\n";
} else {
echo "Failed to create class-zoho-crm-auth.php\n";
}
// Create zoho-admin.js file
$zoho_js_path = $plugin_path . '/assets/js/zoho-admin.js';
echo "\nCreating zoho-admin.js...\n";
$zoho_js_content = <<<'EOT'
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('' + hvac_zoho_admin.testing_connection + '
');
$.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 = '';
successHtml += '
' + response.data.message + '
';
if (response.data.modules) {
successHtml += '
' + response.data.modules + '
';
}
successHtml += '
';
$result.html(successHtml);
} else {
$result.html('Connection test failed. Please check the logs.
');
}
},
error: function(response) {
$button.prop('disabled', false);
$result.empty();
// Create detailed error display
var errorHtml = '';
errorHtml += '
' + response.data.message + ': ' + response.data.error + '
';
// Add error code if available
if (response.data.code) {
errorHtml += '
Error Code: ' + response.data.code + '
';
}
// Add debugging info
errorHtml += '
';
// Add details if available
if (response.data.details) {
errorHtml += '
Details: ' + response.data.details + '
';
}
// Add raw response data if available
if (response.data.raw) {
errorHtml += '
';
errorHtml += 'Raw Response Data (click to expand) ';
errorHtml += '' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + ' ';
errorHtml += ' ';
}
errorHtml += '
'; // Close debug info div
errorHtml += '
'; // Close notice div
$result.html(errorHtml);
}
});
});
});
EOT;
if (file_put_contents($zoho_js_path, $zoho_js_content)) {
echo "Created zoho-admin.js successfully\n";
} else {
echo "Failed to create zoho-admin.js\n";
}
// Create zoho-admin.css file
$zoho_css_path = $plugin_path . '/assets/css/zoho-admin.css';
echo "\nCreating zoho-admin.css...\n";
$zoho_css_content = <<<'EOT'
/* Zoho Admin Styles */
.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;
}
EOT;
if (file_put_contents($zoho_css_path, $zoho_css_content)) {
echo "Created zoho-admin.css successfully\n";
} else {
echo "Failed to create zoho-admin.css\n";
}
echo "\n==========================================\n";
echo "Zoho CRM Integration Fix Completed\n";
echo "==========================================\n\n";
echo "The following files were updated:\n";
echo "- " . $zoho_config_path . "\n";
echo "- " . $zoho_admin_path . "\n";
echo "- " . $zoho_auth_path . "\n";
echo "- " . $zoho_js_path . "\n";
echo "- " . $zoho_css_path . "\n";
echo "- " . $diagnostics_path . "\n";
echo "\nYou can now test the connection in the WordPress admin panel:\n";
echo "Go to Events > Zoho CRM Sync\n";
echo "\nIf issues persist, check the logs at:\n";
echo $plugin_path . "/includes/logs/zoho-debug.log\n";
echo "\nOr run the diagnostic tool at:\n";
echo "https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true\n";
// Exit successfully
exit();
EOPHP
# Execute the script on the remote server
echo -e "${YELLOW}Running remote script to fix Zoho integration...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "php $REMOTE_PATH/fix-zoho.php?run_fix=true"
# Cleanup
echo -e "${YELLOW}Cleaning up...${NC}"
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "rm -f $REMOTE_PATH/fix-zoho.php"
echo -e "${GREEN}=== Zoho CRM integration fixes deployed successfully\! ===${NC}"
echo -e "${YELLOW}You can now test the connection in the WordPress admin panel.${NC}"
echo -e "${YELLOW}Go to Events > Zoho CRM Sync${NC}"
echo -e "${YELLOW}If issues persist, check the logs at: ${PLUGIN_PATH}/includes/logs/zoho-debug.log${NC}"
echo -e "${YELLOW}Or run the diagnostic tool at: https://wordpress-974670-5399585.cloudwaysapps.com/wp-content/plugins/hvac-community-events/includes/zoho/diagnostics.php?run_diagnostics=true${NC}"
exit 0