| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* WebHooks Integration |
| 5 |
* |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace BitCode\BitForm\Core\Integration\WebHooks; |
| 9 |
|
| 10 |
if (!defined('ABSPATH')) { |
| 11 |
exit; |
| 12 |
} |
| 13 |
|
| 14 |
use BitCode\BitForm\Core\Integration\IntegrationHandler; |
| 15 |
use BitCode\BitForm\Core\Util\ApiResponse as UtilApiResponse; |
| 16 |
use BitCode\BitForm\Core\Util\HttpHelper; |
| 17 |
use BitCode\BitForm\Core\Util\Utilities; |
| 18 |
use BitCode\BitForm\GlobalHelper; |
| 19 |
|
| 20 |
/** |
| 21 |
* Provide functionality for webhooks |
| 22 |
*/ |
| 23 |
class WebHooksHandler |
| 24 |
{ |
| 25 |
private $formID; |
| 26 |
private $webhookID; |
| 27 |
|
| 28 |
private $_logResponse; |
| 29 |
|
| 30 |
public function __construct($webhookID, $formID) |
| 31 |
{ |
| 32 |
$this->formID = $formID; |
| 33 |
$this->webhookID = $webhookID; |
| 34 |
$this->_logResponse = new UtilApiResponse(); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Helps to register ajax function's with wp |
| 39 |
* |
| 40 |
* @return null |
| 41 |
*/ |
| 42 |
public static function registerAjax() |
| 43 |
{ |
| 44 |
add_action('wp_ajax_bitforms_test_webhook', [__CLASS__, 'testWebhook']); |
| 45 |
} |
| 46 |
|
| 47 |
public static function testWebhook() |
| 48 |
{ |
| 49 |
if (!isset($_REQUEST['_ajax_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) { |
| 50 |
wp_send_json_error(__('Token expired', 'bit-form'), 401); |
| 51 |
} |
| 52 |
|
| 53 |
GlobalHelper::requirePostMethod(); |
| 54 |
|
| 55 |
try { |
| 56 |
$webhookDetails = GlobalHelper::formatRequestData(); |
| 57 |
} catch (\InvalidArgumentException $e) { |
| 58 |
wp_send_json_error($e->getMessage(), 400); |
| 59 |
} |
| 60 |
|
| 61 |
$details = is_string($webhookDetails) ? (Utilities::jsonObj($webhookDetails)->hookDetails ?? null) : ($webhookDetails->hookDetails ?? null); |
| 62 |
|
| 63 |
$data = self::urlParserWrapper(isset($details->url) ? $details->url : ''); |
| 64 |
if (is_wp_error($data)) { |
| 65 |
wp_send_json_error($data->get_error_message(), 400); |
| 66 |
} |
| 67 |
|
| 68 |
$params = IntegrationHandler::replaceFieldWithValue($data['params'], []); |
| 69 |
$params['entry_id'] = 'test'; |
| 70 |
|
| 71 |
$response = self::sendRequest($data['url'], isset($details->method) ? $details->method : 'get', $params); |
| 72 |
if (is_wp_error($response)) { |
| 73 |
$errorMessage = $response->get_error_message(); |
| 74 |
wp_send_json_error('' === $errorMessage ? __('Unknown error occurred', 'bit-form') : $errorMessage, 400); |
| 75 |
} |
| 76 |
|
| 77 |
wp_send_json_success(['msg' => 'webhook executed succcessfully', 'response' => $response], 200); |
| 78 |
} |
| 79 |
|
| 80 |
public function execute(IntegrationHandler $integrationHandler, $integrationDetails, $fieldValues, $entryID, $logID) |
| 81 |
{ |
| 82 |
$details = is_string($integrationDetails->integration_details) ? json_decode($integrationDetails->integration_details) : $integrationDetails->integration_details; |
| 83 |
|
| 84 |
$entryDetails = [ |
| 85 |
'formId' => $this->formID, |
| 86 |
'entryId' => $entryID, |
| 87 |
'fieldValues' => $fieldValues |
| 88 |
]; |
| 89 |
|
| 90 |
$data = self::urlParserWrapper(isset($details->url) ? $details->url : ''); |
| 91 |
if (is_wp_error($data)) { |
| 92 |
$this->logWebhookResponse($logID, 'errors', $data->get_error_message(), $entryDetails); |
| 93 |
return false; |
| 94 |
} |
| 95 |
|
| 96 |
$params = IntegrationHandler::replaceFieldWithValue($data['params'], $fieldValues); |
| 97 |
$params['entry_id'] = $entryID; |
| 98 |
|
| 99 |
$response = self::sendRequest($data['url'], isset($details->method) ? $details->method : 'get', $params); |
| 100 |
$this->logWebhookResponse($logID, is_wp_error($response) ? 'errors' : 'success', $response, $entryDetails); |
| 101 |
|
| 102 |
return $response; |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Dispatches the webhook request with the configured http method. |
| 107 |
* |
| 108 |
* @param string $url |
| 109 |
* @param string $method |
| 110 |
* @param array $params |
| 111 |
* @return mixed|\WP_Error |
| 112 |
*/ |
| 113 |
private static function sendRequest($url, $method, $params) |
| 114 |
{ |
| 115 |
switch (strtoupper($method)) { |
| 116 |
case 'GET': |
| 117 |
return HttpHelper::get($url, $params); |
| 118 |
|
| 119 |
case 'POST': |
| 120 |
return HttpHelper::post($url, $params); |
| 121 |
|
| 122 |
default: |
| 123 |
return HttpHelper::request($url, $method, $params); |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
private function logWebhookResponse($logID, $status, $response, $entryDetails) |
| 128 |
{ |
| 129 |
$this->_logResponse->apiResponse( |
| 130 |
$logID, |
| 131 |
$this->webhookID, |
| 132 |
['type' => 'record', 'type_name' => 'web hooks'], |
| 133 |
$status, |
| 134 |
$response, |
| 135 |
$entryDetails |
| 136 |
); |
| 137 |
} |
| 138 |
|
| 139 |
/** |
| 140 |
* Splits a webhook url into the url to call and its query params. |
| 141 |
* |
| 142 |
* @param mixed $url url as it comes from the saved integration details |
| 143 |
* @return array|\WP_Error ['url' => string, 'params' => array], or why the url was rejected |
| 144 |
*/ |
| 145 |
private static function urlParserWrapper($url) |
| 146 |
{ |
| 147 |
if (!is_string($url) || '' === trim($url)) { |
| 148 |
return new \WP_Error('bitform_webhook_url_empty', __('Webhook url is empty. Please add a url and try again.', 'bit-form')); |
| 149 |
} |
| 150 |
|
| 151 |
$parsedURL = wp_parse_url($url); |
| 152 |
if (empty($parsedURL['host'])) { |
| 153 |
return new \WP_Error('bitform_webhook_url_invalid', __('Webhook url is not a valid url.', 'bit-form')); |
| 154 |
} |
| 155 |
|
| 156 |
$Scheme = isset($parsedURL['scheme']) ? $parsedURL['scheme'] . '://' : null; |
| 157 |
$Usr = isset($parsedURL['user']) ? $parsedURL['user'] : null; |
| 158 |
$Pass = isset($parsedURL['pass']) ? ':' . $parsedURL['pass'] : null; |
| 159 |
$Host = $parsedURL['host']; |
| 160 |
$Port = isset($parsedURL['port']) ? ':' . $parsedURL['port'] : null; |
| 161 |
$Path = isset($parsedURL['path']) ? $parsedURL['path'] : null; |
| 162 |
$Query = isset($parsedURL['query']) ? $parsedURL['query'] : ''; |
| 163 |
$Pass = ($Pass || $Usr) ? "$Pass@" : null; |
| 164 |
|
| 165 |
$cleanURL = "$Scheme$Usr$Pass$Host$Port$Path"; |
| 166 |
$params = []; |
| 167 |
foreach (explode('&', $Query) as $keyValue) { |
| 168 |
if (empty($keyValue)) { |
| 169 |
continue; |
| 170 |
} |
| 171 |
$pair = explode('=', $keyValue, 2); |
| 172 |
if (2 !== \count($pair)) { |
| 173 |
continue; |
| 174 |
} |
| 175 |
list($field, $value) = $pair; |
| 176 |
if ('' === trim($value)) { |
| 177 |
continue; |
| 178 |
} |
| 179 |
if (isset($params[$field])) { |
| 180 |
if (\is_array($params[$field])) { |
| 181 |
$params[$field][] = sanitize_text_field(urldecode($value)); |
| 182 |
} else { |
| 183 |
$params[$field] = [$params[$field], sanitize_text_field(urldecode($value))]; |
| 184 |
} |
| 185 |
} else { |
| 186 |
$params[$field] = sanitize_text_field(urldecode($value)); |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
if (!wp_http_validate_url($cleanURL)) { |
| 191 |
return new \WP_Error('bitform_webhook_url_rejected', self::urlRejectionReason($cleanURL, $parsedURL)); |
| 192 |
} |
| 193 |
|
| 194 |
return ['url' => $cleanURL, 'params' => $params]; |
| 195 |
} |
| 196 |
|
| 197 |
/** |
| 198 |
* Explains why WordPress refused the url, so the message points at the real cause |
| 199 |
* (internal host, unresolvable dns, blocked port) instead of "url is empty". |
| 200 |
* |
| 201 |
* @param string $url url as it was handed to wp_http_validate_url() |
| 202 |
* @param array $parsedURL wp_parse_url() output of the original url |
| 203 |
* @return string |
| 204 |
*/ |
| 205 |
private static function urlRejectionReason($url, $parsedURL) |
| 206 |
{ |
| 207 |
$host = isset($parsedURL['host']) ? trim($parsedURL['host'], '.') : ''; |
| 208 |
$scheme = isset($parsedURL['scheme']) ? strtolower($parsedURL['scheme']) : ''; |
| 209 |
|
| 210 |
if ('http' !== $scheme && 'https' !== $scheme) { |
| 211 |
return __('Webhook url must start with http:// or https://.', 'bit-form'); |
| 212 |
} |
| 213 |
|
| 214 |
if (isset($parsedURL['user']) || isset($parsedURL['pass'])) { |
| 215 |
return __('Webhook url must not contain a username or password.', 'bit-form'); |
| 216 |
} |
| 217 |
|
| 218 |
if (!filter_var($host, FILTER_VALIDATE_IP) && gethostbyname($host) === $host) { |
| 219 |
/* translators: %s: webhook host name */ |
| 220 |
return sprintf(__('The host "%s" could not be resolved from this server. Check the url spelling and the server DNS.', 'bit-form'), $host); |
| 221 |
} |
| 222 |
|
| 223 |
if (self::validatesAsExternalHost($url)) { |
| 224 |
/* translators: %s: webhook host name */ |
| 225 |
return sprintf(__('The host "%s" resolves to a private or local IP address. WordPress blocks requests to internal hosts, allow it with the "http_request_host_is_external" filter.', 'bit-form'), $host); |
| 226 |
} |
| 227 |
|
| 228 |
if (!empty($parsedURL['port'])) { |
| 229 |
$allowedPorts = apply_filters('http_allowed_safe_ports', [80, 443, 8080], $host, $url); |
| 230 |
if (\is_array($allowedPorts) && !\in_array((int) $parsedURL['port'], $allowedPorts, true)) { |
| 231 |
/* translators: 1: port number, 2: comma separated list of allowed ports */ |
| 232 |
return sprintf(__('Port %1$d is not allowed for outgoing requests. WordPress only allows %2$s, extend it with the "http_allowed_safe_ports" filter.', 'bit-form'), (int) $parsedURL['port'], implode(', ', $allowedPorts)); |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
return __('Webhook url is not a valid url.', 'bit-form'); |
| 237 |
} |
| 238 |
|
| 239 |
/** |
| 240 |
* Re-checks the url while treating the host as external, which tells the local/private |
| 241 |
* IP rejection apart from every other reason wp_http_validate_url() can fail. |
| 242 |
* |
| 243 |
* @param string $url |
| 244 |
* @return bool |
| 245 |
*/ |
| 246 |
private static function validatesAsExternalHost($url) |
| 247 |
{ |
| 248 |
$allowExternal = function () { |
| 249 |
return true; |
| 250 |
}; |
| 251 |
|
| 252 |
add_filter('http_request_host_is_external', $allowExternal, 99); |
| 253 |
$isValid = (bool) wp_http_validate_url($url); |
| 254 |
remove_filter('http_request_host_is_external', $allowExternal, 99); |
| 255 |
|
| 256 |
return $isValid; |
| 257 |
} |
| 258 |
|
| 259 |
private function iterate($array) |
| 260 |
{ |
| 261 |
$ar = []; |
| 262 |
if (is_array($array)) { |
| 263 |
foreach ($array as $k => $v) { |
| 264 |
$ar[$k] = str_replace("\'", "'", $v); |
| 265 |
} |
| 266 |
} |
| 267 |
return $ar; |
| 268 |
} |
| 269 |
} |
| 270 |
|