PluginProbe
WPGet API – Connect to any external REST API / 1.8.0
WPGet API – Connect to any external REST API v1.8.0
1.9.2 1.9.3 1.9.4 1.9.5 1.9.6 1.9.7 1.9.8 1.9.9 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.1.0 2.1.1 2.1.3 2.1.4 2.1.5 2.2.0 2.2.1 2.2.10 2.2.2 2.2.3 All 97 releases
wpgetapi / includes / class-api.php

class-api.php in WPGet API – Connect to any external REST API 1.8.0, at includes/class-api.php

611 lines 22.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 // Exit if accessed directly
4 if ( ! defined( 'ABSPATH' ) ) exit;
5
6 /**
7 * The main class
8 *
9 * @since 1.0.0
10 */
11 class WpGetApi_Api {
12
13 public $encryption = ''; // the encryption class
14
15 public $setup = ''; // store the setup data from the admin page
16 public $api = ''; // store the api's from the admin page
17
18 public $api_id = ''; // the api_id that we are wanting to get
19 public $endpoint_id = ''; // the endpoint_id that we are wanting to get
20 public $args = ''; // the args
21 public $keys = ''; // the keys we want to retrieve
22
23 public $base_url = ''; // base url of the API
24 public $method = 'GET'; // the endpoint method GET POST etc
25 public $cache_time = ''; // the time to cache
26 public $endpoint = ''; // the endpoint that we will get
27 public $query_parameters = ''; // the query paramaters appended to url
28 public $header_parameters = ''; // the header paramaters
29 public $body_parameters = ''; // the body paramaters
30 public $body_json_encode = ''; // body_json_encode body
31 public $body_url_encode = ''; // urlencode body
32 public $body_xml_format = ''; // xml format body
33 public $xml_root_node = 'root'; // root node for xml
34
35 public $response = ''; // the returned response
36
37 public $final_url = ''; // final URL
38 public $final_request_args = array(); // final request_args
39
40 public $results_format = 'json_string'; // reseults format
41
42 public $timeout = 10; // the timeout
43 public $sslverify = 1; // the paramaters
44 public $debug = false;
45
46
47 /**
48 * Main constructor
49 *
50 * @since 1.0.0
51 *
52 */
53 public function __construct( $api_id = '', $endpoint_id = '', $args = array(), $keys = array() ) {
54
55 $this->setup = get_option( 'wpgetapi_setup' );
56 $this->api = get_option( 'wpgetapi_' . $api_id );
57
58 $this->encryption = new WpGetApi_Encryption();
59 $this->api_id = sanitize_text_field( $api_id );
60 $this->endpoint_id = sanitize_text_field( $endpoint_id );
61 $this->keys = $keys;
62 $this->args = $args;
63
64 add_filter( 'wpgetapi_raw_data', array( $this, 'maybe_add_debug_info' ), 99, 2 );
65
66 }
67
68
69 /**
70 * Init our api data
71 */
72 public function init() {
73
74 // do some checks
75 if( empty( $this->setup ) || ! isset( $this->setup['apis'] ) || empty( $this->setup['apis'] ) )
76 return 'No API found.';
77
78 // do some checks
79 if( ! $this->api || ! isset( $this->api['endpoints'] ) || empty( $this->api['endpoints'] ))
80 return 'API not found.';
81
82 // loop through api's
83 // set base_url
84 foreach ( $this->setup['apis'] as $index => $api_item ) {
85 if( $this->api_id == $api_item['id'] ) {
86 $this->base_url = isset( $api_item['base_url'] ) && ! empty( $api_item['base_url'] ) ? esc_url_raw( $api_item['base_url'] ) : '';
87 }
88 }
89
90 // loop through endpoints
91 foreach ( $this->api['endpoints'] as $index => $endpoint ) {
92
93 if( $this->endpoint_id == $endpoint['id'] ) {
94
95 $this->method = isset( $endpoint['method'] ) && $endpoint['method'] != '' ? sanitize_text_field( $endpoint['method'] ) : 'GET';
96 $this->cache_time = isset( $endpoint['cache_time'] ) && ! empty( $endpoint['cache_time'] ) ? absint( $endpoint['cache_time'] ) : '';
97 $this->endpoint = isset( $endpoint['endpoint'] ) && ! empty( $endpoint['endpoint'] ) ? sanitize_text_field( $endpoint['endpoint'] ) : '';
98
99 $this->query_parameters = isset( $endpoint['query_parameters'] ) && ! empty( $endpoint['query_parameters'] ) ? $this->do_parameters( $endpoint['query_parameters'] ) : array();
100
101 $this->header_parameters = isset( $endpoint['header_parameters'] ) && ! empty( $endpoint['header_parameters'] ) ? $this->do_parameters( $endpoint['header_parameters'] ) : array();
102
103 $this->body_parameters = isset( $endpoint['body_parameters'] ) && ! empty( $endpoint['body_parameters'] ) ? $this->do_parameters( $endpoint['body_parameters'] ) : array();
104
105 $this->body_json_encode = isset( $endpoint['body_json_encode'] ) && $endpoint['body_json_encode'] == 'true' ? true : false;
106 $this->body_url_encode = isset( $endpoint['body_json_encode'] ) && $endpoint['body_json_encode'] == 'url' ? true : false;
107 $this->body_xml_format = isset( $endpoint['body_json_encode'] ) && $endpoint['body_json_encode'] == 'xml' ? true : false;
108 $this->xml_root_node = isset( $endpoint['xml_root'] ) && ! empty( $endpoint['xml_root'] ) ? $endpoint['xml_root'] : $this->xml_root_node;
109
110 $this->results_format = isset( $endpoint['results_format'] ) ? sanitize_text_field( $endpoint['results_format'] ) : $this->results_format;
111 }
112 }
113
114 $this->timeout = isset( $this->api['timeout'] ) && ! empty( $this->api['timeout'] ) ? $this->api['timeout'] : $this->timeout;
115 $this->sslverify = isset( $this->api['sslverify'] ) ? absint( $this->api['sslverify'] ) : $this->sslverify;
116
117 }
118
119
120 /**
121 * The main function to output the data
122 *
123 * @param string $field Field to retrieve
124 */
125 public function endpoint_output() {
126
127 do_action( 'wpgetapi_before_do_the_call', $this );
128
129 return $this->do_the_call();
130
131 }
132
133
134 /**
135 * Sort out the parameters if they exist
136 */
137 public function do_parameters( $parameters ) {
138
139 $new_array = array();
140 $parameters = $this->decrypt( $parameters );
141
142 if( is_array( $parameters ) ) {
143 foreach ( $parameters as $key => $parameter ) {
144 if( ! empty( $parameter['name'] ) && ! empty( $parameter['value'] ) ) {
145 $parameter['value'] = stripslashes( $parameter['value'] );
146 $new_array[ sanitize_text_field( $parameter['name'] ) ] = $parameter['value'];
147 }
148 }
149 }
150
151 // look for array or json string and sort these out - for using such things in shortcode
152 if( is_array( $new_array ) ) {
153
154 foreach ( $new_array as $key => $value ) {
155
156 // checking if the parameters have a json string
157 if ( substr( $value, 0, 1 ) === '{' && substr( $value, -1 ) === '}' ) {
158 $new_array[ $key ] = json_decode( $value, true );
159 }
160
161 // checking if the parameters have an array within the string
162 // if they do, create them as an actual array
163 if ( substr( $value, 0, 1 ) === '[' && substr( $value, -1 ) === ']' ) {
164 $value = trim( $value,"[]" );
165 $new_array[ $key ] = array( $value );
166
167 }
168
169 // set value as integer
170 if ( strpos( $value, 'integer(' ) !== false && substr( $value, -1 ) === ')' ) {
171 preg_match("/\(([^\)]*)\)/", $value, $match );
172 $result = $match[1];
173 $new_array[ $key ] = absint( $result );
174
175 }
176
177 // set value as float
178 if ( strpos( $value, 'float(' ) !== false && substr( $value, -1 ) === ')' ) {
179 preg_match("/\(([^\)]*)\)/", $value, $match );
180 $result = $match[1];
181 $new_array[ $key ] = (float) $result;
182
183 }
184
185 }
186
187 }
188
189 return $new_array;
190
191 }
192
193 /**
194 * Send the request and return our data
195 */
196 public function do_the_call() {
197
198 $this->init();
199
200 // build the URL
201 $this->final_url = apply_filters( 'wpgetapi_final_url', $this->build_url(), $this );
202
203 // build the request args
204 $this->final_request_args = apply_filters( 'wpgetapi_final_request_args', $this->build_request_args(), $this );
205
206 /**
207 * Check if we should stop or not. Setting $on to true, will stop us calling the api.
208 * @param bool $on Whether on is set or not.
209 */
210 if ( apply_filters( 'wpgetapi_should_we_stop', false, $this ) ) {
211 return;
212 }
213
214 // POST request
215 if( $this->method == 'POST' )
216 $this->response = $this->POST_request();
217
218 // PUT request
219 if( $this->method == 'PUT' )
220 $this->response = $this->PUT_request();
221
222 // GET request
223 if( $this->method == 'GET' )
224 $this->response = $this->GET_request();
225
226 // DELETE request
227 if( $this->method == 'DELETE' )
228 $this->response = $this->DELETE_request();
229
230 // wp error
231 if( is_wp_error( $this->response ) ) {
232 return apply_filters( 'wpgetapi_raw_error_data', json_encode( $this->response ), $this );
233 }
234
235 // get response_code
236 $response_code = wp_remote_retrieve_response_code( $this->response );
237
238 // action to intercept call depending on response_code
239 $this->response = apply_filters( 'wpgetapi_before_retrieve_body', $this->response, $response_code, $this );
240
241 // get body
242 // modified in version 1.6.1 to allow for OAuth 2.0 plugin returning body already
243 $data = isset( $this->response['body'] ) ? $this->response['body'] : $this->response;
244
245 // returning in JSON format
246 if( $this->results_format == 'json_string' || $this->results_format == 'json_decoded' )
247 $data = $this->return_data( $data );
248
249 if( $data === 'null' )
250 $data = 'Result is null. Check that all endpoint settings are correct.';
251
252 return apply_filters( 'wpgetapi_raw_data', $data, $this );
253
254 }
255
256
257 /**
258 * Build the request url with the ability to add args
259 */
260 public function build_url() {
261
262 // first make sure our endpoint starts with a slash
263 if ( substr( $this->endpoint, 0, 1 ) != '/' )
264 $this->endpoint = '/' . $this->endpoint;
265
266 $this->endpoint = apply_filters( 'wpgetapi_endpoint', $this->endpoint, $this );
267
268 $url = untrailingslashit( $this->base_url ) . $this->endpoint;
269
270 // filter our params - added for use in Oauth 2.0 plugin
271 $params = apply_filters( 'wpgetapi_query_parameters', $this->query_parameters, $this );
272
273 // add empty array - was getting errors if it was just null or false
274 $params = empty( $params ) ? array(''=>'') : $params;
275
276 return add_query_arg( $params, $url );
277
278 }
279
280
281 /**
282 * build the header with the ability to add args
283 */
284 public function build_request_args() {
285
286 // add our header parameters to the headers
287 $headers = apply_filters( 'wpgetapi_header_parameters', array(
288 'headers' => $this->header_parameters,
289 ), $this );
290
291
292 // if doing POST request, include body paramters
293 if( $this->method == 'POST' || $this->method == 'PUT' || $this->method == 'DELETE' ) {
294
295 $this->body_parameters = apply_filters( 'wpgetapi_body_parameters', $this->body_parameters, $this );
296
297 // do we json_encode the entire body
298 if( $this->body_json_encode == true ) {
299 $this->body_parameters = json_encode( $this->body_parameters );
300 }
301
302
303 // do we urlencode the entire body
304 if( $this->body_url_encode == true ) {
305 $data_raw = '';
306 foreach ($this->body_parameters as $key => $value){
307 $data_raw = $data_raw . $key . "=" . urlencode($value) . "&";
308 }
309 $this->body_parameters = $data_raw;
310 }
311
312 // do we xml the entire body
313 if( $this->body_xml_format == true ) {
314
315 $xml = new SimpleXmlElement( '<' . $this->xml_root_node . '/>' );
316
317 foreach( $this->body_parameters as $key => $value) {
318 $xml->addChild( $key, $value );
319 }
320
321 $this->body_parameters = $xml->asXML();
322
323 }
324
325 // add our body parameters
326 if( $this->body_parameters && ! empty( $this->body_parameters ) )
327 $headers['body'] = $this->body_parameters;
328
329 }
330
331 // add headers to our final request args
332 $this->final_request_args = wp_parse_args( $headers, $this->final_request_args );
333
334 // build the args taht are sent to the request
335 $default_args = apply_filters( 'wpgetapi_default_request_args_parameters', array(
336 'timeout' => $this->timeout,
337 'sslverify' => $this->sslverify,
338 'redirection' => 5,
339 'blocking' => true,
340 'cookies' => array(),
341 ) );
342
343 return wp_parse_args( $this->final_request_args, $default_args );
344
345 }
346
347
348 /**
349 * Do a GET request
350 */
351 public function GET_request() {
352 $response = '';
353 // so we can so something before the remote_get (caching)
354 $response = apply_filters( 'wpgetapi_before_get_request', $response, $this );
355 if( empty( $response ) )
356 $response = wp_remote_get( $this->final_url, $this->final_request_args );
357
358 return $response;
359 }
360
361 /**
362 * Do a POST request
363 */
364 public function POST_request() {
365 $response = wp_remote_post( $this->final_url, $this->final_request_args );
366 return $response;
367 }
368
369 /**
370 * Do a PUT request
371 */
372 public function PUT_request() {
373 $this->final_request_args['method'] = 'PUT';
374 $response = wp_remote_request( $this->final_url, $this->final_request_args );
375 return $response;
376 }
377
378 /**
379 * Do a DELETE request
380 */
381 public function DELETE_request() {
382 $this->final_request_args['method'] = 'DELETE';
383 $response = wp_remote_request( $this->final_url, $this->final_request_args );
384 return $response;
385 }
386
387
388 /**
389 * return data
390 */
391 public function return_data( $data ) {
392
393 $data = apply_filters( 'wpgetapi_json_response_body_before_decode', $data, $this->keys );
394
395 // converts all data to arrays, removing objects
396 if( is_string( $data ) )
397 $data = json_decode( $data, true );
398
399 $data = apply_filters( 'wpgetapi_json_response_body', $data, $this->keys );
400
401 if( $this->results_format == 'json_string' )
402 return trim( json_encode( $data ),'"');
403
404 if( $this->results_format == 'json_decoded' )
405 return $data;
406
407 }
408
409
410 /**
411 * decrypt our parameters from the DB
412 */
413 public function decrypt( $array_or_string ) {
414
415 if( is_string($array_or_string) ){
416 $array_or_string = $this->encryption->decrypt($array_or_string);
417 }elseif( is_array($array_or_string) ){
418 foreach ( $array_or_string as $key => &$value ) {
419 if( $key === 'name' )
420 continue;
421 if ( is_array( $value ) ) {
422 $value = $this->decrypt($value);
423 }
424 else {
425 $value = $this->encryption->decrypt($value);
426
427 }
428 }
429 }
430 return $array_or_string;
431 }
432
433
434 /**
435 * debug
436 */
437 public function maybe_add_debug_info( $data, $wpgetapi ) {
438
439 if(
440 ( isset( $this->args['debug'] ) && ( $this->args['debug'] === true || $this->args['debug'] === 'true' ) ) ||
441 ( isset( $this->args['test_endpoint'] ) && ( $this->args['test_endpoint'] === true ) )
442 ) {
443
444 $this->debug = true;
445
446 $testing = isset( $this->args['test_endpoint'] ) && ( $this->args['test_endpoint'] === true ) ? true : false;
447
448 ob_start(); ?>
449
450 <style>
451
452 .wpgetapi-debug {
453 background: #fff;
454 padding: 20px;
455 box-shadow: 0 0 1px #aaa;
456 margin: 20px;
457 font-size: 15px;
458 }
459 .wpgetapi-debug
460 .wpgetapi-debug p
461 .wpgetapi-debug h5
462 .wpgetapi-debug h6 {
463 color: #000;
464 line-height: 1 !important;
465 text-transform: none !important;
466 font-family: sans-serif !important;
467 letter-spacing: 0px !important;
468 }
469 .wpgetapi-debug p.small {
470 font-size: 85%;
471 color: #999;
472 margin: 0 0 12px !important;
473 }
474 .wpgetapi-debug h5 {
475 font-weight: bold;
476 font-size: 18px;
477 margin: 0 0 3px;
478 text-transform: none !important;
479 }
480 .wpgetapi-debug .debug-item {
481 margin: 10px 0;
482 background: #fff;
483 padding: 15px 20px;
484 display: inline-block !important;
485 width: 100% !important;
486 box-shadow: 3px 3px 0 rgb(0 0 0 / 8%);
487 border: 1px solid #efefef;
488 }
489 .wpgetapi-debug .debug-item h6 {
490 font-weight: bold;
491 font-size: 14px;
492 margin: 0;
493 text-transform: none !important;
494 }
495 .wpgetapi-debug .debug-item .debug-result,
496 .wpgetapi-debug .debug-item .debug-result pre {
497 font-family: monospace !important;
498 font-size: 13px !important;
499 margin: 0 !important;
500 padding: 8px 12px;
501 background: #f8f8f8;
502 }
503 .wpgetapi-debug .debug-item .debug-result pre {
504 border: none;
505 padding: 5px
506 }
507
508 .wpgetapi-debug.testing {
509 background: transparent;
510 padding: 0;
511 box-shadow: none;
512 }
513 .wpgetapi-debug.testing .debug-item {
514 margin: 5px 0;
515 }
516 </style>
517
518 <div class="wpgetapi-debug <?php echo $testing ? 'testing' : ''; ?>">
519
520 <?php if( $testing ) { ?>
521
522 <div class="debug-item">
523 <h6><?php esc_html_e( 'Full URL', 'wpgetapi' ); ?></h6>
524 <p class="small"><?php esc_html_e( 'The full URL that is being called.', 'wpgetapi' ); ?></p>
525 <div class="debug-result"><?php esc_html_e( $this->final_url ); ?></div>
526 </div>
527
528 <div class="debug-item">
529 <h6><?php esc_html_e( 'Data Output', 'wpgetapi' ); ?></h6>
530 <p class="small"><?php esc_html_e( 'The output that has been returned from the API. This is what the shortcode or template tag will display and can be formatted however you like.', 'wpgetapi' ); ?></p>
531 <p class="small"><?php esc_html_e( 'See the ', 'wpgetapi' ); ?> <a target="_blank" href="https://wpgetapi.com/docs/?utm_campaign=Test Endpoint&utm_medium=Admin&utm_source=User"><?php esc_html_e( 'documentation', 'wpgetapi' ); ?></a> <?php esc_html_e( ' for help in formatting.', 'wpgetapi' ); ?></p>
532 <div class="debug-result"><?php wpgetapi_pp( $data ); ?></div>
533 </div>
534
535 <div class="debug-item">
536 <h6><?php esc_html_e( 'Response', 'wpgetapi' ); ?></h6>
537 <p class="small"><?php esc_html_e( 'The full response from the API request.', 'wpgetapi' ); ?></p>
538 <div class="debug-result"><?php wpgetapi_pp( $this->response); ?></div>
539 </div>
540
541 <?php } else { ?>
542
543 <h5><strong><?php esc_html_e( 'WPGetAPI, Debug Mode - Plugin Version', 'wpgetapi' ); ?> <?php esc_html_e( WpGetApi()->version ); ?></strong></h5>
544 <p class="small"><?php esc_html_e( 'Below you will find debug info for the current API call. To turn this off, set debug to false in your shortcode or template tag.', 'wpgetapi' ); ?><br><?php esc_html_e( 'Connecting to API\'s can be tricky - if you require help, please see the', 'wpgetapi' ); ?> <a target="_blank" href="https://wpgetapi.com/docs/"><?php esc_html_e( 'Documentation', 'wpgetapi' ); ?></a>.</p>
545
546 <div class="debug-item">
547 <h6><?php esc_html_e( 'Full URL', 'wpgetapi' ); ?></h6>
548 <p class="small"><?php esc_html_e( 'The full URL that is being called.', 'wpgetapi' ); ?></p>
549 <div class="debug-result"><?php esc_html_e( $this->final_url ); ?></div>
550 </div>
551
552 <div class="debug-item">
553 <h6><?php esc_html_e( 'Data Output', 'wpgetapi' ); ?></h6>
554 <p class="small"><?php esc_html_e( 'The resulting output that has been returned from the API.', 'wpgetapi' ); ?></p>
555 <div class="debug-result"><?php wpgetapi_pp( $data ); ?></div>
556 </div>
557
558 <div class="debug-item">
559 <h6><?php esc_html_e( 'Query String', 'wpgetapi' ); ?></h6>
560 <p class="small"><?php esc_html_e( 'The query string parameters (if any) that you have set within the endpoint settings.', 'wpgetapi' ); ?></p>
561 <div class="debug-result"><?php wpgetapi_pp( $this->query_parameters ); ?></div>
562 </div>
563
564 <div class="debug-item">
565 <h6><?php esc_html_e( 'Headers', 'wpgetapi' ); ?></h6>
566 <p class="small"><?php esc_html_e( 'The header parameters (if any) that you have set within the endpoint settings.', 'wpgetapi' ); ?></p>
567 <div class="debug-result"><?php wpgetapi_pp( $this->header_parameters ); ?></div>
568 </div>
569
570 <div class="debug-item">
571 <h6><?php esc_html_e( 'Body', 'wpgetapi' ); ?></h6>
572 <p class="small"><?php esc_html_e( 'The body parameters (if any) that you have set within the endpoint settings.', 'wpgetapi' ); ?></p>
573 <div class="debug-result"><?php wpgetapi_pp( $this->body_parameters ); ?></div>
574 </div>
575
576 <div class="debug-item">
577 <h6><?php esc_html_e( 'Final Request Arguments', 'wpgetapi' ); ?></h6>
578 <p class="small"><?php esc_html_e( 'The final request arguments sent in the API request. Includes headers and body arguments.', 'wpgetapi' ); ?></p>
579 <div class="debug-result"><?php wpgetapi_pp( $this->final_request_args ); ?></div>
580 </div>
581
582 <div class="debug-item">
583 <h6><?php esc_html_e( 'Arguments', 'wpgetapi' ); ?></h6>
584 <p class="small"><?php esc_html_e( 'The arguments set within your shortcode or template tag.', 'wpgetapi' ); ?></p>
585 <div class="debug-result"><?php wpgetapi_pp( $this->args ); ?></div>
586 </div>
587
588 <div class="debug-item">
589 <h6><?php esc_html_e( 'Response', 'wpgetapi' ); ?></h6>
590 <p class="small"><?php esc_html_e( 'The full response from the API request.', 'wpgetapi' ); ?></p>
591 <div class="debug-result"><?php wpgetapi_pp( $this->response); ?></div>
592 </div>
593
594 <?php } ?>
595
596 </div>
597
598 <?php
599
600 return ob_get_clean();
601
602 } else {
603
604 return $data;
605
606 }
607
608 }
609
610
611 }