· 9 years ago · Oct 18, 2016, 10:28 AM
1<?php
2/*
3 Plugin Name: Rakuten API plugin
4 Plugin URI: mechanical-pie.com
5 Description: Plugin to query Rakuten API and display results
6 Version: 0.1
7 Author: mechanical-pie
8
9 */
10if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
11require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
12
13add_action( 'admin_menu', 'wpra_add_admin_menu' );
14add_action( 'admin_init', 'wpra_settings_init' );
15
16function wpra_add_admin_menu( ) {
17 add_options_page( 'Rakuten API ', 'Rakuten API ', 'manage_options', 'rakuten_api_', 'wpra_options_page' );
18}
19
20function wpra_settings_init( ) {
21 register_setting( 'pluginPage', 'wpra_settings' );
22 add_settings_section(
23 'wpra_pluginPage_section',
24 __( 'Your section description', 'rakuten_api_plugin' ),
25 'wpra_settings_section_callback',
26 'pluginPage'
27 );
28 add_settings_field(
29 'wpra_checkbox_logging',
30 __( 'Logging enabled', 'rakuten_api_plugin' ),
31 'wpra_checkbox_logging_render',
32 'pluginPage',
33 'wpra_pluginPage_section'
34 );
35 add_settings_field(
36 'wpra_text_field_1',
37 __( 'Settings field description', 'rakuten_api_plugin' ),
38 'wpra_text_field_1_render',
39 'pluginPage',
40 'wpra_pluginPage_section'
41 );
42}
43
44
45function wpra_checkbox_logging_render( ) {
46 $options = get_option( 'wpra_settings' );
47 ?>
48 <input name='wpra_settings[wpra_checkbox_logging]' value="0" type="hidden">
49 <input type='checkbox' name='wpra_settings[wpra_checkbox_logging]' <?php checked( $options['wpra_checkbox_logging'], 1 ); ?> value='1'>
50 <?php
51}
52
53function wpra_text_field_1_render( ) {
54 $options = get_option( 'wpra_settings' );
55 ?>
56 <input type='text' name='wpra_settings[wpra_text_field_1]' value='<?php echo $options['wpra_text_field_1']; ?>'>
57 <?php
58}
59
60function wpra_settings_section_callback( ) {
61 echo __( 'Rakuten API plugin settings', 'rakuten_api_plugin' );
62
63}
64
65function wpra_options_page( ) {
66 ?>
67 <form action='options.php' method='post'>
68 <h2>Rakuten API </h2>
69 <?php
70 settings_fields( 'pluginPage' );
71 do_settings_sections( 'pluginPage' );
72 submit_button();
73 ?>
74 </form>
75 <?php
76}
77
78//class declaration start
79class rakuten_api_plugin {
80 static $version = '0.1';
81 static $plugin_url;
82 static $plugin_path;
83 //construct
84 function __construct() {
85 rakuten_api_plugin::$plugin_url = plugin_dir_url(__FILE__);
86 rakuten_api_plugin::$plugin_path = plugin_dir_path(__FILE__);
87 add_option("rakuten_last_run", '', '', 'yes');
88 }
89 //logger function start
90 public static function rakuten_logger($var) {
91 $options = get_option( 'wpra_settings' );
92 $logging_enabled = $options['wpra_checkbox_logging'];
93 if ($logging_enabled == true) {
94 $date = '====== '.date('Y-m-d H:i:s')." =====\n";
95 $result = $var;
96 if (is_array($var) || is_object($var)) {
97 $result = print_r($var, 1);
98 }
99 $result .= "\n";
100 $path = WP_PLUGIN_DIR . '/rakuten_api/rakuten.log';
101 //error_log($path);
102 error_log($date.$result, 3, $path);
103 return true;
104 }
105 return false;
106 }
107 //curl post request function
108 public static function curl_post_request($args, $action_adr, $header) {
109 $api_url = curl_init();
110 curl_setopt_array($api_url, array(
111 CURLOPT_URL => $action_adr,
112 CURLOPT_RETURNTRANSFER => true,
113 CURLOPT_POST => true,
114 CURLOPT_HTTPHEADER => $header,
115 CURLOPT_POSTFIELDS => http_build_query($args)
116 ));
117 $response = curl_exec($api_url);
118 curl_close($api_url);
119 return $response;
120 }
121 //request/check access token with the Rakuten API
122 public static function request_access_token() {
123 $args = array(
124 'grant_type'=>'password',
125 'username'=>'maxsharlaev',
126 'password'=>'max12345',
127 'scope'=>'3351878'
128 );
129 $header = array('Content-Type: application/x-www-form-urlencoded',
130 'Authorization: Basic TGludndTamZsTXBoTGpUUFJpZjAyY0V4NkhRYTpGdXpoWUgxRVg1cVV2bG9uYnNFSHhNM0M3b01h');
131 $action_adr = 'https://api.rakutenmarketing.com/token';
132 $response = rakuten_api_plugin::curl_post_request($args, $action_adr, $header);
133 rakuten_api_plugin::rakuten_logger('Requesting new access token from the API');
134 rakuten_api_plugin::rakuten_logger('Response from the API');
135 rakuten_api_plugin::rakuten_logger($response);
136 $response = json_decode($response, true);
137 return $response;
138 }
139 //Request data from the Rakuten API
140 public static function request_api_data($header, $action_adr = 'https://api.rakutenmarketing.com/coupon/1.0') {
141 rakuten_api_plugin::rakuten_logger('Requesting coupons data from Rakuten api');
142 $response = rakuten_api_plugin::curl_get_request($action_adr, $header);
143 rakuten_api_plugin::rakuten_logger('Response from the API');
144 rakuten_api_plugin::rakuten_logger($response);
145 return $response;
146 }
147 //
148 public static function curl_get_request($action_adr, $header) {
149 $api_url = curl_init();
150 curl_setopt_array($api_url, array(
151 CURLOPT_URL => $action_adr,
152 CURLOPT_RETURNTRANSFER => true,
153 CURLOPT_HTTPHEADER => $header,
154 ));
155 $response = curl_exec($api_url);
156 curl_close($api_url);
157 return $response;
158 }
159 //curl get request function end
160 public static function process_xml($xml) {
161 $results = array();
162 foreach($xml->link as $link)
163 {
164 $element = array(
165 'description' => strval($link->offerdescription),
166 'pixel' => strval($link->impressionpixel),
167 'coupon_code' => strval($link->couponcode),
168 'clickurl' => strval($link->clickurl),
169 'start_date' => strval($link->offerstartdate),
170 'end_date' => strval($link->offerenddate),
171 'advertiserid' => strval($link->advertiserid),
172 'advertisername' => strval($link->advertisername),
173 'network_id' => strval($link->network),
174 );
175 /*foreach($link->categories->children() as $category) {
176 $categories[] = (string) $category;
177
178 }
179 $element['categories'] = $categories;
180 foreach($link->promotiontypes->children() as $promotiontype) {
181 $promotiontypes[] = (string) $promotiontype;
182 }
183 $element['promotiontypes'] = $promotiontypes;*/
184 $results[] = $element;
185 }
186 //main foreach cycle end
187 //rakuten_api_plugin::rakuten_logger(print_r($results));
188 return $results;
189 }
190 //process xml function end
191 public static function write_to_db($data) {
192 global $wpdb;
193 $table_name = $wpdb->prefix . "coupons_item";
194 //prepare data
195 foreach($data as $item) {
196 $data_to_save = array(
197 'description' => $item['description'],
198 'company' => $item['advertisername'],
199 'link' => $item['clickurl'],
200 'pixel' => $item['pixel'],
201 'coupon_code' => $item['coupon_code'],
202 'advertiserid' => $item['advertiserid'],
203 'network_id' => $item['network_id'],
204 'start_date' => $item['start_date'],
205 'end_date' => $item['end_date'],
206 );
207 //write to DB
208 $result = $wpdb->insert($table_name, (array) $data_to_save);
209 if($wpdb->last_error !== '') :
210 $last_error = $wpdb->last_error;
211 rakuten_api_plugin::rakuten_logger($last_error);
212 endif;
213 }
214 return $result;
215 }
216 public static function get_coupon_data_from_db() {
217 global $wpdb;
218 $table_name = $wpdb->prefix . "coupons_item";
219 $sql = "SELECT * FROM $table_name WHERE $table_name.fetch_date > DATE_SUB(NOW(), INTERVAL 12 HOUR)";
220 $results = $wpdb->get_results($sql);
221 return $results;
222 }
223}
224//class end
225function scheduled_rakuten_check() {
226 $last_run = get_option('rakuten_last_run');
227 $current_date_time = date('Y-m-d H:i:s');
228 $hours12 = 12*60*60;
229 $compare_12hours = strtotime($last_run) + $hours12;
230 //If 12 hours have passed since last fetch datetime
231 if (strtotime($current_date_time) < $compare_12hours ) {
232 rakuten_api_plugin::rakuten_logger('no need to run DB update');
233 }
234 else {
235 update_option( 'Rakuten_API last_run', $current_date_time );
236 //Request new token
237 $newtoken = rakuten_api_plugin::request_access_token();
238 $access_token_type = ucfirst($newtoken['token_type']);
239 $access_token = $newtoken['access_token'];
240 $header_token_string = 'Authorization: '. $access_token_type . ' ' . $access_token;
241 $header = array('Content-Type: application/x-www-form-urlencoded', $header_token_string);
242 //Request new data from the API
243 $response = rakuten_api_plugin::request_api_data($header);
244 //Convert data to SimpleXML Object
245 $xml = simplexml_load_string($response);
246 //Parse XML
247 $processed_xml = rakuten_api_plugin::process_xml($xml);
248 //Write result to the DB
249 $db_insert_result = rakuten_api_plugin::write_to_db($processed_xml);
250 //Check for any SQL error
251 if ($db_insert_result) {
252 rakuten_api_plugin::rakuten_logger('DB updated, added ' . count($processed_xml) . ' elements');
253 }
254 //done
255 }
256 //write last run fetch datetime to the log
257 $last_run = get_option('rakuten_last_run');
258 rakuten_api_plugin::rakuten_logger('Last run \n' . $last_run);
259}
260//hook end
261
262
263function rakuten_add_css(){
264 wp_enqueue_style( 'arakuten-style', plugins_url('/css/rakuten-style.css', __FILE__), false, '1.0.0', 'all');
265 }
266
267add_action('wp_enqueue_scripts', "rakuten_add_css");
268
269//with the fields: id, fetch date, company, link, pixel, description, start date, end date//
270
271function create_rakuten_table() {
272 rakuten_api_plugin::rakuten_logger('table creation function called');
273 global $wpdb;
274 $table_name = 'coupons_item';
275 if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
276 {
277 $table_name = $wpdb->prefix . "coupons_item";
278 $sql = "CREATE TABLE IF NOT EXISTS " . $table_name .
279 " (
280 id mediumint(9) NOT NULL AUTO_INCREMENT,
281 fetch_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
282 description text NOT NULL,
283 company tinytext NOT NULL,
284 link tinytext NOT NULL,
285 pixel text NOT NULL,
286 coupon_code tinytext NOT NULL,
287 advertiserid tinytext NOT NULL,
288 network_id tinytext NOT NULL,
289 start_date date NOT NULL,
290 end_date date NOT NULL,
291 UNIQUE KEY id (id)
292 );";
293 $result = dbDelta($sql);
294 rakuten_api_plugin::rakuten_logger('MySQL query result: ' . print_r($result));
295 }
296 else {
297 rakuten_api_plugin::rakuten_logger('MySQL error');
298 }
299}
300
301register_activation_hook(__FILE__,'create_rakuten_table');
302
303//new rakuten api plugin instance
304
305function rakuten_api_plugin_inst() {
306 global $rakuten_api_object;
307 $rakuten_api_object = new rakuten_api_plugin();
308}
309//instance function end
310//adding action for instance creation
311add_action('plugins_loaded', 'rakuten_api_plugin_inst', 0);
312add_action( 'after_setup_theme', 'scheduled_rakuten_check', 0 );
313//adding custom template for displaying results
314
315//template-part to shortcode
316function rakuten_api_shortcode(){
317 require_once('rakuten-display.php');
318}
319
320add_shortcode( 'rakuten', 'rakuten_api_shortcode' );
321
322//plugin end
323?>