Changeset 1330565
- Timestamp:
- 01/18/2016 02:15:37 PM (10 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
woocommerce-piwik-integration/trunk/includes/class-wc-piwik.php
r1130200 r1330565 8 8 * @extends WC_Integration 9 9 */ 10 class WC_Piwik extends WC_Integration { 11 const PIWIK_PRO_URL = 'piwik.pro'; 12 13 public $id; 14 15 public $form_text_fields = array(); 16 17 /** 18 * Init and hook in the integration. 19 */ 20 public function __construct() { 21 $this->redirectToPiwikPro(); 22 $this->id = 'piwik'; 23 $this->method_title = __( 'WooCommerce Piwik', 'woocommerce' ); 24 $this->method_description = __( 'This extension enables you to integrate seamlessly with Piwik, a web analytics platform that gives you valuable 10 class WC_Piwik extends WC_Integration 11 { 12 const PIWIK_PRO_URL = 'piwik.pro'; 13 14 public $id; 15 16 public $form_text_fields = array(); 17 18 /** 19 * Init and hook in the integration. 20 */ 21 public function __construct() 22 { 23 $this->redirectToPiwikPro(); 24 $this->id = 'piwik'; 25 $this->method_title = __('WooCommerce Piwik', 'woocommerce'); 26 $this->method_description = __('This extension enables you to integrate seamlessly with Piwik, a web analytics platform that gives you valuable 25 27 insights into your website`s visitors, e-commerce purchases, products statistics, your marketing campaigns and much 26 28 more, so you can optimize your strategy and online experience of your visitors.', 27 'woocommerce' ); 28 29 // Load the settings. 30 $this->init_form_fields(); 31 $this->init_settings(); 32 33 $this->setupPiwikPro(); 34 35 $this->piwik_idsite = $this->get_option( 'piwik_idsite' ); 36 $this->piwik_domain_name = $this->get_option( 'piwik_domain_name' ); 37 $this->piwik_standard_tracking_enabled = $this->get_option( 'piwik_standard_tracking_enabled' ); 38 $this->piwik_ecommerce_tracking_enabled = $this->get_option( 'piwik_ecommerce_tracking_enabled' ); 39 $this->piwik_cartupdate_tracking_enabled = $this->get_option( 'piwik_cartupdate_tracking_enabled' ); 40 41 $this->disconnectPiwikCloud(); 42 43 // Define user set variables 44 45 $this->addActions(); 46 } 47 48 /** 49 * Initialise Settings Form Fields 50 * 51 * @access public 52 * @return void 53 */ 54 function init_form_fields() { 55 $this->form_text_fields = array( 56 'piwik_idsite' => array( 57 'title' => __( 'Piwik site ID', 'woocommerce' ), 58 'description' => __( 'You can find site ID in Piwik administration panel', 'woocommerce' ), 59 'type' => 'text' 60 ), 61 'piwik_domain_name' => array( 62 'title' => __( 'Piwik domain', 'woocommerce' ), 63 'description' => 'Location of your Piwik installation (without http(s)://, i.e. piwik.example.com)', 64 'type' => 'text' 65 ) 66 ); 67 68 $this->form_fields = array( 69 'piwik_standard_tracking_enabled' => array( 70 'title' => __( 'Tracking code', 'woocommerce' ), 71 'label' => __( 'Add tracking code to your site. You don\'t need to enable this if using a 3rd party 29 'woocommerce'); 30 31 // Load the settings. 32 $this->init_form_fields(); 33 $this->init_settings(); 34 35 $this->setupPiwikPro(); 36 37 $this->piwik_idsite = $this->get_option('piwik_idsite'); 38 $this->piwik_domain_name = $this->get_option('piwik_domain_name'); 39 $this->piwik_standard_tracking_enabled = $this->get_option('piwik_standard_tracking_enabled'); 40 $this->piwik_ecommerce_tracking_enabled = $this->get_option('piwik_ecommerce_tracking_enabled'); 41 $this->piwik_cartupdate_tracking_enabled = $this->get_option('piwik_cartupdate_tracking_enabled'); 42 43 $this->disconnectPiwikCloud(); 44 45 // Define user set variables 46 47 $this->addActions(); 48 } 49 50 /** 51 * Initialise Settings Form Fields 52 * 53 * @access public 54 * @return void 55 */ 56 function init_form_fields() 57 { 58 $this->form_text_fields = array( 59 'piwik_idsite' => array( 60 'title' => __('Piwik site ID', 'woocommerce'), 61 'description' => __('You can find site ID in Piwik administration panel', 'woocommerce'), 62 'type' => 'text' 63 ), 64 'piwik_domain_name' => array( 65 'title' => __('Piwik domain', 'woocommerce'), 66 'description' => 'Location of your Piwik installation (without http(s)://, i.e. piwik.example.com)', 67 'type' => 'text' 68 ) 69 ); 70 71 $this->form_fields = array( 72 'piwik_standard_tracking_enabled' => array( 73 'title' => __('Tracking code', 'woocommerce'), 74 'label' => __('Add tracking code to your site. You don\'t need to enable this if using a 3rd party 72 75 analytics plugin (i.e. Piwiktracking plugin)', 73 'woocommerce' ), 74 'type' => 'checkbox', 75 'checkboxgroup' => 'start', 76 'default' => ( $this->is_wp_piwik_installed() ) ? 'no' : 'yes' 77 ), 78 'piwik_ecommerce_tracking_enabled' => array( 79 'label' => __( 'Add eCommerce tracking code to the thankyou page', 'woocommerce' ), 80 'type' => 'checkbox', 81 'checkboxgroup' => '', 82 'default' => 'yes' 83 ), 84 'piwik_cartupdate_tracking_enabled' => array( 85 'label' => __( 'Add cart update for add to cart actions (i.e. allows to track abandoned carts)', 86 'woocommerce' ), 87 'type' => 'checkbox', 88 'checkboxgroup' => 'end', 89 'default' => 'yes' 90 ), 91 ); 92 } 93 94 95 /** 96 * Piwik standard tracking 97 * 98 * @access public 99 * @return void 100 */ 101 function piwik_tracking_code() { 102 include_once( __DIR__ . '/../templates/tracking-code.php' ); 103 } 104 105 /** 106 * Piwik eCommerce order tracking 107 * 108 * @access public 109 * 110 * @param mixed $order_id 111 * 112 * @return void 113 */ 114 function ecommerce_tracking_code( $order_id ) { 115 if ( get_post_meta( $order_id, '_piwik_tracked', true ) == 1 ) { 116 return; 117 } 118 119 $order = new WC_Order( $order_id ); 120 $code = ' 76 'woocommerce'), 77 'type' => 'checkbox', 78 'checkboxgroup' => 'start', 79 'default' => ($this->is_wp_piwik_installed()) ? 'no' : 'yes' 80 ), 81 'piwik_ecommerce_tracking_enabled' => array( 82 'label' => __('Add eCommerce tracking code to the thankyou page', 'woocommerce'), 83 'type' => 'checkbox', 84 'checkboxgroup' => '', 85 'default' => 'yes' 86 ), 87 'piwik_cartupdate_tracking_enabled' => array( 88 'label' => __('Add cart update for add to cart actions (i.e. allows to track abandoned carts)', 89 'woocommerce'), 90 'type' => 'checkbox', 91 'checkboxgroup' => 'end', 92 'default' => 'yes' 93 ), 94 ); 95 } 96 97 98 /** 99 * Piwik standard tracking 100 * 101 * @access public 102 * @return void 103 */ 104 function piwik_tracking_code() 105 { 106 include_once(__DIR__ . '/../templates/tracking-code.php'); 107 } 108 109 /** 110 * Piwik eCommerce order tracking 111 * 112 * @access public 113 * 114 * @param mixed $order_id 115 * 116 * @return void 117 */ 118 function ecommerce_tracking_code($order_id) 119 { 120 if (get_post_meta($order_id, '_piwik_tracked', true) == 1) { 121 return; 122 } 123 124 $order = new WC_Order($order_id); 125 $code = ' 121 126 var _paq = _paq || []; 122 127 '; 123 128 124 if ( $order->get_items()) {125 foreach ( $order->get_items() as $item) {126 $_product = $order->get_product_from_item( $item);127 $code .= '129 if ($order->get_items()) { 130 foreach ($order->get_items() as $item) { 131 $_product = $order->get_product_from_item($item); 132 $code .= ' 128 133 _paq.push(["addEcommerceItem", 129 "' . esc_js( $_product->get_sku() ? $_product->get_sku() : $_product->id) . '",130 "' . esc_js( $item['name']) . '",';131 132 $out= array();133 $categories = get_the_terms( $_product->id, 'product_cat');134 if ( $categories) {135 foreach ( $categories as $category) {136 $out[] = $category->name;137 }138 }139 if ( count( $out ) > 0) {140 $code .= '["' . join( "\", \"", $out) . '"],';141 } else {142 $code .= '[],';143 }144 145 $code .= '"' . esc_js( $order->get_item_total( $item )) . '",';146 $code .= '"' . esc_js( $item['qty']) . '"';147 $code .= "]);";148 }149 }150 151 $code .= '134 "' . esc_js($_product->get_sku() ? $_product->get_sku() : $_product->id) . '", 135 "' . esc_js($item['name']) . '",'; 136 137 $out = array(); 138 $categories = get_the_terms($_product->id, 'product_cat'); 139 if ($categories) { 140 foreach ($categories as $category) { 141 $out[] = $category->name; 142 } 143 } 144 if (count($out) > 0) { 145 $code .= '["' . join("\", \"", $out) . '"],'; 146 } else { 147 $code .= '[],'; 148 } 149 150 $code .= '"' . esc_js($order->get_item_total($item)) . '",'; 151 $code .= '"' . esc_js($item['qty']) . '"'; 152 $code .= "]);"; 153 } 154 } 155 156 $code .= ' 152 157 _paq.push(["trackEcommerceOrder", 153 "' . esc_js( $order->get_order_number()) . '",154 "' . esc_js( $order->get_total()) . '",155 "' . esc_js( $order->get_total() - $order->get_total_shipping()) . '",156 "' . esc_js( $order->get_total_tax()) . '",157 "' . esc_js( $order->get_total_shipping()) . '"158 "' . esc_js($order->get_order_number()) . '", 159 "' . esc_js($order->get_total()) . '", 160 "' . esc_js($order->get_total() - $order->get_total_shipping()) . '", 161 "' . esc_js($order->get_total_tax()) . '", 162 "' . esc_js($order->get_total_shipping()) . '" 158 163 ]); 159 164 '; 160 165 161 echo '<script type="text/javascript">' . $code . '</script>'; 162 163 update_post_meta( $order_id, '_piwik_tracked', 1 ); 164 } 165 166 /** 167 * Sends cart update request 168 */ 169 function update_cart() { 170 global $woocommerce; 171 172 $cart_content = $woocommerce->cart->get_cart(); 173 $code = ' 166 echo '<script type="text/javascript">' . $code . '</script>'; 167 168 update_post_meta($order_id, '_piwik_tracked', 1); 169 } 170 171 function get_cart_items_js_code() 172 { 173 global $woocommerce; 174 175 $cart_content = $woocommerce->cart->get_cart(); 176 $code = ' 174 177 var cartItems = [];'; 175 foreach ( $cart_content as $item) {176 177 $item_sku = esc_js( ( $sku = $item['data']->get_sku() ) ? $sku : $item['product_id']);178 $item_price = $item['data']->get_price();179 $item_title = $item['data']->get_title();180 $cats = $this->getProductCategories( $item['product_id']);181 182 $code .= "178 foreach ($cart_content as $item) { 179 180 $item_sku = esc_js(($sku = $item['data']->get_sku()) ? $sku : $item['product_id']); 181 $item_price = $item['data']->get_price(); 182 $item_title = $item['data']->get_title(); 183 $cats = $this->getProductCategories($item['product_id']); 184 185 $code .= " 183 186 cartItems.push({ 184 187 sku: \"$item_sku\", … … 189 192 }); 190 193 "; 191 } 192 193 wc_enqueue_js( " 194 } 195 196 return $code; 197 } 198 199 /** 200 * Sends cart update request 201 */ 202 function update_cart() 203 { 204 205 $code = $this->get_cart_items_js_code(); 206 207 wc_enqueue_js(" 194 208 " . $code . " 195 209 var arrayLength = cartItems.length, revenue = 0; … … 209 223 210 224 _paq.push(['trackEcommerceCartUpdate', revenue]); 211 " ); 212 } 213 214 /** 215 * Ajax action to get cart 216 */ 217 function get_cart() { 218 global $woocommerce; 219 220 $cart_content = $woocommerce->cart->get_cart(); 221 $products = array(); 222 223 foreach ( $cart_content as $item ) { 224 $item_sku = esc_js( ( $sku = $item['data']->get_sku() ) ? $sku : $item['product_id'] ); 225 $cats = $this->getProductCategories( $item['product_id'] ); 226 227 $products[] = array( 228 'sku' => $item_sku, 229 'title' => $item['data']->get_title(), 230 'price' => $item['data']->get_price(), 231 'quantity' => $item['quantity'], 232 'categories' => $cats 233 ); 234 } 235 236 header( 'Content-Type: application/json; charset=utf-8' ); 237 238 echo json_encode( $products ); 239 exit; 240 } 241 242 function send_update_cart_request() { 243 if ( ! empty( $_REQUEST['add-to-cart'] ) && is_numeric( $_REQUEST['add-to-cart'] ) ) { 244 wc_enqueue_js( " 245 $('body').trigger('added_to_cart'); 246 " ); 247 } 248 } 249 250 /** 251 * @param $itemID 252 * 253 * @return string 254 */ 255 protected function getProductCategories( $itemID ) { 256 $out = array(); 257 $categories = get_the_terms( $itemID, 'product_cat' ); 258 259 if ( $categories ) { 260 foreach ( $categories as $category ) { 261 $out[] = $category->name; 262 } 263 } 264 265 if ( count( $out ) > 0 ) { 266 $cats = '["' . join( "\", \"", $out ) . '"]'; 267 268 return $cats; 269 } else { 270 $cats = '[]'; 271 272 return $cats; 273 } 274 } 275 276 /** 277 * Add actions using WooCommerce hooks 278 */ 279 protected function addActions() { 280 281 add_action( 'woocommerce_update_options_integration_piwik', array( $this, 'process_admin_options' ) ); 282 add_action( 'wp_ajax_nopriv_woocommerce_piwik_get_cart', array( $this, 'get_cart' ) ); 283 add_action( 'wp_ajax_woocommerce_piwik_get_cart', array( $this, 'get_cart' ) ); 284 add_action( 'woocommerce_after_single_product_summary', array($this, 'product_view') ); 285 add_action( 'woocommerce_after_shop_loop', array($this, 'category_view') ); 286 287 288 if ( 289 ( ( empty( $this->piwik_idsite ) || ! is_numeric( $this->piwik_idsite ) || empty( $this->piwik_domain_name ) ) 290 && ! $this->is_wp_piwik_installed() ) 291 || is_admin() || current_user_can( 'manage_options' ) 292 ) { 225 "); 226 } 227 228 /** 229 * Ajax action to get cart 230 */ 231 function get_cart() 232 { 233 global $woocommerce; 234 235 $cart_content = $woocommerce->cart->get_cart(); 236 $products = array(); 237 238 foreach ($cart_content as $item) { 239 $item_sku = esc_js(($sku = $item['data']->get_sku()) ? $sku : $item['product_id']); 240 $cats = $this->getProductCategories($item['product_id']); 241 242 $products[] = array( 243 'sku' => $item_sku, 244 'title' => $item['data']->get_title(), 245 'price' => $item['data']->get_price(), 246 'quantity' => $item['quantity'], 247 'categories' => $cats 248 ); 249 } 250 251 header('Content-Type: application/json; charset=utf-8'); 252 253 echo json_encode($products); 254 exit; 255 } 256 257 function send_update_cart_request() 258 { 259 if (!empty($_REQUEST['add-to-cart']) && is_numeric($_REQUEST['add-to-cart'])) { 260 $code = $this->get_cart_items_js_code(); 261 wc_enqueue_js($code . " 262 $(document).ready(function(){ 263 $('body').trigger('added_to_cart'); 264 }); 265 "); 266 } 267 } 268 269 /** 270 * @param $itemID 271 * 272 * @return string 273 */ 274 protected function getProductCategories($itemID) 275 { 276 $out = array(); 277 $categories = get_the_terms($itemID, 'product_cat'); 278 279 if ($categories) { 280 foreach ($categories as $category) { 281 $out[] = $category->name; 282 } 283 } 284 285 if (count($out) > 0) { 286 $cats = '["' . join("\", \"", $out) . '"]'; 287 288 return $cats; 289 } else { 290 $cats = '[]'; 291 292 return $cats; 293 } 294 } 295 296 /** 297 * Add actions using WooCommerce hooks 298 */ 299 protected function addActions() 300 { 301 add_action('woocommerce_update_options_integration_piwik', array($this, 'process_admin_options')); 302 add_action('wp_ajax_nopriv_woocommerce_piwik_get_cart', array($this, 'get_cart')); 303 add_action('wp_ajax_woocommerce_piwik_get_cart', array($this, 'get_cart')); 304 add_action('woocommerce_after_single_product_summary', array($this, 'product_view')); 305 add_action('woocommerce_after_shop_loop', array($this, 'category_view')); 306 307 if ( 308 ((empty($this->piwik_idsite) || !is_numeric($this->piwik_idsite) || empty($this->piwik_domain_name)) 309 && !$this->is_wp_piwik_installed()) 310 || is_admin() || current_user_can('manage_options') 311 ) { 293 312 return; 294 }295 296 if ( $this->piwik_standard_tracking_enabled == 'yes') {297 add_action( 'wp_footer', array( $this, 'piwik_tracking_code' ));298 }299 300 if ( $this->piwik_ecommerce_tracking_enabled == 'yes') {301 add_action( 'woocommerce_thankyou', array( $this, 'ecommerce_tracking_code' ));302 }303 304 if ( $this->piwik_cartupdate_tracking_enabled == 'yes') {305 add_action( 'woocommerce_after_single_product', array( $this, 'send_update_cart_request' ));306 add_action( 'woocommerce_after_cart', array( $this, 'update_cart' ));307 308 $suffix = defined( 'SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';309 $assets_path = str_replace( array( 'http:', 'https:'),310 '',311 untrailingslashit( plugins_url( '/', __FILE__ ) )) . '/';312 $frontend_script_path = $assets_path . '../assets/js/';313 wp_enqueue_script('get-cart',314 $frontend_script_path . 'get-cart' . $suffix . '.js',315 array( 'jquery'),316 WC_VERSION,317 true);318 }319 }313 } 314 315 if ($this->piwik_standard_tracking_enabled == 'yes') { 316 add_action('wp_footer', array($this, 'piwik_tracking_code')); 317 } 318 319 if ($this->piwik_ecommerce_tracking_enabled == 'yes') { 320 add_action('woocommerce_thankyou', array($this, 'ecommerce_tracking_code')); 321 } 322 323 if ($this->piwik_cartupdate_tracking_enabled == 'yes') { 324 add_action('woocommerce_after_single_product', array($this, 'send_update_cart_request')); 325 add_action('woocommerce_after_cart', array($this, 'update_cart')); 326 327 $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; 328 $assets_path = str_replace(array('http:', 'https:'), 329 '', 330 untrailingslashit(plugins_url('/', __FILE__))) . '/'; 331 $frontend_script_path = $assets_path . '../assets/js/'; 332 wp_enqueue_script('get-cart', 333 $frontend_script_path . 'get-cart' . $suffix . '.js', 334 array('jquery'), 335 WC_VERSION, 336 true); 337 } 338 } 320 339 321 340 function category_view() … … 349 368 _paq.push(['trackPageView']); 350 369 ", 351 $product->get_sku(),352 urlencode($product->get_title()),353 $this->getEncodedCategoriesByProduct($product),354 $product->get_price()370 $product->get_sku(), 371 urlencode($product->get_title()), 372 $this->getEncodedCategoriesByProduct($product), 373 $product->get_price() 355 374 ); 356 375 wc_enqueue_js($jsCode); … … 359 378 protected function getEncodedCategoriesByProduct($product) 360 379 { 361 $categories = get_the_terms($product->post->ID, 'product_cat' );380 $categories = get_the_terms($product->post->ID, 'product_cat'); 362 381 363 382 if (!$categories) { … … 365 384 } 366 385 367 $categories = array_map(function ($element) {386 $categories = array_map(function ($element) { 368 387 return sprintf("'%s'", urlencode($element->name)); 369 388 }, $categories); 370 389 371 return sprintf("[%s]", implode("', '", $categories)); 372 } 373 374 protected function redirectToPiwikPro() { 375 if ( isset( $_GET['integrate-piwik-cloud'] ) && $_GET['integrate-piwik-cloud'] ) { 376 $token = $this->generateToken(); 377 $siteUrl = $this->getSiteUrl(); 378 delete_option( 'woocommerce_piwik_integration' ); 379 delete_option( 'woocommerce_piwik_token' ); 380 delete_option( 'woocommerce_piwik_ts_valid' ); 381 add_option( 'woocommerce_piwik_token', $token ); 382 add_option( 'woocommerce_piwik_ts_valid', time() ); 383 384 header( 'Location: http://' . self::PIWIK_PRO_URL . '/integrate/woocommerce?shop=' . $siteUrl . '&code=' . $token ); 385 386 exit; 387 } 388 389 } 390 391 protected function useOpenSsl() { 392 if ( defined( 'PHP_WINDOWS_VERSION_BUILD' ) && version_compare( PHP_VERSION, '5.3.4', '<' ) ) { 393 return false; 394 } elseif ( ! function_exists( 'openssl_random_pseudo_bytes' ) ) { 395 return false; 396 } else { 397 return true; 398 } 399 } 400 401 protected function generateToken() { 402 return rtrim( strtr( base64_encode( $this->getRandomNumber() ), '+/', '-_' ), '=' ); 403 } 404 405 protected function getRandomNumber() { 406 $nbBytes = 32; 407 408 // try OpenSSL 409 if ( $this->useOpenSsl() ) { 410 $bytes = openssl_random_pseudo_bytes( $nbBytes, $strong ); 411 412 if ( false !== $bytes && true === $strong ) { 413 return $bytes; 414 } 415 } 416 417 return hash( 'sha256', uniqid( mt_rand(), true ), true ); 418 } 419 420 protected function setupPiwikPro() { 421 if ( $this->validateIntegrationValues() ) { 422 $this->setOption( 'piwik_idsite', $_GET['idsite'] ); 423 $this->setOption( 'piwik_domain_name', $_GET['piwikurl'] ); 424 $this->process_admin_options(); 425 WC_Admin_Settings::add_message( __( 'Your site has been successfuly integrated with Piwik Cloud!', 426 'woocommerce' ) ); 427 delete_option( 'woocommerce_piwik_ts_valid' ); 428 add_option( 'woocommerce_piwik_integrated', true ); 429 430 $this->update_wp_piwik_settings(); 431 432 } else { 433 if ( ! empty( $_GET['code'] ) || ! empty( $_GET['piwikurl'] ) || ! empty( $_GET['idsite'] ) ) { 434 header( 'Location: ' . site_url() . '/wp-admin/admin.php?page=wc-settings&tab=integration' ); 435 exit; 436 } 437 } 438 } 439 440 protected function disconnectPiwikCloud() { 441 if ( ! empty( $_GET['disconnect-piwik-cloud'] ) && $_GET['disconnect-piwik-cloud'] ) { 442 443 if ( ! class_exists( 'WP_Http' ) ) { 444 include_once( ABSPATH . WPINC . '/class-http.php' ); 445 } 446 447 $request = new WP_Http; 448 $result = $request->request( 449 'http://' . $this->piwik_domain_name 450 . '/index.php?module=API&method=Integration.woocommerceUninstall&format=JSON&shop=' 451 . $this->getSiteUrl() . '&code=' 452 . get_option( 'woocommerce_piwik_token' ) 453 ); 454 455 if ( array_key_exists( 'response', $result ) && $result['response']['code'] == 200 ) { 456 $this->setOption( 'piwik_idsite', '' ); 457 $this->setOption( 'piwik_domain_name', '' ); 458 $this->process_admin_options(); 459 delete_option( 'woocommerce_piwik_integrated' ); 460 461 WC_Admin_Settings::add_message( __( 'Your site has been successfully disconnected from Piwik Cloud!', 462 'woocommerce' ) ); 463 464 $this->update_wp_piwik_settings(); 465 } else { 466 WC_Admin_Settings::add_error( __( 'An error occurred when trying to disconnect, please try again later', 467 'woocommerce' ) ); 468 } 469 470 } 471 } 472 473 protected function setOption( $key, $value ) { 474 $this->settings[ $key ] = $value; 475 } 476 477 public function validate_checkbox_field( $key ) { 478 if ( $this->validateIntegrationValues() ) { 479 return 'yes'; 480 } 481 482 $status = 'no'; 483 if ( isset( $_POST[ $this->plugin_id . $this->id . '_' . $key ] ) && ( 1 == $_POST[ $this->plugin_id . $this->id . '_' . $key ] ) ) { 484 $status = 'yes'; 485 } 486 487 return $status; 488 } 489 490 protected function validateIntegrationValues() { 491 // ignore field validation if piwik pro integration values are provided 492 if ( ! empty( $_GET['code'] ) && ! empty( $_GET['piwikurl'] ) && ! empty( $_GET['idsite'] ) ) { 493 $token = get_option( 'woocommerce_piwik_token' ); 494 $timestamp = get_option( 'woocommerce_piwik_ts_valid' ); 495 496 if ( $token == $_GET['code'] ) { 497 if ( ( ( time() - $timestamp ) < 3600 ) ) { 498 return true; 499 } 500 } 501 } 502 503 return false; 504 } 505 506 public function admin_options() { 507 $uriParts = explode( '?', $_SERVER['REQUEST_URI'], 2 ); 508 $url = 'http://' . $_SERVER['HTTP_HOST'] . $uriParts[0] . '?page=wc-settings&tab=integration'; 509 510 if ( $_GET['subtab'] == 'piwik-cloud' ) { 511 $cloudClass = 'enabled '; 512 $selfHostedClass = ''; 513 $cloudSubtab = ''; 514 $selfHostedSubtab = $url . '&subtab=piwik-self-hosted'; 515 } elseif ( $_GET['subtab'] == 'piwik-self-hosted' ) { 516 $cloudClass = ''; 517 $selfHostedClass = 'enabled '; 518 $cloudSubtab = $url . '&subtab=piwik-cloud'; 519 $selfHostedSubtab = ''; 520 } else { 521 $cloudClass = 'enabled '; 522 $selfHostedClass = ''; 523 $cloudSubtab = $url . '&subtab=piwik-cloud'; 524 $selfHostedSubtab = $url . '&subtab=piwik-self-hosted'; 525 } 526 527 528 include_once(__DIR__ . '/../templates/admin-options.php'); 529 530 } 531 532 public function validate_settings_fields( $form_fields = false ) { 533 parent::validate_settings_fields( array_merge( $this->form_text_fields, $this->form_fields ) ); 534 } 535 536 /** 537 * @return mixed 538 */ 539 protected function getSiteUrl() { 540 $siteUrl = str_replace( 'http://', '', get_site_url() ); 541 $siteUrl = str_replace( 'https://', '', $siteUrl ); 542 543 return $siteUrl; 544 } 545 546 /** 547 * Check if wp piwik is installed 548 * 549 * @return bool 550 */ 551 protected function is_wp_piwik_installed() { 552 return ( isset( $GLOBALS['wp_piwik'] ) ); 553 } 554 555 protected function get_wp_piwik_settings() { 556 return get_option( 'wp-piwik_settings' ); 557 } 558 559 protected function get_wp_piwik_global_settings() { 560 return get_option( 'wp-piwik_global-settings' ); 561 } 562 563 protected function set_wp_piwik_settings( $value ) { 564 update_option( 'wp-piwik_settings', $value ); 565 } 566 567 protected function set_wp_piwik_global_settings( $value ) { 568 update_option( 'wp-piwik_global-settings', $value ); 569 } 570 571 protected function update_wp_piwik_settings() { 572 if ( ! $this->is_wp_piwik_installed() ) { 573 return; 574 } 575 576 $settings = $this->get_wp_piwik_settings(); 577 $globalSettings = $this->get_wp_piwik_global_settings(); 578 579 if ( $idSite = $this->get_option( 'piwik_idsite' ) ) { 580 $settings['site_id'] = $idSite; 581 $globalSettings['add_tracking_code'] = 0; 582 $globalSettings['piwik_url'] = 'http://' . $this->get_option( 'piwik_domain_name' ); 583 $this->setOption( 'piwik_standard_tracking_enabled', 'yes' ); 584 585 $this->set_wp_piwik_settings( $settings ); 586 $this->set_wp_piwik_global_settings( $globalSettings ); 587 588 WC_Admin_Settings::add_message( __( 'Introduced changes to WP Piwik settings. Please update them according to your needs!', 589 'woocommerce' ) ); 590 } else { 591 $settings['site_id'] = ''; 592 $globalSettings['add_tracking_code'] = 0; 593 $globalSettings['piwik_url'] = ''; 594 $this->setOption( 'piwik_standard_tracking_enabled', 'no' ); 595 596 $this->set_wp_piwik_settings( $settings ); 597 $this->set_wp_piwik_global_settings( $globalSettings ); 598 599 WC_Admin_Settings::add_message( __( 'Introduced changes to WP Piwik settings. Please update them according to your needs!', 600 'woocommerce' ) ); 601 } 602 } 390 return sprintf("[%s]", implode(", ", $categories)); 391 } 392 393 protected function redirectToPiwikPro() 394 { 395 if (isset($_GET['integrate-piwik-cloud']) && $_GET['integrate-piwik-cloud']) { 396 $token = $this->generateToken(); 397 $siteUrl = $this->getSiteUrl(); 398 delete_option('woocommerce_piwik_integration'); 399 delete_option('woocommerce_piwik_token'); 400 delete_option('woocommerce_piwik_ts_valid'); 401 add_option('woocommerce_piwik_token', $token); 402 add_option('woocommerce_piwik_ts_valid', time()); 403 404 header('Location: http://' . self::PIWIK_PRO_URL . '/integrate/woocommerce?shop=' . $siteUrl . '&code=' . $token); 405 406 exit; 407 } 408 409 } 410 411 protected function useOpenSsl() 412 { 413 if (defined('PHP_WINDOWS_VERSION_BUILD') && version_compare(PHP_VERSION, '5.3.4', '<')) { 414 return false; 415 } elseif (!function_exists('openssl_random_pseudo_bytes')) { 416 return false; 417 } else { 418 return true; 419 } 420 } 421 422 protected function generateToken() 423 { 424 return rtrim(strtr(base64_encode($this->getRandomNumber()), '+/', '-_'), '='); 425 } 426 427 protected function getRandomNumber() 428 { 429 $nbBytes = 32; 430 431 // try OpenSSL 432 if ($this->useOpenSsl()) { 433 $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); 434 435 if (false !== $bytes && true === $strong) { 436 return $bytes; 437 } 438 } 439 440 return hash('sha256', uniqid(mt_rand(), true), true); 441 } 442 443 protected function setupPiwikPro() 444 { 445 if ($this->validateIntegrationValues()) { 446 $this->setOption('piwik_idsite', $_GET['idsite']); 447 $this->setOption('piwik_domain_name', $_GET['piwikurl']); 448 $this->process_admin_options(); 449 WC_Admin_Settings::add_message(__('Your site has been successfuly integrated with Piwik Cloud!', 450 'woocommerce')); 451 delete_option('woocommerce_piwik_ts_valid'); 452 add_option('woocommerce_piwik_integrated', true); 453 454 $this->update_wp_piwik_settings(); 455 456 } else { 457 if (!empty($_GET['code']) || !empty($_GET['piwikurl']) || !empty($_GET['idsite'])) { 458 header('Location: ' . site_url() . '/wp-admin/admin.php?page=wc-settings&tab=integration'); 459 exit; 460 } 461 } 462 } 463 464 protected function disconnectPiwikCloud() 465 { 466 if (!empty($_GET['disconnect-piwik-cloud']) && $_GET['disconnect-piwik-cloud']) { 467 468 if (!class_exists('WP_Http')) { 469 include_once(ABSPATH . WPINC . '/class-http.php'); 470 } 471 472 $request = new WP_Http; 473 $result = $request->request( 474 'http://' . $this->piwik_domain_name 475 . '/index.php?module=API&method=Integration.woocommerceUninstall&format=JSON&shop=' 476 . $this->getSiteUrl() . '&code=' 477 . get_option('woocommerce_piwik_token') 478 ); 479 480 if (array_key_exists('response', $result) && $result['response']['code'] == 200) { 481 $this->setOption('piwik_idsite', ''); 482 $this->setOption('piwik_domain_name', ''); 483 $this->process_admin_options(); 484 delete_option('woocommerce_piwik_integrated'); 485 486 WC_Admin_Settings::add_message(__('Your site has been successfully disconnected from Piwik Cloud!', 487 'woocommerce')); 488 489 $this->update_wp_piwik_settings(); 490 } else { 491 WC_Admin_Settings::add_error(__('An error occurred when trying to disconnect, please try again later', 492 'woocommerce')); 493 } 494 495 } 496 } 497 498 protected function setOption($key, $value) 499 { 500 $this->settings[$key] = $value; 501 } 502 503 public function validate_checkbox_field($key) 504 { 505 if ($this->validateIntegrationValues()) { 506 return 'yes'; 507 } 508 509 $status = 'no'; 510 if (isset($_POST[$this->plugin_id . $this->id . '_' . $key]) && (1 == $_POST[$this->plugin_id . $this->id . '_' . $key])) { 511 $status = 'yes'; 512 } 513 514 return $status; 515 } 516 517 protected function validateIntegrationValues() 518 { 519 // ignore field validation if piwik pro integration values are provided 520 if (!empty($_GET['code']) && !empty($_GET['piwikurl']) && !empty($_GET['idsite'])) { 521 $token = get_option('woocommerce_piwik_token'); 522 $timestamp = get_option('woocommerce_piwik_ts_valid'); 523 524 if ($token == $_GET['code']) { 525 if (((time() - $timestamp) < 3600)) { 526 return true; 527 } 528 } 529 } 530 531 return false; 532 } 533 534 public function admin_options() 535 { 536 $uriParts = explode('?', $_SERVER['REQUEST_URI'], 2); 537 $url = 'http://' . $_SERVER['HTTP_HOST'] . $uriParts[0] . '?page=wc-settings&tab=integration'; 538 539 if ($_GET['subtab'] == 'piwik-cloud') { 540 $cloudClass = 'enabled '; 541 $selfHostedClass = ''; 542 $cloudSubtab = ''; 543 $selfHostedSubtab = $url . '&subtab=piwik-self-hosted'; 544 } elseif ($_GET['subtab'] == 'piwik-self-hosted') { 545 $cloudClass = ''; 546 $selfHostedClass = 'enabled '; 547 $cloudSubtab = $url . '&subtab=piwik-cloud'; 548 $selfHostedSubtab = ''; 549 } else { 550 $cloudClass = 'enabled '; 551 $selfHostedClass = ''; 552 $cloudSubtab = $url . '&subtab=piwik-cloud'; 553 $selfHostedSubtab = $url . '&subtab=piwik-self-hosted'; 554 } 555 556 include_once(__DIR__ . '/../templates/admin-options.php'); 557 558 } 559 560 public function validate_settings_fields($form_fields = false) 561 { 562 parent::validate_settings_fields(array_merge($this->form_text_fields, $this->form_fields)); 563 } 564 565 /** 566 * @return mixed 567 */ 568 protected function getSiteUrl() 569 { 570 $siteUrl = str_replace('http://', '', get_site_url()); 571 $siteUrl = str_replace('https://', '', $siteUrl); 572 573 return $siteUrl; 574 } 575 576 /** 577 * Check if wp piwik is installed 578 * 579 * @return bool 580 */ 581 protected function is_wp_piwik_installed() 582 { 583 return (isset($GLOBALS['wp_piwik'])); 584 } 585 586 protected function get_wp_piwik_settings() 587 { 588 return get_option('wp-piwik_settings'); 589 } 590 591 protected function get_wp_piwik_global_settings() 592 { 593 return get_option('wp-piwik_global-settings'); 594 } 595 596 protected function set_wp_piwik_settings($value) 597 { 598 update_option('wp-piwik_settings', $value); 599 } 600 601 protected function set_wp_piwik_global_settings($value) 602 { 603 update_option('wp-piwik_global-settings', $value); 604 } 605 606 protected function update_wp_piwik_settings() 607 { 608 if (!$this->is_wp_piwik_installed()) { 609 return; 610 } 611 612 $settings = $this->get_wp_piwik_settings(); 613 $globalSettings = $this->get_wp_piwik_global_settings(); 614 615 if ($idSite = $this->get_option('piwik_idsite')) { 616 $settings['site_id'] = $idSite; 617 $globalSettings['add_tracking_code'] = 0; 618 $globalSettings['piwik_url'] = 'http://' . $this->get_option('piwik_domain_name'); 619 $this->setOption('piwik_standard_tracking_enabled', 'yes'); 620 621 $this->set_wp_piwik_settings($settings); 622 $this->set_wp_piwik_global_settings($globalSettings); 623 624 WC_Admin_Settings::add_message(__('Introduced changes to WP Piwik settings. Please update them according to your needs!', 625 'woocommerce')); 626 } else { 627 $settings['site_id'] = ''; 628 $globalSettings['add_tracking_code'] = 0; 629 $globalSettings['piwik_url'] = ''; 630 $this->setOption('piwik_standard_tracking_enabled', 'no'); 631 632 $this->set_wp_piwik_settings($settings); 633 $this->set_wp_piwik_global_settings($globalSettings); 634 635 WC_Admin_Settings::add_message(__('Introduced changes to WP Piwik settings. Please update them according to your needs!', 636 'woocommerce')); 637 } 638 } 603 639 } 640
Note: See TracChangeset
for help on using the changeset viewer.