-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathamazonjs.php
1235 lines (1117 loc) · 45 KB
/
amazonjs.php
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: AmazonJS
Plugin URI: http://wordpress.org/extend/plugins/amazonjs/
Description: Easy to use interface to add an amazon product to your post and display it by using jQuery template.
Author: makoto_kw
Version: 0.10
Author URI: https://makotokw.com
Requires at least: 3.4
Tested up to: 5.2.5
License: GPLv2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: amazonjs
Domain Path: /languages
*/
/*
AmazonJS depends on
jQuery tmpl
PEAR Services_JSON: Michal Migurski <[email protected]>
*/
// @codingStandardsIgnoreStart
require_once dirname( __FILE__ ) . '/lib/json.php';
require_once dirname( __FILE__ ) . '/lib/Amazon/AwsV4.php';
require_once dirname( __FILE__ ) . '/lib/Amazon/PaApiClientV5.php';
require_once dirname( __FILE__ ) . '/amazonjs-item-fixer.php';
class Amazonjs
{
const VERSION = '0.10';
const AWS_VERSION = '2013-08-01';
const CACHE_LIFETIME = 86400;
public $title;
public $url;
public $option_page_url;
public $plugin_dir;
public $plugin_rel_file;
public $option_page_name;
public $option_name;
public $setting_sections;
public $setting_fields;
public $default_settings;
public $settings;
public $text_domain;
public $media_type = 'amazonjs';
public $countries;
public $search_indexes;
public $display_items = array();
public $simple_template;
function __construct() {
$path = __FILE__;
$dir = dirname( $path );
$slug = basename( $dir );
$this->title = 'AmazonJS';
$this->plugin_dir = $dir;
$this->plugin_rel_file = basename( $dir ) . DIRECTORY_SEPARATOR . basename( $path );
$this->option_page_name = basename( $dir );
$this->option_name = preg_replace( '/[\-\.]/', '_', $this->option_page_name ) . '_settings';
$this->url = plugins_url( '', $path );
$this->option_page_url = admin_url() . 'options-general.php?page=' . $this->option_page_name;
$this->text_domain = $slug;
if ( get_locale() == 'ja' ) {
add_filter( 'load_textdomain_mofile', array( $this, 'load_textdomain_mofile' ), 10, 2 );
}
load_plugin_textdomain( $this->text_domain, false, dirname( $this->plugin_rel_file ) . '/languages' );
$this->countries = array(
'US' => array(
'label' => __( 'United States', $this->text_domain ),
'domain' => 'Amazon.com',
'baseUri' => 'https://webservices.amazon.com',
'linkTemplate' => '<iframe src="https://rcm.amazon.com/e/cm?t=${t}&o=1&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-20',
'region' => 'us-east-1',
),
'UK' => array(
'label' => __( 'United Kingdom', $this->text_domain ),
'domain' => 'Amazon.co.uk',
'baseUri' => 'https://webservices.amazon.co.uk',
'linkTemplate' => '<iframe src="https://rcm-uk.amazon.co.uk/e/cm?t=${t}&o=2&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-21',
'region' => 'eu-west-1',
),
'DE' => array(
'label' => __( 'Deutschland', $this->text_domain ),
'domain' => 'Amazon.de',
'baseUri' => 'https://webservices.amazon.de',
'linkTemplate' => '<iframe src="https://rcm-de.amazon.de/e/cm?t=${t}&o=3&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '04-21',
'region' => 'eu-west-1',
),
'FR' => array(
'label' => __( 'France', $this->text_domain ),
'domain' => 'Amazon.fr',
'baseUri' => 'https://webservices.amazon.fr',
'linkTemplate' => '<iframe src="https://rcm-fr.amazon.fr/e/cm?t=${t}&o=8&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '09-21',
'region' => 'eu-west-1',
),
'JP' => array(
'label' => __( 'Japan', $this->text_domain ),
'domain' => 'Amazon.co.jp',
'baseUri' => 'https://webservices.amazon.co.jp',
'linkTemplate' => '<iframe src="https://rcm-jp.amazon.co.jp/e/cm?t=${t}&o=9&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-22',
'region' => 'us-west-2',
),
'CA' => array(
'label' => __( 'Canada', $this->text_domain ),
'domain' => 'Amazon.ca',
'baseUri' => 'https://webservices.amazon.ca',
'linkTemplate' => '<iframe src="https://rcm-ca.amazon.ca/e/cm?t=${t}&o=15&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '0c-20',
'region' => 'us-east-1',
),
'CN' => array(
'label' => __( 'China', $this->text_domain ),
'domain' => 'Amazon.cn',
'baseUri' => 'https://webservices.amazon.cn',
'linkTemplate' => '<iframe src="https://rcm-cn.amazon.cn/e/cm?t=${t}&o=28&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-23',
'region' => 'us-west-2',
),
'IT' => array(
'label' => __( 'Italia', $this->text_domain ),
'domain' => 'Amazon.it',
'baseUri' => 'https://webservices.amazon.it',
'linkTemplate' => '<iframe src="https://rcm-it.amazon.it/e/cm?t=${t}&o=29&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-21',
'region' => 'eu-west-1',
),
'ES' => array(
'label' => __( 'España', $this->text_domain ),
'domain' => 'Amazon.es',
'baseUri' => 'https://webservices.amazon.es',
'linkTemplate' => '<iframe src="https://rcm-es.amazon.es/e/cm?t=${t}&o=30&p=8&l=as1&asins=${asins}&fc1=${fc1}&IS2=${IS2}<1=${lt1}&m=amazon&lc1=${lc1}&bc1=${bc1}&bg1=${bg1}&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>',
'associateTagSuffix' => '-21',
'region' => 'eu-west-1',
),
);
}
function init() {
$this->init_settings();
if ( is_admin() ) {
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_action( 'admin_init', array( $this, 'admin_init' ) );
add_action( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );
}
if ( ! is_admin() ) {
add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_styles' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );
add_action( 'wp_footer', array( $this, 'wp_enqueue_scripts_for_footer' ), 1 );
}
add_shortcode( 'amazonjs', array( $this, 'shortcode' ) );
}
function load_textdomain_mofile( $mofile, $domain ) {
if ( $this->text_domain === $domain ) {
if ( strpos( $mofile, 'languages/plugins/amazonjs-ja.mo' ) !== false ) {
return $this->plugin_dir . '/languages/amazonjs-ja.mo';
}
}
return $mofile;
}
function admin_init() {
add_action( 'media_buttons', array( $this, 'media_buttons' ), 20 );
add_action( 'media_upload_amazonjs', array( $this, 'media_upload_amazonjs' ) );
add_action( 'media_upload_amazonjs_keyword', array( $this, 'media_upload_amazonjs_keyword' ) );
add_action( 'media_upload_amazonjs_id', array( $this, 'media_upload_amazonjs_id' ) );
add_action( 'wp_ajax_amazonjs_search', array( $this, 'ajax_amazonjs_search' ) );
add_action( 'admin_notices', array( $this, 'admin_notices' ) );
$page = $this->option_page_name;
register_setting( $this->option_name, $this->option_name, array( $this, 'validate_settings' ) );
if ( $this->setting_sections ) {
foreach ( $this->setting_sections as $key => $section ) {
add_settings_section( $page . '_' . $key, $section['label'], array( $this, $section['add'] ), $page );
}
}
foreach ( $this->setting_fields as $key => $field ) {
$label = ('checkbox' == $field['type']) ? '' : $field['label'];
add_settings_field(
$this->option_name . '_' . $key,
$label,
array( $this, 'add_settings_field' ),
$page,
$page . '_' . $field['section'],
array( $key, $field )
);
}
$gutenberg = false;
if ( version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' ) ) {
$gutenberg = true;
if ( function_exists( 'use_block_editor_for_post_type' )
&& ! use_block_editor_for_post_type( 'post' ) ) {
// block editor is disabled
$gutenberg = false;
}
}
if ( $gutenberg ) {
add_filter( 'mce_buttons', array( $this, 'mce_buttons' ) );
add_filter( 'mce_external_plugins', array( $this, 'mce_external_plugins' ) );
wp_register_script( 'amazonjs_admin', $this->url . '/js/admin.js' );
$admin_vars = array(
'mce' => array(
'buttonTitle' => __( 'Add Amazon Link', $this->text_domain ),
'dialogTitle' => __( 'Add Amazon Link', $this->text_domain ),
'dialogUrl' => get_bloginfo( 'wpurl' ) . '/wp-admin/media-upload.php?post_id=0&type=amazonjs&tab=amazonjs_keyword'
)
);
wp_localize_script( 'amazonjs_admin', 'amazonjsAdmin', $admin_vars );
wp_enqueue_script( 'amazonjs_admin' );
}
}
function mce_buttons( $buttons ) {
array_push( $buttons, 'amazonjs' );
return $buttons;
}
function mce_external_plugins( $plugin_array ) {
$plugin_array['amazonjs'] = $this->url .'/js/tinymce-plugin.js';
return $plugin_array;
}
function admin_print_styles() {
global $wp_version;
// use dashicon
if ( version_compare( $wp_version, '3.8', '>=' ) ) {
wp_enqueue_style( 'amazonjs-options', $this->url . '/css/amazonjs-options.css', array(), self::VERSION );
}
}
function wp_enqueue_styles() {
if ( $this->settings['displayCustomerReview'] ) {
wp_enqueue_style( 'thickbox' );
}
if ( $this->settings['overrideThemeCss'] ) {
wp_enqueue_style( 'amazonjs', $this->url . '/css/amazonjs-force.css', array(), self::VERSION );
} else {
wp_enqueue_style( 'amazonjs', $this->url . '/css/amazonjs.css', array(), self::VERSION );
}
if ( $this->settings['customCss'] ) {
$theme_version = wp_get_theme()->get( 'Version' );
wp_enqueue_style( 'amazonjs-custom', get_stylesheet_directory_uri() . '/amazonjs.css', array(), $theme_version );
}
}
function wp_enqueue_scripts() {
wp_register_script( 'jquery-tmpl', $this->url . '/components/js/jquery-tmpl/jquery.tmpl.min.js', array( 'jquery' ), '1.0.0pre', true );
$depends = array( 'jquery-tmpl' );
if ( $this->settings['displayCustomerReview'] ) {
$depends[] = 'thickbox';
}
wp_register_script( 'amazonjs', $this->url . '/js/amazonjs.js', $depends, self::VERSION, true );
if ( $this->settings['customJs'] ) {
wp_register_script( 'amazonjs-custom', get_stylesheet_directory_uri() . '/amazonjs.js', array( 'amazonjs' ), self::VERSION, true );
}
}
function wp_enqueue_scripts_for_footer() {
$country_codes = array();
$items = array();
foreach ( $this->display_items as $country_code => $sub_items ) {
foreach ( $this->fetch_items( $country_code, $sub_items ) as $asin => $item ) {
$items[ $country_code . ':' . $asin ] = $item;
}
$country_codes[] = $country_code;
}
if ( count( $items ) == 0 ) {
return;
}
$this->enqueue_amazonjs_scripts( $items, $country_codes );
}
function enqueue_amazonjs_scripts( $items = array(), $country_codes = array() ) {
$wpurl = get_bloginfo( 'wpurl' );
$region = array();
foreach ( $this->countries as $code => $value ) {
if ( in_array( $code, $country_codes ) ) {
foreach ( array( 'linkTemplate' ) as $attr ) {
$region[ 'Link' . $code ] = $this->tmpl( $value[ $attr ], array( 't' => $this->settings[ 'associateTag' . $code ] ) );
}
}
}
$amazonVars = array(
'thickboxUrl' => $wpurl . '/wp-includes/js/thickbox/',
'regionTemplate' => $region,
'resource' => array(
'BookAuthor' => __( 'Author', $this->text_domain ),
'BookPublicationDate' => __( 'PublicationDate', $this->text_domain ),
'BookPublisher' => __( 'Publisher', $this->text_domain ),
'NumberOfPagesValue' => __( '${NumberOfPages} pages', $this->text_domain ),
'ListPrice' => __( 'List Price', $this->text_domain ),
'Price' => __( 'Price', $this->text_domain ),
'PriceUsage' => __( 'Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [amazon.com or endless.com, as applicable] at the time of purchase will apply to the purchase of this product.', $this->text_domain ),
'PublicationDate' => __( 'Publication Date', $this->text_domain ),
'ReleaseDate' => __( 'Release Date', $this->text_domain ),
'SalesRank' => __( 'SalesRank', $this->text_domain ),
'SalesRankValue' => __( '#${SalesRank}', $this->text_domain ),
'RunningTime' => __( 'Run Time', $this->text_domain ),
'RunningTimeValue' => __( '${RunningTime} minutes', $this->text_domain ),
'CustomerReviewTitle' => __( '${Title} Customer Review', $this->text_domain ),
'SeeCustomerReviews' => __( 'See Customer Reviews', $this->text_domain ),
'PriceUpdatedat' => __( '(at ${UpdatedDate})', $this->text_domain ),
),
'isCustomerReviewEnabled' => ($this->settings['displayCustomerReview']) ? true : false,
'isTrackEventEnabled' => ($this->settings['useTrackEvent']) ? true : false,
'isFadeInEnabled' => ($this->settings['useAnimation']) ? true : false,
'items' => array_values( $items ),
);
wp_localize_script( 'amazonjs', 'amazonjsVars', $amazonVars );
wp_enqueue_script( 'amazonjs' );
if ( $this->settings['customJs'] ) {
wp_enqueue_script( 'amazonjs-custom' );
}
}
function init_settings() {
// section
$this->setting_sections = array(
'api' => array(
'label' => __( 'Product Advertising API settings', $this->text_domain ),
'add' => 'add_api_setting_section',
),
'associate' => array(
'label' => __( 'Amazon Associates settings', $this->text_domain ),
'add' => 'add_associate_setting_section',
),
'appearance' => array(
'label' => __( 'Appearance settings', $this->text_domain ),
'add' => 'add_appearance_setting_section',
),
'analytics' => array(
'label' => __( 'Analytics settings', $this->text_domain ),
'add' => 'add_analytics_setting_section',
),
'customize' => array(
'label' => __( 'Customize', $this->text_domain ),
'add' => 'add_customize_setting_section',
),
);
// filed
$template_url = get_bloginfo( 'template_url' );
$this->setting_fields = array(
'accessKeyId' => array(
'label' => __( 'Access Key ID', $this->text_domain ),
'type' => 'text',
'size' => 60,
'section' => 'api',
),
'secretAccessKey' => array(
'label' => __( 'Secret Access Key', $this->text_domain ),
'type' => 'text',
'size' => 60,
'section' => 'api',
),
'displayCustomerReview' => array(
'label' => __( 'Display customer review', $this->text_domain ),
'type' => 'checkbox',
'section' => 'appearance',
'description' => __( "AmazonJS will display customer review by using WordPress's Thickbox.", $this->text_domain ),
),
'useAnimation' => array(
'label' => __( 'Use fadeIn animation', $this->text_domain ),
'type' => 'checkbox',
'section' => 'appearance',
),
'overrideThemeCss' => array(
'label' => __( 'Override style of theme', $this->text_domain ),
'type' => 'checkbox',
'section' => 'appearance',
'description' => __( 'If set to true, AmazonJS will override the style of the theme by using <code>!important</code> declaration.', $this->text_domain ),
),
'useShortItemUrl' => array(
'label' => __( 'Use short item url', $this->text_domain ),
'type' => 'checkbox',
'section' => 'appearance',
'description' => __( "AmazonJS will remove a product title from an item url.", $this->text_domain ),
),
'supportDisabledJavascript' => array(
'label' => __( 'Uf set to true, display an official widget instead javascript code', $this->text_domain ),
'type' => 'checkbox',
'section' => 'appearance',
'description' => __( 'If set to true, AmazonJS will output html by using <code><script type="text/javascript">document.write("{$indicator_html}")</script><noscript>{$link_html}</noscript></code>.', $this->text_domain ),
),
'useTrackEvent' => array(
'label' => __( 'Click Tracking by using Google Analytics', $this->text_domain ),
'type' => 'checkbox',
'section' => 'analytics',
'description' => __( 'If set to true, AmazonJS will call <code>_gaq.push(["_trackEvent", "AmazonJS", "Click", "ASIN TITLE"])</code> or <code>ga("send", "event", "AmazonJS", "Click", "ASIN TITLE")</code>.', $this->text_domain ),
),
'customCss' => array(
'label' => __( 'Use Custom Css', $this->text_domain ),
'type' => 'checkbox',
'section' => 'customize',
'description' => '(' . $template_url . '/amazonjs.css)',
),
'customJs' => array(
'label' => __( 'Use Custom Javascript', $this->text_domain ),
'type' => 'checkbox',
'section' => 'customize',
'description' => '(' . $template_url . '/amazonjs.js)',
),
);
foreach ( $this->countries as $key => $value ) {
$this->setting_fields[ 'associateTag' . $key ] = array(
'label' => __( $value['domain'], $this->text_domain ),
'type' => 'text',
'size' => 30,
'placeholder' => 'associatetag' . $value['associateTagSuffix'],
'section' => 'associate',
);
}
$this->default_settings = array();
if ( is_array( $this->setting_fields ) ) {
foreach ( $this->setting_fields as $key => $field ) {
$this->default_settings[ $key ] = @$field['defaults'];
}
}
//delete_option($this->option_name);
$this->settings = wp_parse_args( (array) get_option( $this->option_name ), $this->default_settings );
}
function delete_settings() {
delete_option( $this->option_name );
}
function validate_settings( $settings ) {
foreach ( $this->setting_fields as $key => $field ) {
if ( 'checkbox' == $field['type'] ) {
$settings[ $key ] = ( 'on' == @$settings[ $key ] || '1' == @$settings[ $key ] );
}
}
foreach ( array( 'accessKeyId', 'secretAccessKey' ) as $key ) {
$settings[ $key ] = trim( $settings[ $key ] );
}
foreach ( $this->countries as $country_code => $value ) {
$key = 'associateTag' . $country_code;
$settings[ $key ] = trim( $settings[ $key ] );
}
return $settings;
}
function admin_menu() {
if ( function_exists( 'add_options_page' ) ) {
$page_hook_suffix = add_options_page(
__( $this->title, $this->text_domain ),
__( $this->title, $this->text_domain ),
'manage_options',
$this->option_page_name,
array( $this, 'options_page' )
);
add_action( 'admin_print_styles-' . $page_hook_suffix, array( $this, 'admin_print_styles' ) );
}
}
function get_amazon_official_link( $asin, $country_code ) {
$tmpl = $this->countries[ $country_code ]['linkTemplate'];
$item = array(
't' => $this->settings[ 'associateTag' . $country_code ],
'asins' => $asin,
'fc1' => '000000',
'lc1' => '0000FF',
'bc1' => '000000',
'bg1' => 'FFFFFF',
'IS2' => 1,
'lt1' => '_blank',
'f' => 'ifr',
'm' => 'amazon',
);
return $this->tmpl( $tmpl, $item );
}
function shortcode( $atts, /** @noinspection PhpUnusedParameterInspection */ $content ) {
/**
* @var string $asin
* @var string $tmpl
* @var string $locale
* @var string $title
* @var string $imgsize
*/
$defaults = array( 'asin' => '', 'tmpl' => '', 'locale' => $this->default_country_code(), 'title' => '', 'imgsize' => '' );
extract( shortcode_atts( $defaults, $atts ) );
if ( empty($asin) ) {
return '';
}
$country_code = strtoupper( $locale );
$imgsize = strtolower( $imgsize );
if ( is_feed() ) {
// use static html for rss reader
if ( $ai = $this->get_item( $country_code, $asin ) ) {
$aimg = $ai['SmallImage'];
if ( array_key_exists( 'MediumImage', $ai ) ) {
$aimg = $ai['MediumImage'];
}
return <<<EOF
<a href="{$ai['DetailPageURL']}" title="{$ai['Title']}" target="_blank">
<img src="{$aimg['src']}" width="{$aimg['width']}" height="{$aimg['height']}" alt="{$ai['Title']}"/>
{$ai['Title']}
</a>
EOF;
}
return $this->get_amazon_official_link( $asin, $country_code );
}
if ( ! isset($this->display_items[ $country_code ]) ) {
$this->display_items[ $country_code ] = array();
}
$item = (array_key_exists( $asin, $this->display_items[ $country_code ] ))
? $this->display_items[ $country_code ][ $asin ]
: $this->display_items[ $country_code ][ $asin ] = $this->get_cached_item( $country_code, $asin );
$url = '#';
if ( is_array( $item ) && array_key_exists( 'DetailPageURL', $item ) ) {
$url = $item['DetailPageURL'];
}
$indicator_html = <<<EOF
<div data-role="amazonjs" data-asin="{$asin}" data-locale="{$country_code}" data-tmpl="${tmpl}" data-img-size="${imgsize}" class="asin_{$asin}_{$country_code}_${tmpl} amazonjs_item"><div class="amazonjs_indicator"><span class="amazonjs_indicator_img"></span><a class="amazonjs_indicator_title" href="{$url}">{$title}</a><span class="amazonjs_indicator_footer"></span></div></div>
EOF;
$indicator_html = trim( $indicator_html );
if ( ! $this->settings['supportDisabledJavascript'] ) {
return $indicator_html;
}
$indicator_html = addslashes( $indicator_html );
$link_html = $this->get_amazon_official_link( $asin, $country_code );
return <<<EOF
<script type="text/javascript">document.write("{$indicator_html}")</script><noscript>{$link_html}</noscript>
EOF;
}
function wp_locale_to_amazon_locale() {
switch ( get_locale() ) {
case 'en_CA':
return 'CA';
case 'de_DE':
return 'DE';
case 'fr_FR':
return 'FR';
case 'ja':
return 'JP';
case 'en_GB':
return 'UK';
case 'zh_CN':
return 'CN';
case 'it_IT':
return 'IT';
case 'es_ES':
return 'ES';
}
return 'US';
}
/**
* Gets default country code by get_locale
* @return string
*/
function default_country_code() {
$locale = $this->wp_locale_to_amazon_locale();
if ( isset( $this->settings[ 'associateTag' . $locale ] ) && ! empty( $this->settings[ 'associateTag' . $locale ] ) ) {
return $locale;
}
// search
foreach ( $this->countries as $code => $value ) {
if ( isset( $this->settings[ 'associateTag' . $code ] ) && ! empty( $this->settings[ 'associateTag' . $code ] ) ) {
return $code;
}
}
return $locale;
}
function delete_cache() {
global $wpdb;
if ( !empty( $wpdb ) && $wpdb instanceof wpdb ) {
$flag = $wpdb->suppress_errors;
$wpdb->suppress_errors( true );
$result = $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '\_site\_transient\_%amazonjs\_%'");
$wpdb->suppress_errors( $flag );
return $result !== false;
}
return false;
}
function get_cached_item( $country_code, $asin ) {
if ( $cached_item = get_site_transient( "amazonjs_{$country_code}_{$asin}" ) ) {
return $cached_item;
}
return null;
}
function get_item( $country_code, $asin ) {
if ( $cached_item = $this->get_cached_item( $country_code, $asin ) ) {
return $cached_item;
}
$items = $this->fetch_items( $country_code, array( $asin => false ) );
return @$items[ $asin ];
}
/**
* @param string $country_code
* @param array $items
* @return array
*/
function fetch_items( $country_code, $items ) {
$now = time();
$item_ids = array();
foreach ( $items as $asin => $item ) {
if ( ! $item && $item['UpdatedAt'] + 86400 < $now ) {
$item_ids[] = $asin;
}
}
while ( count( $item_ids ) ) {
// fetch via 10 products
// ItemLookup ItemId: Must be a valid item ID. For more than one ID, use a comma-separated list of up to ten IDs.
$itemid = implode( ',', array_splice( $item_ids, 0, 10 ) );
$results = $this->itemlookup( $country_code, $itemid );
if ( $results && $results['success'] ) {
foreach ( $results['items'] as $item ) {
$items[ $item['ASIN'] ] = $item;
set_site_transient("amazonjs_{$country_code}_{$item['ASIN']}", $item, self::CACHE_LIFETIME);
}
}
}
return $items;
}
function tmpl( $tmpl, $item ) {
$s = $tmpl;
foreach ( $item as $key => $value ) {
$s = str_replace( '${' . $key . '}', $value, $s );
}
return $s;
}
function plugin_row_meta( $links, $file ) {
if ( $file == $this->plugin_rel_file ) {
array_push(
$links,
sprintf( '<a href="%s">%s</a>', $this->option_page_url, __( 'Settings' ) )
);
array_push(
$links,
sprintf( '<a href="https://github.com/makotokw/wp-amazonjs/releases" target="_blank">%s</a>', __( 'Old Releases', $this->text_domain ) )
);
}
return $links;
}
/** @noinspection PhpUnused */
function add_api_setting_section() {
?>
<p><?php _e( 'This plugin uses the Amazon Product Advertising API in order to get product infomation. Thus, you must use your Access Key ID & Secret Access Key.', $this->text_domain ); ?></p>
<p><?php _e( 'You can sign up the Amazon Product Advertising API from <a href="https://affiliate-program.amazon.com/gp/advertising/api/detail/main.html" target="_blank">here</a>. Please review the <a href="http://affiliate-program.amazon.com/gp/advertising/api/detail/agreement.html" target="_blank">Product Advertising API License Agreement</a> for details.', $this->text_domain ) ?></p>
<?php
}
/** @noinspection PhpUnused */
function add_associate_setting_section() {
?>
<p><?php _e( 'Amazon has an affiliate program called Amazon Associates. To apply for the Associates Program, visit the <a href="https://affiliate-program.amazon.com/" target="_blank">Amazon Associates website</a> for details.', $this->text_domain ); ?></p>
<p><?php _e( 'Associate Tag has been a <strong>required and verified</strong> input parameter in all requests to the Amazon Product Advertising API since 11/1/2011.', $this->text_domain ) ?></p>
<?php
}
/** @noinspection PhpUnused */
function add_appearance_setting_section() {
}
/** @noinspection PhpUnused */
function add_analytics_setting_section() {
}
/** @noinspection PhpUnused */
function add_customize_setting_section() {
}
function add_settings_field( $args = array() ) {
// not work wordpress 2.9.0 #11143
if ( empty($args) ) {
return;
}
list ($key, $field) = $args;
$id = $this->option_name . '_' . $key;
$name = $this->option_name . "[{$key}]";
$value = $this->settings[ $key ];
if ( isset($field['html']) ) {
echo '' . $field['html'] . '';
} else {
switch ( $field['type'] ) {
case 'checkbox':
?>
<input id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>" type="checkbox" <?php checked( true, $value ); ?> value="1" />
<label for="<?php echo esc_attr( $id ); ?>"><?php echo esc_html( $field['label'] ); ?></label>
<?php
break;
case 'radio':
$index = 1;
foreach ( $field['options'] as $v => $content ) {
$input_element_id = $id . '_' . $index;
?>
<input id="<?php echo esc_attr( $input_element_id ); ?>" name="<?php echo esc_attr( $name ); ?>" type="radio" <?php checked( $v, $value ); ?> value="<?php echo esc_attr( $v ); ?>" />
<label for="<?php echo esc_attr( $input_element_id ); ?>"><?php echo esc_html( $content ); ?></label>
<?php
$index++;
}
break;
case 'select':
?>
<select id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>">
<?php foreach ( $field['options'] as $option => $name ) : ?>
<option value="<?php echo esc_attr( $option ); ?>" <?php selected( $option, $value ); ?>><?php echo esc_html( $name ); ?></option>
<?php endforeach ?>
</select>
<?php
break;
case 'text':
default:
$size = @$field['size'];
$placeholder = @$field['placeholder'];
if ( $size <= 0 ) {
$size = 40;
}
if ( ! is_string( $placeholder ) ) {
$placeholder = '';
}
?>
<input id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>" type="text" size="<?php echo esc_attr( $size ); ?>" value="<?php echo esc_attr( $value ); ?>" placeholder="<?php echo esc_attr( $placeholder ); ?>"/>
<?php
break;
}
}
if ( @$field['description'] ) {
echo '<p class="description">' . $field['description'] . '</p>';
}
}
/**
* @return bool
*/
function is_page_amazonjs_options() {
global $pagenow;
return ( 'options-general.php' == $pagenow && isset($_GET['page']) && $this->option_page_name == $_GET['page'] );
}
function admin_notices() {
// https://wordpress.org/support/topic/how-to-use-settings-api-and-print-custom-validation-errors?replies=3
if ( $this->is_page_amazonjs_options() ) {
if ( (isset($_GET['updated']) && 'true' == $_GET['updated']) || (isset($_GET['settings-updated']) && 'true' == $_GET['settings-updated']) ) {
// Validate keys
if ( !empty($this->settings['accessKeyId']) && !empty($this->settings['secretAccessKey']) ) {
$results = $this->itemsearch( $this->default_country_code(), null, 'WordPress' );
if ( is_array( $results ) && isset($results['error_code']) ) {
switch ( $results['error_code'] ) {
case 'InvalidClientTokenId':
add_settings_error( 'general', 'settings_updated', __( 'The Access Key ID may be invalid', $this->text_domain ) . ' (' . $results['error_code'] . ')', 'error' );
break;
case 'SignatureDoesNotMatch':
add_settings_error( 'general', 'settings_updated', __( 'The Secret Access Key may be invalid', $this->text_domain ). ' (' . $results['error_code'] . ')', 'error' );
break;
}
}
}
}
if ( isset( $_POST['action'] ) && $_POST['action'] === 'amazonjs_delete_cache' ) {
if ( $this->delete_cache() ) {
add_settings_error( 'general', 'settings_updated', __( 'The Caches are deleted', $this->text_domain ), 'updated' );
}
}
}
}
function media_buttons() {
global $post_ID, $temp_ID;
$iframe_ID = (int) ( 0 == $post_ID ? $temp_ID : $post_ID );
$iframe_src = 'media-upload.php?post_id=' . $iframe_ID . '&type=' . $this->media_type . '&tab=' . $this->media_type . '_keyword';
$label = __( 'Add Amazon Link', $this->text_domain );
?>
<a href="<?php echo esc_attr( $iframe_src . '&TB_iframe=true' ); ?>" id="add_amazon" class="button thickbox" title="<?php echo esc_attr( $label ); ?>"><img src="<?php echo esc_attr( $this->url . '/images/amazon-icon.png' ); ?>" alt="<?php echo esc_attr( $label ); ?>"/></a>
<?php
}
function media_upload_init() {
add_action( 'admin_print_styles', array( $this, 'wp_enqueue_styles' ) );
$this->wp_enqueue_scripts();
wp_enqueue_style( 'amazonjs-media-upload', $this->url . '/css/media-upload-type-amazonjs.css', array( 'amazonjs' ), self::VERSION );
$this->enqueue_amazonjs_scripts();
}
function media_upload_amazonjs() {
$this->media_upload_init();
wp_iframe( 'media_upload_type_amazonjs' );
}
function media_upload_amazonjs_keyword() {
$this->media_upload_init();
wp_iframe( 'media_upload_type_amazonjs_keyword' );
}
function media_upload_amazonjs_id() {
$this->media_upload_init();
wp_iframe( 'media_upload_type_amazonjs_id' );
}
function media_upload_tabs( /** @noinspection PhpUnusedParameterInspection */$tabs ) {
return array(
$this->media_type . '_keyword' => __( 'Keyword Search', $this->text_domain ),
$this->media_type . '_id' => __( 'Search by ASIN/URL', $this->text_domain ),
);
}
function options_page() {
?>
<div class="wrap wrap-amazonjs">
<h2><?php echo esc_html( $this->title ); ?></h2>
<?php $this->options_page_header(); ?>
<!--suppress HtmlUnknownTarget -->
<form action="options.php" method="post">
<?php settings_fields( $this->option_name ); ?>
<?php do_settings_sections( $this->option_page_name ); ?>
<?php submit_button(); ?>
</form>
<form action="<?php echo $_SERVER["REQUEST_URI"] ?>" method="post">
<input type="hidden" name="action" value="amazonjs_delete_cache"/>
<?php submit_button( __( 'Delete Cache', $this->text_domain ), 'secondary', 'amazonjs_delete_cache' ); ?>
</form>
</div>
<?php
}
function options_page_header() {
?>
<?php if ( ! function_exists( 'simplexml_load_string' ) ) : ?>
<div class="error">
<p><?php printf( __( 'Error! "simplexml_load_string" function is not found. %s requires PHP 5 and SimpleXML extension.', $this->text_domain ), $this->title ); ?></p>
</div>
<?php endif ?>
<?php
}
/**
* parse ASIN from URL
* @param string $url
* @return bool|string
*/
static function parse_asin( $url ) {
if ( preg_match( '/^https?:\/\/.+\.amazon\.([^\/]+).+\/(dp|gp\/product|ASIN)\/([^\/]+)/', $url, $matches ) ) {
return $matches[3];
}
return null;
}
function ajax_amazonjs_search() {
$itemId = null;
// from http get
$itemPage = @$_GET['ItemPage'];
$id = @$_GET['ID'];
$keywords = @$_GET['Keywords'];
$searchIndex = @$_GET['SearchIndex'];
$countryCode = @$_GET['CountryCode'];
if ( ! empty($id) ) {
if ( preg_match( '/^https?:\/\//', $id ) ) {
if ( $asin = self::parse_asin( $id ) ) {
$itemId = $asin;
} else {
// url string as query keyword
$keywords = $id;
}
} else {
$itemId = $id;
}
} else if ( ! empty($keywords) ) {
if ( preg_match( '/^https?:\/\//', $keywords ) ) {
if ( $asin = self::parse_asin( $keywords ) ) {
$itemId = $asin;
}
}
}
$amazonjs = new Amazonjs();
$amazonjs->init();
if ( isset($itemId) ) {
$result = $amazonjs->itemlookup( $countryCode, $itemId );
die(json_encode( $result ));
} else {
$result = $amazonjs->itemsearch( $countryCode, $searchIndex, $keywords, $itemPage );
die(json_encode( $result ));
}
}
// amazon api
function itemlookup( $countryCode, $itemId ) {
$options = array();
$options['ItemId'] = $itemId;
$options['Operation'] = 'ItemLookup';
return $this->amazon_get( $countryCode, $options );
}
// amazon api
function itemsearch( $countryCode, $searchIndex, $keywords, $itemPage = 0 ) {
$options = array();
if ( $itemPage > 0 ) {
$options['ItemPage'] = $itemPage;
}
$options['Keywords'] = $keywords;
$options['Operation'] = 'ItemSearch';
$options['SearchIndex'] = null;
if ( !empty($searchIndex) ) {
$options['SearchIndex'] = $searchIndex;
}
return $this->amazon_get( $countryCode, $options );
}
function amazon_get( $countryCode, $options ) {
return $this->amazon_get_v5( $countryCode, $options );
}
function amazon_get_v5( $countryCode, $options ) {
try {
$baseUri = $this->countries[ $countryCode ]['baseUri'];
$region = $this->countries[ $countryCode ]['region'];
$accessKeyId = @trim( $this->settings['accessKeyId'] );
$secretAccessKey = @trim( $this->settings['secretAccessKey'] );
$associateTag = @$this->settings[ 'associateTag' . $countryCode ];
// validate request
if ( empty( $countryCode ) || ( empty( $options['ItemId'] ) && empty( $options['Keywords'] ) ) || ( empty( $accessKeyId ) || empty( $secretAccessKey ) ) ) {
throw new Exception( __( 'Invalid Request Parameters', $this->text_domain ) );
}
$client = new Amazonjs_Amazon_PaApiClientV5( $accessKeyId, $secretAccessKey, $associateTag, $baseUri, $region, $this->text_domain );
if ( $options['Operation'] == 'ItemLookup' ) {
$result = $client->lookup( explode( ',', $options['ItemId'] ) );
} else {
$result = $client->search( $options['SearchIndex'], $options['Keywords'], $options['ItemPage'] );
}
if ( isset( $result['items'] ) ) {
$fetchedAt = time();
$fixed_items = array();
foreach ( $result['items'] as $item ) {
Amazonjs_Itemfixer::fixed_item( $item );
$item['CountryCode'] = $countryCode;
$item['UpdatedAt'] = $fetchedAt;
$fixed_items[] = $item;
}
$result['items'] = $fixed_items;
}
} catch (Exception $e) {
$result = array( 'success' => false, 'message' => $e->getMessage() );
}
if ( self::is_debug() ) {
if ( isset( $result ) && ! $result['success'] ) {
error_log( var_export( array( 'options' => $options, 'result' => $result ), true ) );
}
}
return $result;
}
/** @noinspection PhpUnused */
function amazon_get_v4( $countryCode, $options ) {
$baseUri = $this->countries[ $countryCode ]['baseUri'];
$accessKeyId = @trim( $this->settings['accessKeyId'] );