PluginProbe
Datafeedr API / 1.0.124
Datafeedr API v1.0.124
1.4.2 1.0.125 1.0.13 1.0.14 1.0.15 1.0.16 1.0.17 1.0.18 1.0.19 1.0.2 1.0.20 1.0.21 1.0.22 1.0.23 1.0.24 1.0.25 1.0.26 1.0.27 1.0.28 1.0.29 1.0.3 1.0.30 1.0.31 1.0.32 1.0.33 All 181 releases
datafeedr-api / functions / functions.php

functions.php in Datafeedr API 1.0.124, at functions/functions.php

1,143 lines 35.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 function dfrapi_get_api_usage_percentage() {
4 $account = get_option( 'dfrapi_account' );
5 if ( $account ) {
6 if ( $account['max_requests'] > 0 ) {
7 $percentage = floor ( ( intval( $account['request_count'] ) / intval( $account['max_requests'] ) * 100 ) );
8 } else {
9 $percentage = 0;
10 }
11 return $percentage;
12 }
13 return false;
14 }
15
16 add_action( 'init', 'dfrapi_email_user_about_usage' );
17 function dfrapi_email_user_about_usage() {
18
19 $percentage = dfrapi_get_api_usage_percentage();
20 $status = get_option( 'dfrapi_account', array() );
21
22 $request_count = ( isset( $status['request_count'] ) ) ? abs( $status['request_count'] ) : 0;
23 $remaining_requests = ( isset( $status['max_requests'] ) ) ? abs( $status['max_requests'] - $request_count ) : 0;
24
25 $reset_date = '';
26 if ( isset( $status['bill_day'] ) ) {
27 $today = date('j');
28 $num_days = date('t');
29 if ( $status['bill_day'] > $num_days ) {
30 $bill_day = $num_days;
31 } else {
32 $bill_day = $status['bill_day'];
33 }
34 if ( $bill_day == 0 ) {
35 $reset_date .= '<em>' . __( 'Never', DFRAPI_DOMAIN ) . '</em>';
36 } elseif ( $today >= $bill_day ) {
37 $reset_date .= date('F', strtotime('+1 month')) . ' ' . $bill_day . ', ' . date('Y', strtotime('+1 month'));
38 } else {
39 $reset_date .= date('F') . ' ' . $bill_day . ', ' . date('Y');
40 }
41 }
42
43 $default = array(
44 '90_percent' => '',
45 '100_percent' => ''
46 );
47
48 // Don't do anything if less than 90%.
49 if ( $percentage < 90 ) {
50 update_option( 'dfrapi_usage_notification_tracker', $default );
51 return;
52 }
53
54 $tracker = get_option( 'dfrapi_usage_notification_tracker', $default );
55
56 $params = array();
57 $params['to'] = get_bloginfo( 'admin_email' );
58 $params['message'] = "<p>" . __( "This is an automated message generated by: ", DFRAPI_DOMAIN ) . get_bloginfo( 'wpurl' ) . "</p>";
59
60 if ( $percentage >= 100 && empty( $tracker['100_percent'] ) ) {
61
62 $params['subject'] = get_bloginfo( 'name' ) . __( ': Datafeedr API Usage (Critical)', DFRAPI_DOMAIN );
63
64 $params['message'] .= "<p>" . __( "You have used <strong>100%</strong> of your allocated Datafeedr API requests for this period. <u>You are no longer able to query the Datafeedr API to get product information.</u>", DFRAPI_DOMAIN ) . "</p>";
65 $params['message'] .= "<p><strong>" . __( "What to do next?", DFRAPI_DOMAIN ) . "</strong></p>";
66 $params['message'] .= "<p>" . __( "We strongly recommend that you upgrade to prevent your product information from becoming outdated.", DFRAPI_DOMAIN ) . "</p>";
67 $params['message'] .= "<p><a href=\"" . dfrapi_user_pages( 'change' ) . "?utm_source=email&utm_medium=link&utm_campaign=upgrade100percentnotice\"><strong>" . __( "UPGRADE NOW", DFRAPI_DOMAIN ) . "</strong></a></p>";
68 $params['message'] .= "<p>" . __( "Upgrading only takes a minute. You will have <strong>instant access</strong> to more API requests. Any remaining credit for your current plan will be applied to your new plan.", DFRAPI_DOMAIN ) . "</p>";
69 $params['message'] .= "<p>" . __( "You are under no obligation to upgrade. You may continue using your current plan for as long as you would like.", DFRAPI_DOMAIN ) . "</p>";
70 $params['message'] .= "<p>" . __( "If you have any questions about your account, please ", DFRAPI_DOMAIN );
71 $params['message'] .= "<a href=\"" . DFRAPI_EMAIL_US_URL . "?utm_source=email&utm_medium=link&utm_campaign=upgrade100percentnotice\">" . __( "contact us", DFRAPI_DOMAIN ) . "</a>.</p>";
72 $params['message'] .= "<p>" . __( "Thanks,<br />Eric &amp; Stefan<br />The Datafeedr Team", DFRAPI_DOMAIN ) . "</p>";
73 $params['message'] .= "<p>";
74 $params['message'] .= "<a href=\"" . admin_url( 'admin.php?page=dfrapi_account' ) . "\">" . __( "Account Information", DFRAPI_DOMAIN ) . "</a> | ";
75 $params['message'] .= "<a href=\"" . dfrapi_user_pages( 'change' ) . "?utm_source=email&utm_medium=link&utm_campaign=upgrade100percentnotice\">" . __( "Upgrade Account", DFRAPI_DOMAIN ) . "</a>";
76 $params['message'] .= "</p>";
77
78 $tracker['100_percent'] = 1;
79 update_option( 'dfrapi_usage_notification_tracker', $tracker );
80
81 add_filter( 'wp_mail_content_type', 'dfrapi_set_html_content_type' );
82 wp_mail( $params['to'], $params['subject'], $params['message'] );
83 remove_filter( 'wp_mail_content_type', 'dfrapi_set_html_content_type' );
84
85
86 } elseif ( $percentage >= 90 && $percentage < 100 && empty( $tracker['90_percent'] ) ) {
87
88 $params['subject'] = get_bloginfo( 'name' ) . __( ': Datafeedr API Usage (Warning)', DFRAPI_DOMAIN );
89 $params['message'] .= "<p>" . __( "You have used <strong>90%</strong> of your allocated Datafeedr API requests for this period.", DFRAPI_DOMAIN ) . "</p>";
90 $params['message'] .= "<p><strong>" . __( "API Usage", DFRAPI_DOMAIN ) . "</strong></p>";
91 $params['message'] .= "<ul>";
92 $params['message'] .= "<li>" . __( "API requests used: ", DFRAPI_DOMAIN ) . $request_count . "</li>";
93 $params['message'] .= "<li>" . __( "API requests remaining: ", DFRAPI_DOMAIN ) . $remaining_requests . "</li>";
94 $params['message'] .= "<li>" . __( "API requests will reset on: ", DFRAPI_DOMAIN ) . $reset_date . "</li>";
95 $params['message'] .= "</ul>";
96 $params['message'] .= "<p><strong>" . __( "What to do next?", DFRAPI_DOMAIN ) . "</strong></p>";
97 $params['message'] .= "<p>" . __( "We recommend that you upgrade to prevent your product information from becoming outdated.", DFRAPI_DOMAIN ) . "</p>";
98 $params['message'] .= "<p><a href=\"" . dfrapi_user_pages( 'change' ) . "?utm_source=email&utm_medium=link&utm_campaign=upgrade90percentnotice\"><strong>" . __( "UPGRADE NOW", DFRAPI_DOMAIN ) . "</strong></a></p>";
99 $params['message'] .= "<p>" . __( "Upgrading only takes a minute. You will have <strong>instant access</strong> to more API requests. Any remaining credit for your current plan will be applied to your new plan.", DFRAPI_DOMAIN ) . "</p>";
100 $params['message'] .= "<p>" . __( "You are under no obligation to upgrade. You may continue using your current plan for as long as you would like.", DFRAPI_DOMAIN ) . "</p>";
101 $params['message'] .= "<p>" . __( "If you have any questions about your account, please ", DFRAPI_DOMAIN );
102 $params['message'] .= "<a href=\"" . DFRAPI_EMAIL_US_URL . "?utm_source=email&utm_medium=link&utm_campaign=upgrade90percentnotice\">" . __( "contact us", DFRAPI_DOMAIN ) . "</a>.</p>";
103 $params['message'] .= "<p>" . __( "Thanks,<br />Eric &amp; Stefan<br />The Datafeedr Team", DFRAPI_DOMAIN ) . "</p>";
104 $params['message'] .= "<p>";
105 $params['message'] .= "<a href=\"" . admin_url( 'admin.php?page=dfrapi_account' ) . "\">" . __( "Account Information", DFRAPI_DOMAIN ) . "</a> | ";
106 $params['message'] .= "<a href=\"" . dfrapi_user_pages( 'change' ) . "?utm_source=email&utm_medium=link&utm_campaign=upgrade90percentnotice\">" . __( "Upgrade Account", DFRAPI_DOMAIN ) . "</a>";
107 $params['message'] .= "</p>";
108
109 $tracker['90_percent'] = 1;
110 update_option( 'dfrapi_usage_notification_tracker', $tracker );
111
112 add_filter( 'wp_mail_content_type', 'dfrapi_set_html_content_type' );
113 wp_mail( $params['to'], $params['subject'], $params['message'] );
114 remove_filter( 'wp_mail_content_type', 'dfrapi_set_html_content_type' );
115
116 }
117
118 return;
119 }
120
121 function dfrapi_set_html_content_type() {
122 return 'text/html';
123 }
124
125 /**
126 * Modify affiliate ID if product is a Zanox product.
127 * Replaces $affiliate_id with "zmid".
128 */
129 add_filter( 'dfrapi_affiliate_id', 'dfrapi_get_zanox_zmid', 10, 3 );
130 function dfrapi_get_zanox_zmid( $affiliate_id, $product, $networks ) {
131 if ( isset( $product['source'] ) && preg_match( "/\bZanox\b/", $product['source'] ) ) {
132 $zanox = dfrapi_api_get_zanox_zmid( $product['merchant_id'], $affiliate_id );
133 $affiliate_id = ( !isset( $zanox[0]['zmid']) ) ? '___MISSING___' : $zanox[0]['zmid'];
134 }
135 return $affiliate_id;
136 }
137
138 /**
139 * Modify affiliate ID if product is a Partnerize product.
140 * Replaces $affiliate_id with "camref".
141 *
142 * @since 1.0.66
143 *
144 * @return string Affiliate ID.
145 */
146 add_filter( 'dfrapi_affiliate_id', 'dfrapi_get_ph_camref', 10, 3 );
147 function dfrapi_get_ph_camref( $affiliate_id, $product, $networks ) {
148 if ( isset( $product['source'] ) && preg_match( "/\bPartnerize\b/", $product['source'] ) ) {
149 $ph = dfrapi_api_get_ph_camref( $product['merchant_id'] );
150 $affiliate_id = ( ! isset( $ph[0]['camref'] ) ) ? '___MISSING___' : $ph[0]['camref'];
151 }
152
153 return $affiliate_id;
154 }
155
156 /**
157 * Modify affiliate ID if product is a Effiliation product.
158 * Replaces $affiliate_id with "affiliate ID".
159 *
160 * @return string Affiliate ID.
161 * @since 1.0.81
162 *
163 */
164 function dfrapi_get_effiliation_affiliate_id( $affiliate_id, $product, $networks ) {
165 if ( isset( $product['source'] ) && preg_match( "/\bEffiliation\b/", $product['source'] ) ) {
166 $effiliation = dfrapi_api_get_effiliation_affiliate_id( $product['merchant_id'] );
167 $affiliate_id = $effiliation == 'dfrapi_unapproved_effiliation_merchant' ? '___MISSING___' : $effiliation;
168 }
169
170 return $affiliate_id;
171 }
172
173 add_filter( 'dfrapi_affiliate_id', 'dfrapi_get_effiliation_affiliate_id', 10, 3 );
174
175 function dfrapi_get_zanox_keys() {
176
177 $configuration = (array) get_option( 'dfrapi_configuration' );
178
179 $zanox_connection_key = false;
180 $zanox_secret_key = false;
181
182 if ( isset( $configuration['zanox_connection_key'] ) && ( $configuration['zanox_connection_key'] != '' ) ) {
183 $zanox_connection_key = $configuration['zanox_connection_key'];
184 }
185
186 if ( isset( $configuration['zanox_secret_key'] ) && ( $configuration['zanox_secret_key'] != '' ) ) {
187 $zanox_secret_key = $configuration['zanox_secret_key'];
188 }
189
190 if ( $zanox_connection_key && $zanox_secret_key ) {
191 return array(
192 'connection_key'=> $zanox_connection_key,
193 'secret_key' => $zanox_secret_key,
194 );
195 }
196
197 return false;
198 }
199
200 /**
201 * Get Partnerize Keys.
202 *
203 * @since 1.0.66
204 *
205 * @return array|bool Array of keys or false if they do not exist.
206 */
207 function dfrapi_get_ph_keys() {
208
209 $configuration = (array) get_option( 'dfrapi_configuration' );
210
211 $ph_application_key = false;
212 $ph_user_api_key = false;
213 $ph_publisher_id = false;
214
215 if ( isset( $configuration['ph_application_key'] ) && ( $configuration['ph_application_key'] != '' ) ) {
216 $ph_application_key = $configuration['ph_application_key'];
217 }
218
219 if ( isset( $configuration['ph_user_api_key'] ) && ( $configuration['ph_user_api_key'] != '' ) ) {
220 $ph_user_api_key = $configuration['ph_user_api_key'];
221 }
222
223 if ( isset( $configuration['ph_publisher_id'] ) && ( $configuration['ph_publisher_id'] != '' ) ) {
224 $ph_publisher_id = $configuration['ph_publisher_id'];
225 }
226
227 if ( $ph_application_key && $ph_user_api_key && $ph_publisher_id ) {
228 return array(
229 'application_key' => $ph_application_key,
230 'user_api_key' => $ph_user_api_key,
231 'publisher_id' => $ph_publisher_id,
232 );
233 }
234
235 return false;
236 }
237
238 /**
239 * Get Effiliation Keys.
240 *
241 * @since 1.0.81
242 *
243 * @return array|bool Array of keys or false if they do not exist.
244 */
245 function dfrapi_get_effiliation_keys() {
246
247 $configuration = (array) get_option( 'dfrapi_configuration' );
248
249 $effiliation_key = false;
250
251 if ( isset( $configuration['effiliation_key'] ) && ( $configuration['effiliation_key'] != '' ) ) {
252 $effiliation_key = $configuration['effiliation_key'];
253 }
254
255 if ( $effiliation_key ) {
256 return array(
257 'effiliation_key' => $effiliation_key,
258 );
259 }
260
261 return false;
262 }
263
264
265 /**
266 * Returns Amazon API key credentials if they exist.
267 *
268 * If the Amazon API keys such as the Access Key ID, Secret Access Key, Tracking ID and Locale all
269 * exists, then this function returns them in array format. Otherwise it returns false.
270 *
271 * @since 1.0.33
272 *
273 * @return array|bool Returns array of values if all values exist, otherwise false.
274 */
275 function dfrapi_get_amazon_keys() {
276
277 $configuration = (array) get_option( 'dfrapi_configuration' );
278
279 $amazon_access_key_id = false;
280 $amazon_secret_access_key = false;
281 $amazon_tracking_id = false;
282 $amazon_locale = false;
283
284 if ( isset( $configuration['amazon_access_key_id'] ) && ( $configuration['amazon_access_key_id'] != '' ) ) {
285 $amazon_access_key_id = $configuration['amazon_access_key_id'];
286 }
287
288 if ( isset( $configuration['amazon_secret_access_key'] ) && ( $configuration['amazon_secret_access_key'] != '' ) ) {
289 $amazon_secret_access_key = $configuration['amazon_secret_access_key'];
290 }
291
292 if ( isset( $configuration['amazon_tracking_id'] ) && ( $configuration['amazon_tracking_id'] != '' ) ) {
293 $amazon_tracking_id = $configuration['amazon_tracking_id'];
294 }
295
296 if ( isset( $configuration['amazon_locale'] ) && ( $configuration['amazon_locale'] != '' ) ) {
297 $amazon_locale = $configuration['amazon_locale'];
298 }
299
300 if ( $amazon_access_key_id && $amazon_secret_access_key && $amazon_tracking_id && $amazon_locale ) {
301 return array(
302 'amazon_access_key_id' => $amazon_access_key_id,
303 'amazon_secret_access_key' => $amazon_secret_access_key,
304 'amazon_tracking_id' => $amazon_tracking_id,
305 'amazon_locale' => $amazon_locale,
306 );
307 }
308
309 return false;
310 }
311
312 /**
313 * Returns a link to a user page on v4.datafeedr.com.
314 */
315 function dfrapi_user_pages( $page ) {
316
317 $pages = array(
318 'edit' => 'https://members.datafeedr.com/account',
319 'invoices' => 'https://members.datafeedr.com/invoices',
320 'billing' => 'https://members.datafeedr.com/billing',
321 'cancel' => 'https://members.datafeedr.com/',
322 'change' => 'https://members.datafeedr.com/subscription',
323 'signup' => 'https://members.datafeedr.com/subscribe',
324 'summary' => 'https://members.datafeedr.com/subscription',
325 'api' => 'https://members.datafeedr.com/api',
326 'factory' => 'https://members.datafeedr.com/factory',
327 );
328
329 return $pages[$page];
330 }
331
332 /**
333 * Adds option name to transient whitelist. This is so we know
334 * all transient options that can be deleted when deleting the
335 * API cache on Tools page.
336 */
337 function dfrapi_update_transient_whitelist( $option_name ) {
338 $whitelist = get_option( 'dfrapi_transient_whitelist', array() );
339 $whitelist[] = $option_name;
340 update_option( 'dfrapi_transient_whitelist', array_unique( $whitelist ) );
341 }
342
343 /**
344 * Add affiliate ID and tracking ID to an affiliate link.
345 *
346 * @param array $product An array of a single Datafeedr $product.
347 *
348 * @return string A URL with affiliate ID inserted or an empty string if the affiliate ID is missing.
349 */
350 function dfrapi_url( $product ) {
351
352 // Get all the user's selected networks.
353 $networks = (array) get_option( 'dfrapi_networks' );
354
355 // Support added for Amazon in version 1.0.60 (2017-10-18) Ticket #15201
356 if ( substr( $product['source'], 0, 6 ) === "Amazon" ) {
357 // Get the user's Amazon Associate Tag
358 $affiliate_id = dfrapi_get_amazon_associate_tag();
359 } else {
360 // Extract the affiliate ID from the $networks array.
361 $affiliate_id = isset( $networks['ids'][ $product['source_id'] ]['aid'] ) ? $networks['ids'][ $product['source_id'] ]['aid'] : '';
362 }
363
364 $affiliate_id = apply_filters( 'dfrapi_affiliate_id', $affiliate_id, $product, $networks );
365 $affiliate_id = trim( $affiliate_id );
366
367 // Extract the Tracking ID from the $networks array.
368 $tracking_id = ( isset( $networks['ids'][ $product['source_id'] ]['tid'] ) ) ? $networks['ids'][ $product['source_id'] ]['tid'] : '';
369 $tracking_id = apply_filters( 'dfrapi_tracking_id', $tracking_id, $product, $networks );
370 $tracking_id = trim( $tracking_id );
371
372 // Affiliate ID is missing. Do action and return empty string.
373 if ( $affiliate_id == '' ) {
374 do_action( 'dfrapi_affiliate_id_is_missing', $product );
375
376 return '';
377 }
378
379 // Determine which URL field to get: 'url' OR 'ref_url'. Return 'url' if $tracking_id is empty, otherwise, use 'ref_url'.
380 $url = ( $tracking_id !== '' && isset( $product['ref_url'] ) ) ? $product['ref_url'] : $product['url'];
381
382 // Apply filters to URL before affiliate & tracking ID insertion.
383 $url = apply_filters( 'dfrapi_before_affiliate_id_insertion', $url, $product, $affiliate_id );
384 $url = apply_filters( 'dfrapi_before_tracking_id_insertion', $url, $product, $tracking_id );
385
386 // Replace placeholders in URL.
387 $placeholders = array( "@@@", "###" );
388 $replacements = array( $affiliate_id, $tracking_id );
389 $url = str_replace( $placeholders, $replacements, $url );
390
391 // Apply filters to URL after affiliate & tracking ID insertion.
392 $url = apply_filters( 'dfrapi_after_affiliate_id_insertion', $url, $product, $affiliate_id );
393 $url = apply_filters( 'dfrapi_after_tracking_id_insertion', $url, $product, $tracking_id );
394
395 // Return URL
396 return $url;
397 }
398
399 /**
400 * Return Amazon Associate Tag (ie. Tracking ID).
401 *
402 * @since 1.0.60
403 *
404 * @return string Associate Tag or empty string if it does not exist.
405 */
406 function dfrapi_get_amazon_associate_tag() {
407 $config = get_option( 'dfrapi_configuration' );
408
409 return ( isset( $config['amazon_tracking_id'] ) ) ? $config['amazon_tracking_id'] : '';
410 }
411
412 /**
413 * Add affiliate ID to impression URL.
414 *
415 * Since 1.0.39
416 *
417 * @param $product - An array of a single's product's information.
418 */
419 function dfrapi_impression_url( $product ) {
420
421 $impression_url = ( isset( $product['impressionurl'] ) ) ? trim( $product['impressionurl'] ) : false;
422
423 if ( ! $impression_url ) {
424 return '';
425 }
426
427 // Get all the user's selected networks.
428 $networks = (array) get_option( 'dfrapi_networks' );
429
430 // Extract the affiliate ID from the $networks array.
431 $affiliate_id = $networks['ids'][ $product['source_id'] ]['aid'];
432 $affiliate_id = apply_filters( 'dfrapi_affiliate_id', $affiliate_id, $product, $networks );
433 $affiliate_id = trim( $affiliate_id );
434
435 // Affiliate ID is missing. Do action and return empty string.
436 if ( $affiliate_id == '' ) {
437 do_action( 'dfrapi_affiliate_id_is_missing_impression', $product );
438
439 return '';
440 }
441
442 // Apply filters to URL before affiliate & tracking ID insertion.
443 $impression_url = apply_filters( 'dfrapi_before_affiliate_id_insertion_impression', $impression_url, $product, $affiliate_id );
444
445 // Replace placeholders in URL.
446 $placeholders = array( "@@@" );
447 $replacements = array( $affiliate_id );
448 $impression_url = str_replace( $placeholders, $replacements, $impression_url );
449
450 // Apply filters to URL after affiliate & tracking ID insertion.
451 $impression_url = apply_filters( 'dfrapi_after_affiliate_id_insertion_impression', $impression_url, $product, $affiliate_id );
452
453 // Return URL
454 return $impression_url;
455 }
456
457 /**
458 * Output an error message generated by the API.
459 */
460 function dfrapi_output_api_error( $data ) {
461 $error = @$data['dfrapi_api_error'];
462 $params = @$data['dfrapi_api_error']['params'];
463 ?>
464 <div class="dfrapi_api_error">
465 <div class="dfrapi_head"><?php _e( 'Datafeedr API Error', DFRAPI_DOMAIN ); ?></div>
466 <div class="dfrapi_msg"><strong><?php _e( 'Message:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['msg']; ?></div>
467 <div class="dfrapi_code"><strong><?php _e( 'Code:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['code']; ?></div>
468 <div class="dfrapi_class"><strong><?php _e( 'Class:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['class']; ?></div>
469 <?php if ( is_array( $params ) ) : ?>
470 <div class="dfrps_query"><strong><?php _e( 'Query:', DFRAPI_DOMAIN ); ?></strong> <span><?php echo dfrapi_display_api_request( $params ); ?></span></div>
471 <?php endif; ?>
472 </div>
473 <?php
474 }
475
476 /**
477 * Convert a currency code to sign. USD => $
478 *
479 * @https://github.com/pelle/bux/blob/master/src/bux/currencies.clj
480 *
481 * Currently supported currencies:
482 *
483 * AUD Australia &#36;
484 * BRL Brazil R$
485 * CAD Canada &#36;
486 * CHF Switzerland Fr
487 * DKK Denmark kr
488 * EUR Belgium &euro;
489 * EUR Finland &euro;
490 * EUR France &euro;
491 * EUR Germany &euro;
492 * EUR Ireland &euro;
493 * EUR Italy &euro;
494 * EUR Netherlands &euro;
495 * EUR Spain &euro;
496 * GBP United Kingdom &pound;
497 * HUF Hungary Fr
498 * INR India &#8377;
499 * MYR Malaysia RM
500 * NOK Norway kr
501 * NZD New Zealand &#36;
502 * PHP Philippines &#8369;
503 * PLN Poland zł
504 * RON Romania L
505 * RUB Russia ₽
506 * SEK Sweden kr
507 * TRY Turkey &#8356;
508 * USD United States &#36;
509 *
510 */
511 function dfrapi_currency_code_to_sign( $code ) {
512
513 $map = array(
514 'AUD' => '&#36;',
515 'BRL' => 'R$',
516 'CAD' => '&#36;',
517 'CHF' => 'Fr',
518 'DKK' => 'kr',
519 'EUR' => '&euro;',
520 'GBP' => '&pound;',
521 'HUF' => 'Ft',
522 'INR' => '&#8377;',
523 'MYR' => 'RM',
524 'NOK' => 'kr',
525 'NZD' => '&#36;',
526 'PLN' => 'zł',
527 'PHP' => '&#8369;',
528 'RON' => 'L',
529 'RUB' => '&#8381;',
530 'SEK' => 'kr',
531 'TRY' => '&#8356;',
532 'USD' => '&#36;',
533 'CZK' => '&#75;&#269;',
534 );
535
536 $map = apply_filters( 'dfrapi_currency_sign_mapper', $map );
537
538 if ( isset ( $map[$code] ) ) {
539 return $map[$code];
540 } else {
541 return $map['USD'];
542 }
543 }
544
545 /**
546 * This displays the API request in PHP format.
547 */
548 function dfrapi_display_api_request( $params=array() ) {
549
550 $html = '';
551
552 if ( empty( $params ) ) { return $html; }
553
554 $html .= '$search = $api->searchRequest();<br />';
555 foreach ( $params as $k => $v ) {
556
557 // Handle query.
558 if ( $k == 'query' ) {
559 foreach ( $v as $query ) {
560 if ( substr( $query, 0, 9 ) !== 'source_id' || substr( $query, 0, 11 ) !== 'merchant_id' ) {
561 $query = str_replace( ",", ", ", $query );
562 }
563 $html .= '$search->addFilter( \''.( $query ).'\' );<br />';
564 }
565 }
566
567 // Handle sort.
568 if ( $k == 'sort' ) {
569 foreach ( $v as $sort ) {
570 $html .= '$search->addSort( \''.stripslashes( $sort ).'\' );<br />';
571 }
572 }
573
574 // Handle limit.
575 if ( $k == 'limit' ) {
576 $html .= '$search->setLimit( \''.stripslashes( $v ).'\' );<br />';
577 }
578
579 // Handle merchant_limit.
580 if ( $k == 'merchant_limit' ) {
581 $html .= '$search->setMerchantLimit( \''.stripslashes( absint($v) ).'\' );<br />';
582 }
583
584 // Handle Offset.
585 if ( $k == 'offset' ) {
586 $html .= '$search->setOffset( \''.stripslashes( $v ).'\' );<br />';
587 }
588
589 // Handle Exclude duplicates.
590 if ( $k == 'exclude_duplicates' ) {
591 $html .= '$search->excludeDuplicates( \''. $v . '\' );<br />';
592 }
593 }
594
595 $html .= '$products = $search->execute();';
596 return $html;
597
598 }
599
600 function dfrapi_get_query_param( $query, $param ) {
601 if ( is_array( $query ) && !empty( $query ) ) {
602 foreach( $query as $k => $v ) {
603 if ( $v['field'] == $param ) {
604 return array(
605 'field' => @$v['field'],
606 'operator' => @$v['operator'],
607 'value' => @$v['value'],
608 );
609 }
610 }
611 }
612 return false;
613 }
614
615 /**
616 * Converts a value in cents into a value with proper
617 * decimal placement.
618 *
619 * Example: 14999 => 149.99
620 */
621 function dfrapi_int_to_price( $price ) {
622 return number_format( ( $price/100 ), 2 );
623 }
624
625 /**
626 * Converts decimal or none decimal prices into values in cents.
627 *
628 * assert(dfrapi_price_to_int('123') ==12300);
629 * assert(dfrapi_price_to_int('123.4') ==12340);
630 * assert(dfrapi_price_to_int('1234.56') ==123456);
631 * assert(dfrapi_price_to_int('123,4') ==12340);
632 * assert(dfrapi_price_to_int('1234,56') ==123456);
633 * assert(dfrapi_price_to_int('1,234,567') ==123456700);
634 * assert(dfrapi_price_to_int('1,234,567.8') ==123456780);
635 * assert(dfrapi_price_to_int('1,234,567.89') ==123456789);
636 * assert(dfrapi_price_to_int('1.234.567') ==123456700);
637 * assert(dfrapi_price_to_int('1.234.567,8') ==123456780);
638 * assert(dfrapi_price_to_int('1.234.567,89') ==123456789);
639 * assert(dfrapi_price_to_int('FOO 123 BAR') ==12300);
640 */
641 function dfrapi_price_to_int( $price ) {
642 $d = $price;
643 $d = preg_replace('~^[^\d.,]+~', '', $d);
644 $d = preg_replace('~[^\d.,]+$~', '', $d);
645
646 // 123 => 12300
647 if(preg_match('~^(\d+)$~', $d, $m))
648 return intval($m[1] . '00');
649
650 // 123.4 => 12340, 123,45 => 12345
651 if(preg_match('~^(\d+)[.,](\d{1,2})$~', $d, $m))
652 return intval($m[1] . substr($m[2] . '0000', 0, 2));
653
654 // 1,234,567.89 => 123456789
655 if(preg_match('~^((?:\d{1,3})(?:,\d{3})*)(\.\d{1,2})?$~', $d, $m)) {
656 $f = isset($m[2]) ? $m[2] : '.';
657 return intval(str_replace(',', '', $m[1]) . substr($f . '0000', 1, 2));
658 }
659
660 // 1.234.567,89 => 123456789
661 if(preg_match('~^((?:\d{1,3})(?:\.\d{3})*)(,\d{1,2})?$~', $d, $m)) {
662 $f = isset($m[2]) ? $m[2] : '.';
663 return intval(str_replace('.', '', $m[1]) . substr($f . '0000', 1, 2));
664 }
665
666 return NULL;
667 }
668
669 function dfrapi_html_output_api_error( $data ) {
670 $error = $data['dfrapi_api_error'];
671 $params = @$data['dfrapi_api_error']['params'];
672 ?>
673 <div class="dfrapi_api_error">
674 <div class="dfrapi_head"><?php _e( 'Datafeedr API Error', DFRAPI_DOMAIN ); ?></div>
675 <div class="dfrapi_msg"><strong><?php _e( 'Message:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['msg']; ?></div>
676 <div class="dfrapi_code"><strong><?php _e( 'Code:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['code']; ?></div>
677 <div class="dfrapi_class"><strong><?php _e( 'Class:', DFRAPI_DOMAIN ); ?></strong> <?php echo $error['class']; ?></div>
678 <?php if ( is_array( $params ) ) : ?>
679 <div class="dfrapi_query"><strong><?php _e( 'Query:', DFRAPI_DOMAIN ); ?></strong> <span><?php echo dfrapi_helper_display_api_request( $params ); ?></span></div>
680 <?php endif; ?>
681 </div>
682 <?php
683 }
684
685 function dfrapi_get_total_products_in_db( $formatted=TRUE, $default=0 ) {
686
687 $account = get_option( 'dfrapi_account' );
688 $product_count = $default;
689
690 if ( $account ) {
691 if ( isset( $account['product_count'] ) ) {
692 $product_count = intval( $account['product_count'] );
693 }
694 }
695
696 if ( $formatted && is_int( $product_count ) ) {
697 $product_count = number_format( $product_count );
698 }
699
700 return $product_count;
701 }
702
703 /**
704 * Imports an image from a URL into the WordPress Media Library.
705 *
706 * @since 1.0.71
707 *
708 * @param string $url Image URL.
709 * @param array $args Optional. An array of options. See Datafeedr_Image_Importer::default_args()
710 *
711 * @return Datafeedr_Image_Importer
712 */
713 function datafeedr_import_image( $url, $args = array() ) {
714 return ( new Datafeedr_Image_Importer( $url, $args ) )->import();
715 }
716
717 /**
718 * Returns true if the $string starts with one of the $patterns. Otherwise returns false.
719 *
720 * @since 1.0.78
721 *
722 * @param string $string The haystack.
723 * @param string|array $patterns The patterns to search for in the beginning of the $string.
724 *
725 * @return bool True if string starts with the pattern(s) else returns false.
726 */
727 function dfrapi_string_starts_with( $string, $patterns ) {
728 $patterns = ( is_string( $patterns ) ) ? array( $patterns ) : $patterns;
729 foreach ( $patterns as $pattern ) {
730 $length = mb_strlen( $pattern );
731 if ( mb_substr( $string, 0, $length ) === $pattern ) {
732 return true;
733 }
734 }
735
736 return false;
737 }
738
739 /**
740 * Includes HelpScout Beacon if enabled and if on a Datafeedr-specific page.
741 *
742 * @since 1.0.84
743 */
744 function dfrapi_include_helpscout_beacon() {
745
746 $options = get_option( 'dfrapi_configuration', [] );
747
748 if ( isset( $options['hs_beacon'] ) && 'off' == $options['hs_beacon'] ) {
749 return;
750 }
751
752 if ( ! dfrapi_is_datafeedr_admin_page() ) {
753 return;
754 }
755
756 include_once DFRAPI_PATH . 'js/helpscout-beacon.php';
757
758 return;
759 }
760
761 add_action( 'admin_footer', 'dfrapi_include_helpscout_beacon' );
762
763 /**
764 * Returns true if we are viewing a Datafeedr-specific page in the WordPress Admin Area.
765 *
766 * @global $pagenow
767 *
768 * @since 1.0.84
769 *
770 * @return bool
771 */
772 function dfrapi_is_datafeedr_admin_page() {
773
774 /**
775 * For post edit pages (ie. post.php?post=1&action=edit).
776 */
777 $post_types = [
778 'datafeedr-productset',
779 ];
780
781 /**
782 * For $_GET params (ie. admin.php?page=dfrps_configuration).
783 */
784 $params = [
785 'page' => [
786 'dfrapi',
787 'dfrapi_networks',
788 'dfrapi_merchants',
789 'dfrapi_tools',
790 'dfrapi_export',
791 'dfrapi_import',
792 'dfrapi_account',
793 'dfrcs_options',
794 'dfrps_configuration',
795 'dfrps_tools',
796 'dfrpswc_options',
797 ],
798 'post_type' => [
799 'datafeedr-productset'
800 ]
801 ];
802
803 foreach ( $params as $k => $v ) {
804 if ( isset( $_GET[ $k ] ) && in_array( $_GET[ $k ], $v ) ) {
805 return true;
806 }
807 }
808
809 global $pagenow;
810
811 if ( 'post.php' === $pagenow && in_array( get_post_type(), $post_types ) ) {
812 return true;
813 }
814
815 return false;
816 }
817
818 /**
819 * @param integer $network_id
820 * @param string $id_type
821 *
822 * @return WP_Error|string
823 */
824 function dfrapi_get_affiliate_and_tracking_id( $network_id, $id_type = 'aid' ) {
825
826 static $networks = null;
827
828 $key = 'ids';
829 $type = ( 'tid' == $id_type ) ? 'tid' : 'aid';
830
831 if ( null === $networks ) {
832 $networks = get_option( 'dfrapi_networks', [] );
833 }
834
835 if ( empty( $networks ) ) {
836 return new WP_Error(
837 'dfrapi_get_affiliate_id_no_networks',
838 __( 'No networks selected.', 'datafeedr-api' )
839 );
840 }
841
842 if ( ! isset( $networks[ $key ] ) ) {
843 return new WP_Error(
844 'dfrapi_get_affiliate_id_no_network_ids',
845 __( 'No network IDs selected.', 'datafeedr-api' )
846 );
847 }
848
849 if ( ! isset( $networks[ $key ][ $network_id ] ) ) {
850 return new WP_Error(
851 'dfrapi_get_affiliate_id_no_network_ids',
852 __( 'No data for network with ID of ' . intval( $network_id ), 'datafeedr-api' )
853 );
854 }
855
856 if ( ! isset( $networks[ $key ][ $network_id ][ $type ] ) || empty( $networks[ $key ][ $network_id ][ $type ] ) ) {
857 return new WP_Error(
858 'dfrapi_get_affiliate_id_empty_type',
859 __( 'No affiliate or tracking ID entered for network with ID of ' . intval( $network_id ), 'datafeedr-api' )
860 );
861 }
862
863 return $networks[ $key ][ $network_id ][ $type ];
864 }
865
866 /**
867 * @param array $merchants
868 * @param array $network
869 *
870 * @return array|WP_Error|null
871 */
872 function dfrapi_remove_unapproved_awin_merchants( $merchants, $network ) {
873
874 // Return if not in Awin network.
875 if ( 10006 != $network['group_id'] ) {
876 return $merchants;
877 }
878
879 $affiliate_id = dfrapi_get_affiliate_and_tracking_id( $network['_id'], 'aid' );
880
881 if ( is_wp_error( $affiliate_id ) ) {
882 return new WP_Error(
883 'missing_awin_affiliate_id',
884 'Please enter your Awin affiliate ID for ' . esc_html( $network['name'] ) . ' <a href="' . admin_url( 'admin.php?page=dfrapi_networks' ) . '#group_affiliatewindow" target="_blank">here</a>.'
885 );
886 }
887
888 static $awin_access_token = null;
889
890 if ( null === $awin_access_token ) {
891
892 $config = get_option( 'dfrapi_configuration', [] );
893
894 $awin_access_token = ( isset( $config['awin_access_token'] ) && ! empty( $config['awin_access_token'] ) ) ?
895 trim( $config['awin_access_token'] ) :
896 new WP_Error(
897 'awin_access_token_missing',
898 'Please enter your Awin API Token <a href="' . admin_url( 'admin.php?page=dfrapi' ) . '" target="_blank">here</a>.'
899 );
900 }
901
902 if ( is_wp_error( $awin_access_token ) ) {
903 return $awin_access_token;
904 }
905
906 $url = null;
907 $approved_program_ids = null;
908
909 $url = sprintf(
910 'https://api.awin.com/publishers/%1$s/programmes?relationship=joined&accessToken=%2$s',
911 $affiliate_id, $awin_access_token
912 );
913
914 $response = wp_remote_get( $url );
915
916 if ( is_array( $response ) && ! is_wp_error( $response ) ) {
917 if ( isset( $response['response']['code'] ) && '200' == $response['response']['code'] ) {
918 if ( isset( $response['body'] ) ) {
919 $programs = json_decode( $response['body'], true );
920 $approved_program_ids = wp_list_pluck( $programs, 'id' );
921 }
922 }
923 }
924
925 if ( null === $approved_program_ids ) {
926 return new WP_Error(
927 'unable_to_retrieve_approved_awin_program_ids',
928 'Unable to get your list of joined ' . esc_html( $network['name'] ) . ' programs. Please ensure your Awin Access Token is correct <a href="' . admin_url( 'admin.php?page=dfrapi' ) . '" target="_blank">here</a> and your affiliate ID is correct <a href="' . admin_url( 'admin.php?page=dfrapi_networks' ) . '#group_affiliatewindow" target="_blank">here</a>.' );
929 }
930
931 foreach ( $merchants as $key => $merchant ) {
932
933 $approved = false;
934 $suids = isset( $merchant['suids'] ) ? explode( ',', $merchant['suids'] ) : [];
935
936 foreach ( $suids as $suid ) {
937 if ( in_array( $suid, $approved_program_ids ) ) {
938 $approved = true;
939 }
940 }
941
942 if ( ! $approved ) {
943 unset( $merchants[ $key ] );
944 }
945 }
946
947 return $merchants;
948 }
949
950 add_filter( 'dfrapi_list_merchants', 'dfrapi_remove_unapproved_awin_merchants', 10, 2 );
951
952 /**
953 * @param array $merchants
954 * @param array $network
955 *
956 * @return array|WP_Error|null
957 * @since 1.0.102
958 */
959 function dfrapi_disable_affiliate_gateway_merchant_selection_when_sid_empty( $merchants, $network ) {
960
961 // Return if not in The Affiliate Gateway network.
962 if ( 10033 != $network['group_id'] ) {
963 return $merchants;
964 }
965
966 $sid = dfrapi_get_affiliate_gateway_sid();
967
968 if ( is_wp_error( $sid ) ) {
969 return $sid;
970 }
971
972 return $merchants;
973 }
974
975 add_filter( 'dfrapi_list_merchants', 'dfrapi_disable_affiliate_gateway_merchant_selection_when_sid_empty', 10, 2 );
976
977 /**
978 * Get The Affiliate Gateway SID from this page WordPress Admin Area > Datafeedr API > Configuration
979 *
980 * @return string|WP_Error
981 * @since 1.0.102
982 */
983 function dfrapi_get_affiliate_gateway_sid() {
984
985 static $sid = null;
986
987 if ( null === $sid ) {
988
989 $config = get_option( 'dfrapi_configuration', [] );
990
991 $sid = ( isset( $config['affiliate_gateway_sid'] ) && ! empty( $config['affiliate_gateway_sid'] ) ) ?
992 trim( $config['affiliate_gateway_sid'] ) :
993 new WP_Error(
994 'missing_affiliate_gateway_sid',
995 'Please enter your The Affiliate Gateway SID <a href="' . admin_url( 'admin.php?page=dfrapi' ) . '" target="_blank">here</a>.'
996 );
997 }
998
999 return $sid;
1000 }
1001
1002 /**
1003 * Insert SID into The Affiliate Gateway affiliate links.
1004 *
1005 * @param string $url
1006 * @param array $product
1007 * @param string $tracking_id
1008 *
1009 * @return string
1010 */
1011 function dfrapi_insert_affiliate_gateway_sid_into_affiliate_link( $url, $product, $tracking_id ) {
1012
1013 if ( $product['source'] != 'The Affiliate Gateway' ) {
1014 return $url;
1015 }
1016
1017 $sid = dfrapi_get_affiliate_gateway_sid();
1018
1019 if ( is_wp_error( $sid ) ) {
1020 return $url;
1021 }
1022
1023 $url = str_replace( '{SID}', $sid, $url );
1024
1025 return $url;
1026 }
1027
1028 add_filter( 'dfrapi_after_tracking_id_insertion', 'dfrapi_insert_affiliate_gateway_sid_into_affiliate_link', 20, 3 );
1029
1030 /**
1031 * @param array $merchants
1032 * @param array $network
1033 *
1034 * @return array|WP_Error|null
1035 * @since 1.0.124
1036 */
1037 function dfrapi_disable_belboon_merchant_selection_when_aid_empty( $merchants, $network ) {
1038
1039 // Return if not in Belboon network.
1040 if ( 10007 != $network['group_id'] ) {
1041 return $merchants;
1042 }
1043
1044 $aid = dfrapi_get_belboon_adspace_id();
1045
1046 if ( is_wp_error( $aid ) ) {
1047 return $aid;
1048 }
1049
1050 return $merchants;
1051 }
1052
1053 add_filter( 'dfrapi_list_merchants', 'dfrapi_disable_belboon_merchant_selection_when_aid_empty', 10, 2 );
1054
1055 /**
1056 * Get Belboon Adspace ID from this page WordPress Admin Area > Datafeedr API > Configuration
1057 *
1058 * @return string|WP_Error
1059 * @since 1.0.124
1060 */
1061 function dfrapi_get_belboon_adspace_id() {
1062
1063 static $aid = null;
1064
1065 if ( null === $aid ) {
1066
1067 $config = get_option( 'dfrapi_configuration', [] );
1068
1069 $aid = ( isset( $config['belboon_aid'] ) && ! empty( $config['belboon_aid'] ) ) ?
1070 trim( $config['belboon_aid'] ) :
1071 new WP_Error(
1072 'missing_belboon_aid',
1073 'Please enter your Belboon Adspace ID <a href="' . admin_url( 'admin.php?page=dfrapi' ) . '" target="_blank">here</a>.'
1074 );
1075 }
1076
1077 return $aid;
1078 }
1079
1080 /**
1081 * Insert Adspace ID into Belboon affiliate links.
1082 *
1083 * @param string $url
1084 * @param array $product
1085 * @param string $affiliate_id
1086 *
1087 * @return string
1088 * @since 1.0.124
1089 */
1090 function dfrapi_insert_belboon_adspace_id_into_affiliate_link( $url, $product, $affiliate_id ) {
1091
1092 if ( strpos( $product['source'], 'Belboon' ) === false ) {
1093 return $url;
1094 }
1095
1096 $aid = dfrapi_get_belboon_adspace_id();
1097
1098 if ( is_wp_error( $aid ) ) {
1099 return $url;
1100 }
1101
1102 $url = str_replace( '{AID}', $aid, $url );
1103
1104 return $url;
1105 }
1106
1107 add_filter( 'dfrapi_before_affiliate_id_insertion', 'dfrapi_insert_belboon_adspace_id_into_affiliate_link', 20, 3 );
1108
1109 /**
1110 * @param string $url
1111 * @param string $method
1112 * @param array $args
1113 *
1114 * @return SimpleXMLElement|WP_Error
1115 */
1116 function dfrapi_get_xml_response( $url, $method = 'GET', array $args = [] ) {
1117
1118 $response = $method === 'GET' ? wp_remote_get( $url, $args ) : wp_remote_post( $url, $args );
1119
1120 if ( is_wp_error( $response ) ) {
1121 return $response;
1122 }
1123
1124 $code = wp_remote_retrieve_response_code( $response );
1125 $body = wp_remote_retrieve_body( $response );
1126
1127 if ( $code < 200 || $code >= 300 ) {
1128 return new WP_Error( $code, strip_tags( $body ) );
1129 }
1130
1131 if ( ! strlen( $body ) ) {
1132 return new WP_Error( 'connection_error', esc_html__( 'Empty response', 'datafeedr' ) );
1133 }
1134
1135 $xml = simplexml_load_string( $body, null, LIBXML_NOCDATA );
1136
1137 if ( $xml->getName() == 'error' ) {
1138 return new WP_Error( $code, esc_html( strval( $xml->message ) ) );
1139 }
1140
1141 return $xml;
1142 }
1143