File: /var/www/kevin-demo/wp-content/plugins/allspice/includes/webhook.php
<?php
// webhooks.php
if (!defined('ABSPATH')) exit;
function allspice_should_send_webhook_for_post($post): bool {
if (!$post || !isset($post->ID)) return false;
$post_id = (int)$post->ID;
if (wp_is_post_revision($post_id)) return false;
if (wp_is_post_autosave($post_id)) return false;
if (get_post_status($post_id) === 'auto-draft') return false;
$url = get_permalink($post_id);
if (!is_string($url) || $url === '') return false;
if (strpos($url, '?') !== false) return false;
return true;
}
function allspice_post_public_url($post_id): string {
$u = get_permalink($post_id);
return is_string($u) ? $u : '';
}
function allspice_send_wp_webhook(string $event, string $url): array {
$s = allspice_opt_get();
$token = trim((string)$s['webhook_token']);
if ($token === '') return array('ok' => false, 'error' => 'Missing webhook_token');
$endpoint = allspice_wp_event_endpoint();
$payload = array(
'token' => $token,
'event' => $event,
'url' => $url,
);
$resp = wp_remote_post($endpoint, array(
'timeout' => 15,
'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'),
'body' => wp_json_encode($payload),
));
if (is_wp_error($resp)) return array('ok' => false, 'error' => $resp->get_error_message());
$code = (int)wp_remote_retrieve_response_code($resp);
$body = (string)wp_remote_retrieve_body($resp);
if ($code < 200 || $code >= 300) return array('ok' => false, 'error' => 'HTTP ' . $code, 'body' => $body);
$json = json_decode($body, true);
if (!is_array($json)) $json = array();
return array('ok' => true, 'code' => $code, 'body' => $json);
}
function allspice_on_transition_post_status($new_status, $old_status, $post): void {
if (!allspice_should_send_webhook_for_post($post)) return;
$post_id = (int)$post->ID;
$url = allspice_post_public_url($post_id);
if ($url === '') return;
if ($new_status === 'publish' && $old_status === 'publish') { // published -> published (update)
allspice_send_wp_webhook('updated', $url);
return;
}
if ($new_status === 'publish' && $old_status !== 'publish') { // anything -> publish (created/published)
allspice_send_wp_webhook('created', $url);
return;
}
if ($old_status === 'publish' && $new_status !== 'publish') { // publish -> non-publish (deleted/unpublished)
allspice_send_wp_webhook('deleted', $url);
return;
}
}
add_action('transition_post_status', 'allspice_on_transition_post_status', 10, 3);
/**
* Catch hard deletes.
*/
function allspice_on_before_delete_post($post_id): void {
$post = get_post($post_id);
if (!allspice_should_send_webhook_for_post($post)) return;
$url = allspice_post_public_url($post_id);
if ($url === '') return;
allspice_send_wp_webhook('deleted', $url);
}
add_action('before_delete_post', 'allspice_on_before_delete_post', 10, 1);