-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-freemius-api.php
More file actions
527 lines (448 loc) · 12.8 KB
/
Copy pathclass-freemius-api.php
File metadata and controls
527 lines (448 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
<?php
/**
* Freemius API
*
* @package Freemius
* @category WordPress_Plugin
* @author Freemius <support@freemius.com>
* @license MIT
* @link https://freemius.com/
*/
namespace Freemius;
/**
* Class Api
*
* @package Freemius
*/
class Api {
/**
* Instance of this class
*
* @var Api
*/
private static $instance = null;
/**
* Freemius API settings
*
* @var array
*/
private $api_settings = null;
/**
* Cache expiry time in seconds (1 hour)
*
* @var int
*/
private $cache_expiry = 3600;
/**
* Freemius API base URL
*
* @var string
*/
private $api_base_url = 'https://api.freemius.com/v1';
/**
* Dummy token for playground
*
* @var string
*/
private $dummy_token = '1234567890';
/**
* Constructor
*/
private function __construct() {
// Register REST API endpoints.
\add_action( 'rest_api_init', array( $this, 'register_rest_endpoints' ) );
}
/**
* Get instance of this class
*
* @return Api
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Prevent cloning of the instance
*/
private function __clone() {}
/**
* Prevent unserializing of the instance
*/
public function __wakeup() {}
/**
* Register REST API endpoints
*/
public function register_rest_endpoints() {
// Register namespace for Freemius API proxy.
\register_rest_route(
'freemius/v1',
'/proxy/(?P<endpoint>.*)',
array(
'methods' => 'GET',
'callback' => array( $this, 'proxy_get_request' ),
'permission_callback' => array( $this, 'check_permissions' ),
'args' => array(
'endpoint' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
),
)
);
\register_rest_route(
'freemius/v1',
'/proxy/(?P<endpoint>.*)',
array(
'methods' => array( 'POST', 'PUT', 'DELETE' ),
'callback' => array( $this, 'proxy_request' ),
'permission_callback' => array( $this, 'check_permissions' ),
'args' => array(
'endpoint' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
),
)
);
// Clear cache endpoint.
\register_rest_route(
'freemius/v1',
'/cache/clear',
array(
'methods' => 'POST',
'callback' => array( $this, 'clear_cache' ),
'permission_callback' => array( $this, 'check_permissions' ),
)
);
}
/**
* Check permissions for API access
*
* @return bool
*/
public function check_permissions() {
return \current_user_can( 'manage_options' );
}
/**
* Set cache expiry time in seconds
*
* @param int $expiry Cache expiry time in seconds.
*/
public function set_cache_expiry( $expiry ) {
$this->cache_expiry = $expiry;
}
/**
* Get Freemius API settings
*
* @return array|null
*/
private function get_api_settings() {
if ( null !== $this->api_settings ) {
return $this->api_settings;
}
$this->api_settings = \get_option( 'freemius_settings', array() );
if ( empty( $this->api_settings['token'] ) ) {
return null;
}
// Set default values.
$this->api_settings = wp_parse_args(
$this->api_settings,
array(
'token' => '',
)
);
return $this->api_settings;
}
/**
* Handle GET proxy requests with caching
*
* @param \WP_REST_Request $request The request object.
* @return \WP_REST_Response|\WP_Error
*/
public function proxy_get_request( $request ) {
$endpoint = $request->get_param( 'endpoint' );
$query_params = $request->get_query_params();
// Remove endpoint from query params.
unset( $query_params['endpoint'] );
unset( $query_params['_locale'] );
return $this->get_request( $endpoint, $query_params );
}
/**
* Make a GET request to Freemius API
*
* @param string $endpoint API endpoint.
* @param array $query_params Request parameters.
* @return \WP_REST_Response|\WP_Error
*/
public function get_request( $endpoint, $query_params = array() ) {
// Generate cache key.
$cache_key = $this->generate_cache_key( 'GET', $endpoint, $query_params );
// Try to get from cache first.
$cached_response = \get_transient( $cache_key );
if ( false !== $cached_response ) {
$response = new \WP_REST_Response( $cached_response['data'], $cached_response['status'] );
$response->header( 'X-Freemius-Cache', 'HIT' );
return $response;
}
// Make the actual API request.
$result = $this->make_freemius_request( 'GET', $endpoint, $query_params );
if ( \is_wp_error( $result ) ) {
return $result;
}
// Cache successful responses.
if ( $result['status'] >= 200 && $result['status'] < 300 ) {
\set_transient( $cache_key, $result, $this->cache_expiry );
}
$response = new \WP_REST_Response( $result['data'], $result['status'] );
$response->header( 'X-Freemius-Cache', 'MISS' );
return $response;
}
/**
* Handle non-GET proxy requests (no caching)
*
* @param \WP_REST_Request $request The request object.
* @return \WP_REST_Response|\WP_Error
*/
public function proxy_request( $request ) {
$endpoint = $request->get_param( 'endpoint' );
$method = $request->get_method();
$body = $request->get_json_params();
// Make the actual API request.
$result = $this->make_freemius_request( $method, $endpoint, $body );
if ( \is_wp_error( $result ) ) {
return $result;
}
// Clear related cache entries for write operations.
if ( in_array( $method, array( 'POST', 'PUT', 'DELETE' ), true ) ) {
$this->clear_related_cache( $endpoint );
}
return new \WP_REST_Response( $result['data'], $result['status'] );
}
/**
* Make request to Freemius API
*
* @param string $method HTTP method.
* @param string $endpoint API endpoint.
* @param array $data Request data.
* @return array|\WP_Error
*/
private function make_freemius_request( $method, $endpoint, $data = array() ) {
$settings = $this->get_api_settings();
if ( null === $settings ) {
return new \WP_Error(
'freemius_api_not_configured',
__( 'Freemius API is not configured. Please add your API token in the Freemius settings.', 'freemius' ),
array( 'status' => 500 )
);
}
try {
$endpoint = '/' . ltrim( $endpoint, '/' );
$token = $this->get_token_by_endpoint( $endpoint );
// fallback to global token if product token is not set
if ( ! $token && isset( $settings['token'] ) ) {
$token = $settings['token'];
}
if ( ! $token ) {
return new \WP_Error(
'freemius_api_not_configured',
__( 'Freemius API is not configured. Please add your API token in the Freemius settings.', 'freemius' ),
array( 'status' => 500 )
);
}
$plugin_data = get_plugin_data( FREEMIUS_PLUGIN_DIR . '/freemius.php' );
// Prepare request arguments.
$request_args = array(
'method' => strtoupper( $method ),
'timeout' => 30,
'headers' => array(
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
'User-Agent' => $plugin_data['Name'] . '/' . $plugin_data['Version'] . ';',
),
);
$url = $this->api_base_url . $endpoint;
if ( 'GET' === strtoupper( $method ) ) {
// For GET requests, add all parameters to URL.
$url = add_query_arg( $data, $url );
} elseif ( ! empty( $data ) ) {
// For other methods, add data to body.
$request_args['body'] = wp_json_encode( $data );
}
// check for dummy token for playground
if ( $token === $this->dummy_token ) {
$response = $this->get_dummy_response( $endpoint );
} else {
$response = wp_remote_request( $url, $request_args );
}
if ( is_wp_error( $response ) ) {
return new \WP_Error(
'freemius_api_request_failed',
$response->get_error_message(),
array( 'status' => 500 )
);
}
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
// Decode JSON response.
$decoded_response = json_decode( $response_body, true );
if ( null === $decoded_response ) {
return new \WP_Error(
'freemius_api_invalid_response',
__( 'Invalid JSON response from Freemius API.', 'freemius' ),
array( 'status' => 500 )
);
}
// Handle API errors.
if ( $response_code >= 400 ) {
$error_message = isset( $decoded_response['error']['message'] )
? $decoded_response['error']['message']
: __( 'Unknown Freemius API error.', 'freemius' );
return new \WP_Error(
'freemius_api_error',
$error_message,
array( 'status' => $response_code )
);
}
return array(
'data' => $decoded_response,
'status' => $response_code,
);
} catch ( \Exception $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
\error_log( 'Freemius API request error: ' . $e->getMessage() );
}
return new \WP_Error(
'freemius_api_exception',
$e->getMessage(),
array( 'status' => 500 )
);
}
}
/**
* Generate cache key for API requests
*
* @param string $method HTTP method.
* @param string $endpoint API endpoint.
* @param array $data Request data.
* @return string
*/
private function generate_cache_key( $method, $endpoint, $data = array() ) {
$key_data = array(
'method' => $method,
'endpoint' => $endpoint,
'data' => $data,
'settings' => $this->get_api_settings(), // include settings to invalidate cache when settings change
'seed' => 1234, // artificially change cache invalidation.
);
return 'freemius_api_' . md5( wp_json_encode( $key_data ) );
}
/**
* Clear related cache entries
*
* @param string $endpoint The endpoint that was modified (unused; clears all API transients).
*/
private function clear_related_cache( $endpoint ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
global $wpdb;
// Clear all transients that start with freemius_api_.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$transient_keys = $wpdb->get_col(
$wpdb->prepare(
"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
'_transient_freemius_api_%'
)
);
foreach ( $transient_keys as $transient_key ) {
$key = str_replace( '_transient_', '', $transient_key );
\delete_transient( $key );
}
}
/**
* Clear all API cache
*
* @param \WP_REST_Request $request The request object (unused; required by REST callback signature).
* @return \WP_REST_Response
*/
public function clear_cache( $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$this->clear_related_cache( '' );
return new \WP_REST_Response(
array( 'message' => __( 'Cache cleared successfully.', 'freemius' ) ),
200
);
}
/**
* Get token by endpoint
*
* @param string $endpoint API endpoint.
* @return string
*/
private function get_token_by_endpoint( $endpoint ) {
// extract product id from endpoint
$product_id = (int) preg_replace( '/(.*?)products\/(\d+)(.*)$/', '$2', $endpoint );
$products = get_option( 'freemius_products', array() );
foreach ( $products as $product ) {
if ( $product['product_id'] === $product_id ) {
return $product['token'];
}
}
return null;
}
/**
* Return dummy API data for playground environments.
*
* @param string $endpoint API endpoint path.
* @return array|null Dummy response body or null.
*/
private function get_dummy_response( string $endpoint ) {
$dummy = $this->load_dummy_response_data();
$body = null;
if ( substr( $endpoint, -strlen( '/currencies.json' ) ) === '/currencies.json' ) {
$body = $dummy['currencies'];
}
if ( substr( $endpoint, -strlen( '/pricing.json' ) ) === '/pricing.json' ) {
$body = $dummy['pricing'];
}
if ( substr( $endpoint, -strlen( '/coupons.json' ) ) === '/coupons.json' ) {
$body = $dummy['coupons'];
}
if ( substr( $endpoint, -strlen( '/products/19794.json' ) ) === '/products/19794.json' ) {
$body = $dummy['product'];
}
return array(
'response' => array(
'code' => 200,
'message' => 'OK',
),
'body' => $body,
'headers' => array(),
'cookies' => array(),
'http_response_code' => 200,
);
}
/**
* Load dummy response payloads once per request.
*
* @since 0.4.2
*
* @return array<string, string|null>
*/
private function load_dummy_response_data(): array {
static $data = null;
if ( null !== $data ) {
return $data;
}
include __DIR__ . '/dummy-response.php';
$data = array(
'pricing' => $pricing,
'currencies' => $currencies,
'product' => $product,
'coupons' => $coupons,
);
return $data;
}
}