PluginProbe
Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder / 3.6.41
Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder v3.6.41
6.2.14 6.2.13 6.2.12 6.2.10 6.2.11 6.2.9 6.2.8 6.2.7 6.2.6 6.2.5 6.2.4 6.2.3 6.2.2 3.6.22 3.6.31 3.6.40 3.6.41 3.6.42 3.6.50 3.6.51 3.6.60 3.6.61 3.6.62 3.6.64 3.6.65 All 196 releases
fluentform / app / Services / Integrations / MailChimp / MailChimp.php

MailChimp.php in Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder 3.6.41, at app/Services/Integrations/MailChimp/MailChimp.php

445 lines 14.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentForm\App\Services\Integrations\MailChimp;
4
5 /**
6 * Super-simple, minimum abstraction MailChimp API v3 wrapper
7 * MailChimp API v3: http://developer.mailchimp.com
8 * This wrapper: https://github.com/drewm/mailchimp-api
9 *
10 * @author Drew McLellan <drew.mclellan@gmail.com>
11 * @version 2.4
12 */
13 class MailChimp
14 {
15 private $api_key;
16 private $api_endpoint = 'https://<dc>.api.mailchimp.com/3.0';
17
18 const TIMEOUT = 10;
19
20 /* SSL Verification
21 Read before disabling:
22 http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
23 */
24 public $verify_ssl = true;
25
26 private $request_successful = false;
27 private $last_error = '';
28 private $last_response = array();
29 private $last_request = array();
30
31 /**
32 * Create a new instance
33 * @param string $api_key Your MailChimp API key
34 * @param string $api_endpoint Optional custom API endpoint
35 * @throws \Exception
36 */
37 public function __construct($api_key, $api_endpoint = null)
38 {
39 $this->api_key = $api_key;
40
41 if ($api_endpoint === null) {
42 if (strpos($this->api_key, '-') === false) {
43 throw new \Exception("Invalid MailChimp API key `{$api_key}` supplied.");
44 }
45 list(, $data_center) = explode('-', $this->api_key);
46 $this->api_endpoint = str_replace('<dc>', $data_center, $this->api_endpoint);
47 } else {
48 $this->api_endpoint = $api_endpoint;
49 }
50
51 $this->last_response = array('headers' => null, 'body' => null);
52 }
53
54 /**
55 * @return string The url to the API endpoint
56 */
57 public function getApiEndpoint()
58 {
59 return $this->api_endpoint;
60 }
61
62
63 /**
64 * Convert an email address into a 'subscriber hash' for identifying the subscriber in a method URL
65 * @param string $email The subscriber's email address
66 * @return string Hashed version of the input
67 */
68 public function subscriberHash($email)
69 {
70 return md5(strtolower($email));
71 }
72
73 /**
74 * Was the last request successful?
75 * @return bool True for success, false for failure
76 */
77 public function success()
78 {
79 return $this->request_successful;
80 }
81
82 /**
83 * Get the last error returned by either the network transport, or by the API.
84 * If something didn't work, this should contain the string describing the problem.
85 * @return string|false describing the error
86 */
87 public function getLastError()
88 {
89 return $this->last_error ?: false;
90 }
91
92 /**
93 * Get an array containing the HTTP headers and the body of the API response.
94 * @return array Assoc array with keys 'headers' and 'body'
95 */
96 public function getLastResponse()
97 {
98 return $this->last_response;
99 }
100
101 /**
102 * Get an array containing the HTTP headers and the body of the API request.
103 * @return array Assoc array
104 */
105 public function getLastRequest()
106 {
107 return $this->last_request;
108 }
109
110 /**
111 * Make an HTTP DELETE request - for deleting data
112 * @param string $method URL of the API request method
113 * @param array $args Assoc array of arguments (if any)
114 * @param int $timeout Timeout limit for request in seconds
115 * @return array|false Assoc array of API response, decoded from JSON
116 */
117 public function delete($method, $args = array(), $timeout = self::TIMEOUT)
118 {
119 return $this->makeRequest('delete', $method, $args, $timeout);
120 }
121
122 /**
123 * Make an HTTP GET request - for retrieving data
124 * @param string $method URL of the API request method
125 * @param array $args Assoc array of arguments (usually your data)
126 * @param int $timeout Timeout limit for request in seconds
127 * @return array|false Assoc array of API response, decoded from JSON
128 */
129 public function get($method, $args = array(), $timeout = self::TIMEOUT)
130 {
131 return $this->makeRequest('get', $method, $args, $timeout);
132 }
133
134 /**
135 * Make an HTTP PATCH request - for performing partial updates
136 * @param string $method URL of the API request method
137 * @param array $args Assoc array of arguments (usually your data)
138 * @param int $timeout Timeout limit for request in seconds
139 * @return array|false Assoc array of API response, decoded from JSON
140 */
141 public function patch($method, $args = array(), $timeout = self::TIMEOUT)
142 {
143 return $this->makeRequest('patch', $method, $args, $timeout);
144 }
145
146 /**
147 * Make an HTTP POST request - for creating and updating items
148 * @param string $method URL of the API request method
149 * @param array $args Assoc array of arguments (usually your data)
150 * @param int $timeout Timeout limit for request in seconds
151 * @return array|false Assoc array of API response, decoded from JSON
152 */
153 public function post($method, $args = array(), $timeout = self::TIMEOUT)
154 {
155 return $this->makeRequest('post', $method, $args, $timeout);
156 }
157
158 /**
159 * Make an HTTP PUT request - for creating new items
160 * @param string $method URL of the API request method
161 * @param array $args Assoc array of arguments (usually your data)
162 * @param int $timeout Timeout limit for request in seconds
163 * @return array|false Assoc array of API response, decoded from JSON
164 * @throws \Exception
165 */
166 public function put($method, $args = array(), $timeout = self::TIMEOUT)
167 {
168 return $this->makeRequest('put', $method, $args, $timeout);
169 }
170
171 /**
172 * Performs the underlying HTTP request. Not very exciting.
173 * @param string $http_verb The HTTP verb to use: get, post, put, patch, delete
174 * @param string $method The API method to be called
175 * @param array $args Assoc array of parameters to be passed
176 * @param int $timeout
177 * @return array|false Assoc array of decoded result
178 * @throws \Exception
179 */
180 private function makeRequest($http_verb, $method, $args = array(), $timeout = self::TIMEOUT)
181 {
182 if (!function_exists('curl_init') || !function_exists('curl_setopt')) {
183 throw new \Exception("cURL support is required, but can't be found.");
184 }
185
186 $url = $this->api_endpoint . '/' . $method;
187
188 $response = $this->prepareStateForRequest($http_verb, $method, $url, $timeout);
189
190 $httpHeader = array(
191 'Accept: application/vnd.api+json',
192 'Content-Type: application/vnd.api+json',
193 'Authorization: apikey ' . $this->api_key
194 );
195
196 if (isset($args["language"])) {
197 $httpHeader[] = "Accept-Language: " . $args["language"];
198 }
199
200 $ch = curl_init();
201 curl_setopt($ch, CURLOPT_URL, $url);
202 curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
203 curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)');
204 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
205 curl_setopt($ch, CURLOPT_VERBOSE, true);
206 curl_setopt($ch, CURLOPT_HEADER, true);
207 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
208 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
209 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
210 curl_setopt($ch, CURLOPT_ENCODING, '');
211 curl_setopt($ch, CURLINFO_HEADER_OUT, true);
212
213 switch ($http_verb) {
214 case 'post':
215 curl_setopt($ch, CURLOPT_POST, true);
216 $this->attachRequestPayload($ch, $args);
217 break;
218
219 case 'get':
220 $query = http_build_query($args, '', '&');
221 curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
222 break;
223
224 case 'delete':
225 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
226 break;
227
228 case 'patch':
229 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
230 $this->attachRequestPayload($ch, $args);
231 break;
232
233 case 'put':
234 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
235 $this->attachRequestPayload($ch, $args);
236 break;
237 }
238
239 $responseContent = curl_exec($ch);
240 $response['headers'] = curl_getinfo($ch);
241 $response = $this->setResponseState($response, $responseContent, $ch);
242 $formattedResponse = $this->formatResponse($response);
243
244 curl_close($ch);
245
246 $this->determineSuccess($response, $formattedResponse, $timeout);
247
248 return $formattedResponse;
249 }
250
251 /**
252 * @param string $http_verb
253 * @param string $method
254 * @param string $url
255 * @param integer $timeout
256 */
257 private function prepareStateForRequest($http_verb, $method, $url, $timeout)
258 {
259 $this->last_error = '';
260
261 $this->request_successful = false;
262
263 $this->last_response = array(
264 'headers' => null, // array of details from curl_getinfo()
265 'httpHeaders' => null, // array of HTTP headers
266 'body' => null // content of the response
267 );
268
269 $this->last_request = array(
270 'method' => $http_verb,
271 'path' => $method,
272 'url' => $url,
273 'body' => '',
274 'timeout' => $timeout,
275 );
276
277 return $this->last_response;
278 }
279
280 /**
281 * Get the HTTP headers as an array of header-name => header-value pairs.
282 *
283 * The "Link" header is parsed into an associative array based on the
284 * rel names it contains. The original value is available under
285 * the "_raw" key.
286 *
287 * @param string $headersAsString
288 * @return array
289 */
290 private function getHeadersAsArray($headersAsString)
291 {
292 $headers = array();
293
294 foreach (explode("\r\n", $headersAsString) as $i => $line) {
295 if ($i === 0) { // HTTP code
296 continue;
297 }
298
299 $line = trim($line);
300 if (empty($line)) {
301 continue;
302 }
303
304 list($key, $value) = explode(': ', $line);
305
306 if ($key == 'Link') {
307 $value = array_merge(
308 array('_raw' => $value),
309 $this->getLinkHeaderAsArray($value)
310 );
311 }
312
313 $headers[$key] = $value;
314 }
315
316 return $headers;
317 }
318
319 /**
320 * Extract all rel => URL pairs from the provided Link header value
321 *
322 * Mailchimp only implements the URI reference and relation type from
323 * RFC 5988, so the value of the header is something like this:
324 *
325 * 'https://us13.api.mailchimp.com/schema/3.0/Lists/Instance.json; rel="describedBy", <https://us13.admin.mailchimp.com/lists/members/?id=XXXX>; rel="dashboard"'
326 *
327 * @param string $linkHeaderAsString
328 * @return array
329 */
330 private function getLinkHeaderAsArray($linkHeaderAsString)
331 {
332 $urls = array();
333
334 if (preg_match_all('/<(.*?)>\s*;\s*rel="(.*?)"\s*/', $linkHeaderAsString, $matches)) {
335 foreach ($matches[2] as $i => $relName) {
336 $urls[$relName] = $matches[1][$i];
337 }
338 }
339
340 return $urls;
341 }
342
343 /**
344 * Encode the data and attach it to the request
345 * @param resource $ch cURL session handle, used by reference
346 * @param array $data Assoc array of data to attach
347 */
348 private function attachRequestPayload(&$ch, $data)
349 {
350 $encoded = json_encode($data);
351 $this->last_request['body'] = $encoded;
352 curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
353 }
354
355 /**
356 * Decode the response and format any error messages for debugging
357 * @param array $response The response from the curl request
358 * @return array|false The JSON decoded into an array
359 */
360 private function formatResponse($response)
361 {
362 $this->last_response = $response;
363
364 if (!empty($response['body'])) {
365 return json_decode($response['body'], true);
366 }
367
368 return false;
369 }
370
371 /**
372 * Do post-request formatting and setting state from the response
373 * @param array $response The response from the curl request
374 * @param string $responseContent The body of the response from the curl request
375 * * @return array The modified response
376 */
377 private function setResponseState($response, $responseContent, $ch)
378 {
379 if ($responseContent === false) {
380 $this->last_error = curl_error($ch);
381 } else {
382
383 $headerSize = $response['headers']['header_size'];
384
385 $response['httpHeaders'] = $this->getHeadersAsArray(substr($responseContent, 0, $headerSize));
386 $response['body'] = substr($responseContent, $headerSize);
387
388 if (isset($response['headers']['request_header'])) {
389 $this->last_request['headers'] = $response['headers']['request_header'];
390 }
391 }
392
393 return $response;
394 }
395
396 /**
397 * Check if the response was successful or a failure. If it failed, store the error.
398 * @param array $response The response from the curl request
399 * @param array|false $formattedResponse The response body payload from the curl request
400 * @param int $timeout The timeout supplied to the curl request.
401 * @return bool If the request was successful
402 */
403 private function determineSuccess($response, $formattedResponse, $timeout)
404 {
405 $status = $this->findHTTPStatus($response, $formattedResponse);
406
407 if ($status >= 200 && $status <= 299) {
408 $this->request_successful = true;
409 return true;
410 }
411
412 if (isset($formattedResponse['detail'])) {
413 $this->last_error = sprintf('%d: %s', $formattedResponse['status'], $formattedResponse['detail']);
414 return false;
415 }
416
417 if( $timeout > 0 && $response['headers'] && $response['headers']['total_time'] >= $timeout ) {
418 $this->last_error = sprintf('Request timed out after %f seconds.', $response['headers']['total_time'] );
419 return false;
420 }
421
422 $this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
423 return false;
424 }
425
426 /**
427 * Find the HTTP status code from the headers or API response body
428 * @param array $response The response from the curl request
429 * @param array|false $formattedResponse The response body payload from the curl request
430 * @return int HTTP status code
431 */
432 private function findHTTPStatus($response, $formattedResponse)
433 {
434 if (!empty($response['headers']) && isset($response['headers']['http_code'])) {
435 return (int) $response['headers']['http_code'];
436 }
437
438 if (!empty($response['body']) && isset($formattedResponse['status'])) {
439 return (int) $formattedResponse['status'];
440 }
441
442 return 418;
443 }
444 }
445