WP-Matomo (WP-Piwik) - Version 0.10.0.0

Version Description

Please update Piwik if not done yet (Piwik 2.7 or higher is recommended).

Download this release

Release Info

Developer Braekling
Plugin Icon 128x128 WP-Matomo (WP-Piwik)
Version 0.10.0.0
Comparing to
See all releases

Code changes from version 0.9.9.14 to 0.10.0.0

Files changed (86) hide show
  1. classes/WP_Piwik.php +368 -1200
  2. classes/WP_Piwik/Admin.php +26 -0
  3. classes/WP_Piwik/Admin/Network.php +25 -0
  4. classes/WP_Piwik/Admin/Settings.php +354 -0
  5. classes/WP_Piwik/Admin/Sitebrowser.php +96 -0
  6. classes/WP_Piwik/Admin/Statistics.php +53 -0
  7. classes/{WP_Piwik_Logger.php → WP_Piwik/Logger.php} +3 -1
  8. classes/WP_Piwik/Logger/Dummy.php +9 -0
  9. classes/{WP_Piwik_Logger_File.php → WP_Piwik/Logger/File.php} +4 -4
  10. classes/WP_Piwik/Logger/Screen.php +27 -0
  11. classes/WP_Piwik/Request.php +57 -0
  12. classes/WP_Piwik/Request/Php.php +41 -0
  13. classes/WP_Piwik/Request/Rest.php +51 -0
  14. classes/WP_Piwik/Settings.php +258 -0
  15. classes/WP_Piwik/Shortcode.php +23 -0
  16. classes/{WP_Piwik_Template.php → WP_Piwik/Template.php} +6 -7
  17. classes/WP_Piwik/Template/MetaBoxCustomVars.php +63 -0
  18. classes/WP_Piwik/TrackingCode.php +109 -0
  19. classes/WP_Piwik/Widget.php +172 -0
  20. classes/WP_Piwik/Widget/BrowserDetails.php +62 -0
  21. classes/WP_Piwik/Widget/Browsers.php +62 -0
  22. classes/WP_Piwik/Widget/Chart.php +71 -0
  23. classes/WP_Piwik/Widget/Keywords.php +21 -0
  24. classes/WP_Piwik/Widget/Noresult.php +37 -0
  25. classes/WP_Piwik/Widget/OptOut.php +17 -0
  26. classes/WP_Piwik/Widget/Overview.php +42 -0
  27. classes/WP_Piwik/Widget/Pages.php +21 -0
  28. classes/WP_Piwik/Widget/Plugins.php +37 -0
  29. classes/WP_Piwik/Widget/Post.php +51 -0
  30. classes/WP_Piwik/Widget/Referrers.php +21 -0
  31. classes/WP_Piwik/Widget/Screens.php +62 -0
  32. classes/WP_Piwik/Widget/Search.php +37 -0
  33. classes/WP_Piwik/Widget/Seo.php +31 -0
  34. classes/WP_Piwik/Widget/Systems.php +60 -0
  35. classes/WP_Piwik/Widget/Visitors.php +53 -0
  36. classes/WP_Piwik_Logger_Dummy.php +0 -9
  37. classes/WP_Piwik_MetaBox_PerPost_Stats.php +0 -47
  38. classes/WP_Piwik_Settings.php +0 -163
  39. config.php +1 -1
  40. dashboard/.htaccess +0 -1
  41. dashboard/browserdetails.php +0 -68
  42. dashboard/browsers.php +0 -69
  43. dashboard/index.php +0 -2
  44. dashboard/keywords.php +0 -30
  45. dashboard/noresult.php +0 -30
  46. dashboard/overview.php +0 -70
  47. dashboard/pages.php +0 -57
  48. dashboard/plugins.php +0 -58
  49. dashboard/screens.php +0 -68
  50. dashboard/search.php +0 -30
  51. dashboard/seo.php +0 -36
  52. dashboard/systems.php +0 -69
  53. dashboard/visitors.php +0 -99
  54. dashboard/websites.php +0 -34
  55. piwik.php +0 -126
  56. proxy/config.php +14 -0
  57. {classes → proxy}/index.php +0 -0
  58. proxy/piwik.php +134 -0
  59. readme.txt +38 -12
  60. settings/.htaccess +0 -1
  61. settings/homepage.php +0 -11
  62. settings/index.php +0 -2
  63. settings/sitebrowser.php +0 -99
  64. settings/support.php +5 -5
  65. shortcodes/.htaccess +0 -1
  66. shortcodes/overview.php +0 -45
  67. shortcodes/post.php +0 -6
  68. update/80502.php +0 -2
  69. update/80602.php +0 -2
  70. update/80800.php +1 -1
  71. update/90001.php +2 -7
  72. update/90206.php +0 -2
  73. update/90405.php +0 -5
  74. update/90601.php +0 -3
  75. update/90700.php +0 -2
  76. update/90801.php +0 -2
  77. update/90821.php +0 -2
  78. update/90910.php +0 -3
  79. update/90920.php +0 -2
  80. update/90940.php +0 -2
  81. update/90961.php +0 -2
  82. update/90971.php +0 -3
  83. update/90980.php +0 -6
  84. update/91007.php +0 -2
  85. update/index.php +0 -2
  86. wp-piwik.php +27 -1506
classes/WP_Piwik.php CHANGED
@@ -1,23 +1,18 @@
1
  <?php
2
 
3
- class wp_piwik {
4
 
5
  private static
6
- $intRevisionId = 92000,
7
- $strVersion = '0.9.9.10',
8
  $blog_id,
9
  $intDashboardID = 30,
10
  $strPluginBasename = NULL,
11
  $bolJustActivated = false,
12
  $logger,
13
- $settings;
 
14
 
15
- private
16
- $intStatsPage = NULL,
17
- $bolNetwork = false,
18
- $aryAttributes = array(),
19
- $strResult = '';
20
-
21
  public function __construct() {
22
  global $blog_id;
23
  self::$blog_id = (isset($blog_id)?$blog_id:'n/a');
@@ -27,6 +22,11 @@ class wp_piwik {
27
  $this->addFilters();
28
  $this->addActions();
29
  $this->addShortcodes();
 
 
 
 
 
30
  self::$settings->save();
31
  }
32
 
@@ -36,80 +36,84 @@ class wp_piwik {
36
 
37
  private function setup() {
38
  self::$strPluginBasename = plugin_basename(__FILE__);
39
- register_activation_hook(__FILE__, array($this, 'installPlugin'));
40
- if ($this->isUpdated())
41
- $this->upgradePlugin();
 
42
  if ($this->isConfigSubmitted())
43
  $this->applySettings();
44
  if ($this->isPHPMode())
45
  self::definePiwikConstants();
46
- $this->loadLanguage();
47
  }
48
 
49
  private function addActions() {
 
 
50
  add_action('admin_menu', array($this, 'buildAdminMenu'));
51
- add_action('admin_post_save_wp-piwik_stats', array(&$this, 'onStatsPageSaveChanges'));
52
- add_action('load-post.php', array(&$this, 'postMetaboxes'));
53
- add_action('load-post-new.php', array(&$this, 'postMetaboxes'));
54
- if ($this->isNetworkMode())
55
  add_action('network_admin_menu', array($this, 'buildNetworkAdminMenu'));
 
 
 
 
 
 
56
  if ($this->isDashboardActive())
57
  add_action('wp_dashboard_setup', array($this, 'extendWordPressDashboard'));
58
  if ($this->isToolbarActive()) {
59
  add_action(is_admin()?'admin_head':'wp_head', array($this, 'loadToolbarRequirements'));
60
- add_action('admin_bar_menu', array(&$this, 'extendWordPressToolbar'), 1000);
61
  }
62
  if ($this->isTrackingActive()) {
63
  add_action(self::$settings->getGlobalOption('track_codeposition') == 'footer'?'wp_footer':'wp_head', array($this, 'addJavascriptCode'));
64
  if ($this->isAddNoScriptCode())
65
  add_action('wp_footer', array($this, 'addNoscriptCode'));
66
  if ($this->isAdminTrackingActive())
67
- add_action('admin_head', array($this, 'addAdminHeaderTracking'));
68
  }
69
  if (self::$settings->getGlobalOption('add_post_annotations'))
70
- add_action('transition_post_status', array($this, 'onPostStatusTransition'));
71
  }
72
 
73
  private function addFilters() {
74
  add_filter('plugin_row_meta', array($this, 'setPluginMeta'), 10, 2);
75
- add_filter('screen_layout_columns', array(&$this, 'onScreenLayoutColumns'), 10, 2);
76
  if ($this->isTrackingActive()) {
77
  if ($this->isTrackFeed()) {
78
- add_filter('the_excerpt_rss', array(&$this, 'addFeedTracking'));
79
- add_filter('the_content', array(&$this, 'addFeedTracking'));
80
  }
81
  if ($this->isAddFeedCampaign())
82
- add_filter('post_link', array(&$this, 'addFeedCampaign'));
83
  }
84
  }
85
 
86
  private function addShortcodes() {
87
  if ($this->isAddShortcode())
88
- add_shortcode('wp-piwik', array(&$this, 'shortcode'));
89
  }
90
 
91
- private function loadLanguage() {
92
- load_plugin_textdomain('wp-piwik', false, dirname(self::$strPluginBasename)."/../languages/");
93
- }
94
-
95
- function installPlugin() {
96
  self::$logger->log('Running WP-Piwik installation');
97
- add_action('admin_notices', array($this, 'updateMessage'));
98
- self::$bolJustActivated = true;
99
  self::$settings->setGlobalOption('revision', self::$intRevisionId);
100
  self::$settings->setGlobalOption('last_settings_update', time());
101
  }
102
 
103
- static function uninstallPlugin() {
104
  self::$logger->log('Running WP-Piwik uninstallation');
105
  if (!defined('WP_UNINSTALL_PLUGIN'))
106
  exit();
 
107
  self::$settings->resetSettings(true);
108
  }
109
 
110
- function upgradePlugin() {
111
  self::$logger->log('Upgrade WP-Piwik to '.self::$strVersion);
112
- add_action('admin_notices', array($this, 'updateMessage'));
113
  $patches = glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'update'.DIRECTORY_SEPARATOR.'*.php');
114
  if (is_array($patches)) {
115
  sort($patches);
@@ -119,494 +123,143 @@ class wp_piwik {
119
  self::includeFile('update'.DIRECTORY_SEPARATOR.$patchVersion);
120
  }
121
  }
122
- $this->installPlugin();
123
- }
124
-
125
- function updateMessage() {
126
- $text = sprintf(__('%s %s installed.', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), self::$strVersion);
127
- $notice = (!self::isConfigured()?
128
- __('Next you should connect to Piwik','wp-piwik'):
129
- __('Please validate your configuration','wp-piwik')
130
- );
131
- $link = sprintf('<a href="'.getSettingsURL.'?page=%s">%s</a>', self::$strPluginBasename, __('Settings', 'wp-piwik'));
132
- printf('<div class="updated fade"><p>%s<strong>%s:</strong> %s: %s</p></div>', $text, __('Important', 'wp-piwik'), $notice, $link);
133
  }
134
 
135
- function getSettingsURL() {
136
- return (self::$settings->checkNetworkActivation()?'settings':'options-general').'.php';
 
 
137
  }
138
 
139
- private function updateTrackingCode() {
140
- if (!self::$settings->getOption('site_id') || !self::$settings->getOption('tracking_code'))
141
- $this->addPiwikSite();
142
- if ($this->isCurrentTrackingCode()) {
143
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
144
- self::$settings->save();
145
- }
 
 
 
 
 
 
146
  }
147
 
148
- /* -- </REFACTORED><OLD> -- */
149
-
150
- function addJavascriptCode() {
151
  if ($this->isHiddenUser()) {
152
- self::$logger->log('Do not add tracking code to site header (user should not be tracked) Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
153
  return;
154
  }
155
- $this->updateTrackingCode();
156
-
157
- // Change code if 404
158
- if (is_404() && self::$settings->getGlobalOption('track_404')) {
159
- self::$logger->log('Apply 404 changes. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
160
- $strTrackingCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setDocumentTitle', '404/URL = '+String(document.location.pathname+document.location.search).replace(/\//g,'%2f') + '/From = ' + String(document.referrer).replace(/\//g,'%2f')]);\n_paq.push(['trackPageView']);", self::$settings->getOption('tracking_code'));
161
- }
162
- // Change code if search result
163
- elseif (is_search() && self::$settings->getGlobalOption('track_search')) {
164
- self::$logger->log('Apply search tracking changes. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
165
- $objSearch = new WP_Query("s=" . get_search_query() . '&showposts=-1');
166
- $intResultCount = $objSearch->post_count;
167
- $strTrackingCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['trackSiteSearch','".get_search_query()."', false, ".$intResultCount."]);\n_paq.push(['trackPageView']);", self::$settings->getOption('tracking_code'));
168
- // Use default tracking code
169
- } else
170
- $strTrackingCode = self::$settings->getOption('tracking_code');
171
- // Send tracking code
172
  self::$logger->log('Add tracking code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
173
- // Add custom variables if set:
174
- if (is_single()) {
175
- $strCustomVars = '';
176
- for ($i = 1; $i <= 5; $i++) {
177
- // Get post ID
178
- $intID = get_the_ID();
179
- // Get key
180
- $strMetaKey = get_post_meta($intID, 'wp-piwik_custom_cat'.$i, true);
181
- // Get value
182
- $strMetaVal = get_post_meta($intID, 'wp-piwik_custom_val'.$i, true);
183
- if (!empty($strMetaKey) && !empty($strMetaVal))
184
- $strCustomVars .= "_paq.push(['setCustomVariable',".$i.", '".$strMetaKey."', '".$strMetaVal."', 'page']);\n";
185
- }
186
- if (!empty($strCustomVars)) $strTrackingCode = str_replace("_paq.push(['trackPageView']);", $strCustomVars."_paq.push(['trackPageView']);", $strTrackingCode);
187
- }
188
- echo $strTrackingCode;
189
- $strName = get_bloginfo('name');
190
- if (self::$settings->getOption('name') != $strName)
191
- $this->updatePiwikSite();
192
  }
193
-
194
- function addNoscriptCode() {
195
- // Hotfix: Custom capability problem with WP multisite
196
- if (is_multisite()) {
197
- foreach (self::$settings->getGlobalOption('capability_stealth') as $strKey => $strVal)
198
- if ($strVal && current_user_can($strKey))
199
- return;
200
- // Don't add tracking code?
201
- } elseif (current_user_can('wp-piwik_stealth')) return;
202
- // Send tracking code
203
  self::$logger->log('Add noscript code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
204
  echo self::$settings->getOption('noscript_code')."\n";
205
  }
206
 
207
- /**
208
- * Shortcode function
209
- **/
210
-
211
- function shortcode($aryAttributes) {
212
- $this->aryAttributes = shortcode_atts(
213
- array(
214
- 'title' => '',
215
- 'module' => 'overview',
216
- 'period' => 'day',
217
- 'date' => 'yesterday',
218
- 'limit' => 10,
219
- 'width' => '100%',
220
- 'height' => '200px',
221
- 'language' => 'en',
222
- 'range' => false,
223
- 'key' => 'sum_daily_nb_uniq_visitors'
224
- ), $aryAttributes);
225
- switch ($this->aryAttributes['module']) {
226
- case 'opt-out':
227
- $this->strResult = '<iframe frameborder="no" width="'.$this->aryAttributes['width'].'" height="'.$this->aryAttributes['height'].'" src="'.self::$settings->getGlobalOption('piwik_url').'index.php?module=CoreAdminHome&action=optOut&language='.$this->aryAttributes['language'].'"></iframe>';
228
- break;
229
- case 'post':
230
- self::includeFile('shortcodes/post');
231
- break;
232
- case 'overview':
233
- default:
234
- self::includeFile('shortcodes/overview');
235
- }
236
- return $this->strResult;
237
- }
238
-
239
- /**
240
- * Add metaboxes to posts
241
- */
242
- function postMetaboxes() {
243
  if (self::$settings->getGlobalOption('add_customvars_box')) {
244
- add_action('add_meta_boxes', array(&$this, 'postAddMetaboxes'));
245
- add_action('save_post', array(&$this, 'postCustomvarsSave'), 10, 2);
246
  }
247
- // Show per post stats if enabled
248
  if (self::$settings->getGlobalOption('perpost_stats')) {
249
- $this->includeFile('classes/WP_Piwik_MetaBox_PerPost_Stats');
250
- add_action('add_meta_boxes', array(new WP_Piwik_MetaBox_PerPost_Stats($this->subClassConfig()), 'addMetabox'));
251
  }
252
  }
253
 
254
- /**
255
- * Create post meta boxes
256
- */
257
- function postAddMetaboxes() {
258
- add_meta_box(
259
- 'wp-piwik_post_customvars',
260
- __('Piwik Custom Variables', 'wp-piwik'),
261
- array(&$this, 'postCustomvars'),
262
- 'post',
263
- 'side',
264
- 'default'
265
- );
266
- }
267
-
268
- /**
269
- * Display custom variables meta box
270
- */
271
- function postCustomvars($objPost, $objBox ) {
272
- wp_nonce_field(basename( __FILE__ ), 'wp-piwik_post_customvars_nonce'); ?>
273
- <table>
274
- <tr><th></th><th><?php _e('Name', 'wp-piwik'); ?></th><th><?php _e('Value', 'wp-piwik'); ?></th></tr>
275
- <?php for($i = 1; $i <= 5; $i++) { ?>
276
- <tr>
277
- <th><label for="wp-piwik_customvar1"><?php echo $i; ?>: </label></th>
278
- <td><input class="widefat" type="text" name="wp-piwik_custom_cat<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_cat'.$i, true ) ); ?>" size="200" /></td>
279
- <td><input class="widefat" type="text" name="wp-piwik_custom_val<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_val'.$i, true ) ); ?>" size="200" /></td>
280
- </tr>
281
- <?php } ?>
282
- </table>
283
- <p><?php _e('Set custom variables for a page view', 'wp-piwik'); ?>. (<a href="http://piwik.org/docs/custom-variables/"><?php _e('More information', 'wp-piwik'); ?></a>.)</p>
284
- <?php
285
- }
286
-
287
- /**
288
- * Save post custom variables
289
- */
290
- function postCustomvarsSave($intID, $objPost) {
291
- // Verify the nonce before proceeding.
292
- if (!isset( $_POST['wp-piwik_post_customvars_nonce'] ) || !wp_verify_nonce( $_POST['wp-piwik_post_customvars_nonce'], basename( __FILE__ ) ) )
293
- return $intID;
294
- // Get post type object
295
- $objPostType = get_post_type_object($objPost->post_type);
296
- // Check if the current user has permission to edit the post.
297
- if (!current_user_can($objPostType->cap->edit_post, $intID))
298
- return $intID;
299
- $aryNames = array('cat', 'val');
300
- for ($i = 1; $i <= 5; $i++)
301
- for ($j = 0; $j <= 1; $j++) {
302
- // Get data
303
- $strMetaVal = (isset($_POST['wp-piwik_custom_'.$aryNames[$j].$i])?htmlentities($_POST['wp-piwik_custom_'.$aryNames[$j].$i]):'');
304
- // Create key
305
- $strMetaKey = 'wp-piwik_custom_'.$aryNames[$j].$i;
306
- // Get the meta value of the custom field key
307
- $strCurVal = get_post_meta($intID, $strMetaKey, true);
308
- // Add meta val:
309
- if ($strMetaVal && '' == $strCurVal)
310
- add_post_meta($intID, $strMetaKey, $strMetaVal, true);
311
- // Update meta val:
312
- elseif ($strMetaVal && $strMetaVal != $strCurVal)
313
- update_post_meta($intID, $strMetaKey, $strMetaVal);
314
- // Delete meta val:
315
- elseif (''==$strMetaVal && $strCurVal)
316
- delete_post_meta($intID, $strMetaKey, $strCurVal);
317
- }
318
- }
319
-
320
- /**
321
- * Add pages to admin menu
322
- */
323
- function buildAdminMenu() {
324
- // Show stats dashboard page if WP-Piwik is configured
325
  if (self::isConfigured()) {
326
- // Add dashboard page
327
- $this->intStatsPage = add_dashboard_page(
328
- __('Piwik Statistics', 'wp-piwik'),
329
- self::$settings->getGlobalOption('plugin_display_name'),
330
- 'wp-piwik_read_stats',
331
- 'wp-piwik_stats',
332
- array($this, 'showStats')
333
- );
334
- // Add required scripts
335
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadStatsScripts'));
336
- // Add required styles
337
- add_action('admin_print_styles-'.$this->intStatsPage, array($this, 'addAdminStyle'));
338
- // Add required header tags
339
- add_action('admin_head-'.$this->intStatsPage, array($this, 'addAdminHeaderStats'));
340
- // Stats page onload callback
341
- add_action('load-'.$this->intStatsPage, array(&$this, 'onloadStatsPage'));
342
  }
343
  if (!self::$settings->checkNetworkActivation()) {
344
- // Add options page
345
- $intOptionsPage = add_options_page(
346
- self::$settings->getGlobalOption('plugin_display_name'),
347
- self::$settings->getGlobalOption('plugin_display_name'),
348
- 'activate_plugins',
349
- __FILE__,
350
- array($this, 'showSettings')
351
- );
352
- // Add required scripts
353
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadSettingsScripts'));
354
- // Add required header tags
355
- add_action('admin_head-'.$intOptionsPage, array($this, 'addAdminHeaderSettings'));
356
- // Add styles required by options page
357
- add_action('admin_print_styles-'.$intOptionsPage, array($this, 'addAdminStyle'));
358
  }
359
  }
360
 
361
- /**
362
- * Add pages to network admin menu
363
- */
364
- function buildNetworkAdminMenu() {
365
- // Show stats dashboard page if WP-Piwik is configured
366
  if (self::isConfigured()) {
367
- // Add dashboard page
368
- $this->intStatsPage = add_dashboard_page(
369
- __('Piwik Statistics', 'wp-piwik'),
370
- self::$settings->getGlobalOption('plugin_display_name'),
371
- 'manage_sites',
372
- 'wp-piwik_stats',
373
- array($this, 'showStatsNetwork')
374
- );
375
- // Add required scripts
376
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadStatsScripts'));
377
- // Add required styles
378
- add_action('admin_print_styles-'.$this->intStatsPage, array($this, 'addAdminStyle'));
379
- // Add required header tags
380
- add_action('admin_head-'.$this->intStatsPage, array($this, 'addAdminHeaderStats'));
381
- // Stats page onload callback
382
- add_action('load-'.$this->intStatsPage, array(&$this, 'onloadStatsPage'));
383
  }
384
- $intOptionsPage = add_submenu_page(
385
- 'settings.php',
386
- self::$settings->getGlobalOption('plugin_display_name'),
387
- self::$settings->getGlobalOption('plugin_display_name'),
388
- 'manage_sites',
389
- __FILE__,
390
- array($this, 'showSettings')
391
- );
392
-
393
- // Add styles required by options page
394
- add_action('admin_print_styles-'.$intOptionsPage, array($this, 'addAdminStyle'));
395
- add_action('admin_head-'.$intOptionsPage, array($this, 'addAdminHeaderSettings'));
396
  }
397
 
398
- /**
399
- * Support two columns
400
- * seen in Heiko Rabe's metabox demo plugin
401
- *
402
- * @see http://tinyurl.com/5r5vnzs
403
- */
404
- function onScreenLayoutColumns($aryColumns, $strScreen) {
405
- if ($strScreen == $this->intStatsPage)
406
- $aryColumns[$this->intStatsPage] = 3;
407
- return $aryColumns;
408
- }
409
-
410
- /**
411
- * Add widgets to WordPress dashboard
412
- */
413
- function extendWordPressDashboard() {
414
- // Is user allowed to see stats?
415
  if (current_user_can('wp-piwik_read_stats')) {
416
- // TODO: Use bitmask here
417
- // Add data widget if enabled
418
- if (self::$settings->getGlobalOption('dashboard_widget'))
419
- $this->addWordPressDashboardWidget();
420
- // Add chart widget if enabled
421
- if (self::$settings->getGlobalOption('dashboard_chart')) {
422
- // Add required scripts
423
- add_action('admin_print_scripts-index.php', array($this, 'loadStatsScripts'));
424
- // Add required styles
425
- add_action('admin_print_styles-index.php', array($this, 'addAdminStyle'));
426
- // Add required header tags
427
- add_action('admin_head-index.php', array($this, 'addAdminHeaderStats'));
428
- $this->addWordPressDashboardChart();
429
- }
430
- // Add SEO widget if enabled
431
  if (self::$settings->getGlobalOption('dashboard_seo'))
432
- $this->addWordPressDashboardSEO();
433
  }
434
  }
435
 
436
- /**
437
- * Add widgets to WordPress Toolbar
438
- */
439
- public function extendWordPressToolbar(&$objToolbar) {
440
- // Is user allowed to see stats?
441
  if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
442
- $aryUnique = $this->callPiwikAPI('VisitsSummary.getUniqueVisitors','day','last30',null);
443
- if (!is_array($aryUnique)) $aryUnique = array();
444
- $strGraph = '<script type="text/javascript">';
445
- $strGraph .= "var \$jSpark = jQuery.noConflict();\$jSpark(function() {var piwikSparkVals=[".implode(',',$aryUnique)."];\$jSpark('.wp-piwik_dynbar').sparkline(piwikSparkVals, {type: 'bar', barColor: '#ccc', barWidth:2});});";
446
- $strGraph .= '</script>';
447
- $strGraph .= '<span class="wp-piwik_dynbar">Loading...</span>';
448
- $objToolbar->add_menu(array(
449
- 'id' => 'wp-piwik_stats',
450
- 'title' => $strGraph,
451
- 'href' => admin_url().'?page=wp-piwik_stats'
452
- ));
453
- }
454
- }
455
-
456
- /**
457
- * Add a data widget to the WordPress dashboard
458
- */
459
- function addWordPressDashboardWidget() {
460
- $aryConfig = array(
461
- 'params' => array('period' => 'day','date' => self::$settings->getGlobalOption('dashboard_widget'),'limit' => null),
462
- 'inline' => true,
463
- );
464
- $strFile = 'overview';
465
- add_meta_box(
466
- 'wp-piwik_stats-dashboard-overview',
467
- self::$settings->getGlobalOption('plugin_display_name').' - '.__(self::$settings->getGlobalOption('dashboard_widget'), 'wp-piwik'),
468
- array(&$this, 'createDashboardWidget'),
469
- 'dashboard',
470
- 'side',
471
- 'high',
472
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
473
- );
474
- }
475
-
476
- /**
477
- * Add a visitor chart to the WordPress dashboard
478
- */
479
- function addWordPressDashboardChart() {
480
- $aryConfig = array(
481
- 'params' => array('period' => 'day','date' => 'last30','limit' => null),
482
- 'inline' => true,
483
- );
484
- $strFile = 'visitors';
485
- add_meta_box(
486
- 'wp-piwik_stats-dashboard-chart',
487
- self::$settings->getGlobalOption('plugin_display_name').' - '.__('Visitors', 'wp-piwik'),
488
- array(&$this, 'createDashboardWidget'),
489
- 'dashboard',
490
- 'side',
491
- 'high',
492
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
493
- );
494
- }
495
-
496
- /**
497
- * Add a SEO widget to the WordPress dashboard
498
- */
499
- function addWordPressDashboardSEO() {
500
- $aryConfig = array(
501
- 'params' => array('period' => 'day','date' => 'today','limit' => null),
502
- 'inline' => true,
503
- );
504
- $strFile = 'seo';
505
- add_meta_box(
506
- 'wp-piwik_stats-dashboard-seo',
507
- self::$settings->getGlobalOption('plugin_display_name').' - '.__('SEO', 'wp-piwik'),
508
- array(&$this, 'createDashboardWidget'),
509
- 'dashboard',
510
- 'side',
511
- 'high',
512
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
513
- );
514
- }
515
-
516
- /**
517
- * Add plugin meta links to plugin details
518
- *
519
- * @see http://wpengineer.com/1295/meta-links-for-wordpress-plugins/
520
- */
521
- function setPluginMeta($strLinks, $strFile) {
522
- // Get plugin basename
523
- $strPlugin = plugin_basename(__FILE__);
524
- // Add link just to this plugin's details
525
- if ($strFile == self::$strPluginBasename)
526
- return array_merge(
527
- $strLinks,
528
- array(
529
- sprintf('<a href="'.(self::$settings->checkNetworkActivation()?'settings':'options-general').'.php?page=%s">%s</a>', self::$strPluginBasename, __('Settings', 'wp-piwik'))
530
- )
531
- );
532
- // Don't affect other plugins details
533
- return $strLinks;
534
  }
535
 
536
- /**
537
- * Load required scripts to stats page
538
- */
539
- function loadStatsScripts() {
540
- // Load WP-Piwik script
541
- wp_enqueue_script('wp-piwik', $this->getPluginURL().'js/wp-piwik.js', array(), self::$strVersion, true);
542
- // Load jqPlot
543
- wp_enqueue_script('wp-piwik-jqplot',$this->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
544
  }
545
 
546
- /**
547
- * Load scripts required by Toolbar graphs
548
- */
549
- function loadToolbarRequirements() {
550
- // Only load if user is allowed to see stats
551
  if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
552
- // Load Sparklines
553
- wp_enqueue_script('wp-piwik-sparkline',$this->getPluginURL().'js/sparkline/jquery.sparkline.min.js',array('jquery'),'2.1.1');
554
- // Load CSS
555
- wp_enqueue_style('wp-piwik', $this->getPluginURL().'css/wp-piwik-spark.css');
556
  }
557
  }
558
 
559
- /**
560
- * Load required scripts to settings page
561
- */
562
- function loadSettingsScripts() {
563
- wp_enqueue_script('jquery');
564
- }
565
-
566
- /**
567
- * Load required styles to admin pages
568
- */
569
- function addAdminStyle() {
570
- // Load WP-Piwik styles
571
- wp_enqueue_style('wp-piwik', $this->getPluginURL().'css/wp-piwik.css',array(),self::$strVersion);
572
- }
573
-
574
- /**
575
- * Add tracking code to admin header
576
- */
577
- function addAdminHeaderTracking() {
578
- $this->site_header();
579
- }
580
-
581
- /**
582
- * Add tracking image to feeds
583
- **/
584
- function addFeedTracking($content) {
585
  global $post;
586
  if(is_feed()) {
587
  self::$logger->log('Add tracking image to feed entry.');
588
- if (!self::$settings->getOption('site_id'))
589
- self::addPiwikSite();
590
  $title = the_title(null,null,false);
591
  $posturl = get_permalink($post->ID);
592
  $urlref = get_bloginfo('rss2_url');
593
  $url = self::$settings->getGlobalOption('piwik_url');
594
- if (substr($url, -10, 10) == '/index.php')
595
- $url = str_replace('/index.php', '/piwik.php', $url);
596
  else $url .= 'piwik.php';
597
- $trackingImage = $url.'?idsite='.self::$settings->getOption('site_id').'&amp;rec=1'.
598
- '&amp;url='.urlencode($posturl).
599
- '&amp;action_name='.urlencode($title).
600
- '&amp;urlref='.urlencode($urlref);
601
  $content .= '<img src="'.$trackingImage.'" style="border:0;width:0;height:0" width="0" height="0" alt="" />';
602
  }
603
  return $content;
604
  }
605
 
606
- /**
607
- * Add tracking image to feeds
608
- **/
609
- function addFeedCampaign($permalink) {
610
  global $post;
611
  if(is_feed()) {
612
  self::$logger->log('Add campaign to feed permalink.');
@@ -616,590 +269,19 @@ class wp_piwik {
616
  return $permalink;
617
  }
618
 
619
- function addPiwikAnnotation($postID) {
620
- $this->callPiwikAPI('Annotations.add', '', date('Y-m-d'), '', false, false, 'PHP', '', false, 'Published: '.get_post($postID)->post_title.' - URL: '.get_permalink($postID));
621
- }
622
-
623
- /**
624
- * Add required header tags to stats page
625
- */
626
- function addAdminHeaderStats() {
627
- // Load jqPlot IE compatibility script
628
- echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.$this->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
629
- // Load jqPlot styles
630
- echo '<link rel="stylesheet" href="'.$this->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
631
- echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
632
- }
633
-
634
- /**
635
- * Add required header tags to settings page
636
- */
637
- function addAdminHeaderSettings() {
638
- echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
639
- }
640
-
641
- /**
642
- * Get this plugin's URL
643
- */
644
- function getPluginURL() {
645
- // Return plugins URL + /wp-piwik/
646
- return trailingslashit(plugins_url().'/wp-piwik/');
647
- }
648
-
649
- /**
650
- * Call REST API
651
- *
652
- * @param $strURL Remote file URL
653
- */
654
- function callREST($strURL) {
655
- $strPiwikURL = self::$settings->getGlobalOption('piwik_url');
656
- if (substr($strPiwikURL, -1, 1) != '/') $strPiwikURL .= '/';
657
- $strURL = $strPiwikURL.'?module=API'.$strURL;
658
- // Use cURL if available
659
- if (function_exists('curl_init')) {
660
- // Init cURL
661
- $c = curl_init($strURL);
662
- // Disable SSL peer verification if asked to
663
- curl_setopt($c, CURLOPT_SSL_VERIFYPEER, !self::$settings->getGlobalOption('disable_ssl_verify'));
664
- // Set user agent
665
- curl_setopt($c, CURLOPT_USERAGENT, self::$settings->getGlobalOption('piwik_useragent')=='php'?ini_get('user_agent'):self::$settings->getGlobalOption('piwik_useragent_string'));
666
- // Configure cURL CURLOPT_RETURNTRANSFER = 1
667
- curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
668
- // Configure cURL CURLOPT_HEADER = 0
669
- curl_setopt($c, CURLOPT_HEADER, 0);
670
- // Set cURL timeout
671
- curl_setopt($c, CURLOPT_TIMEOUT, self::$settings->getGlobalOption('connection_timeout'));
672
- $httpProxyClass = new WP_HTTP_Proxy();
673
- if ($httpProxyClass->is_enabled() && $httpProxyClass->send_through_proxy($strURL)) {
674
- curl_setopt($c, CURLOPT_PROXY, $httpProxyClass->host());
675
- curl_setopt($c, CURLOPT_PROXYPORT, $httpProxyClass->port());
676
- if ($httpProxyClass->use_authentication())
677
- curl_setopt($c, CURLOPT_PROXYUSERPWD, $httpProxyClass->username().':'.$httpProxyClass->password());
678
- }
679
- // Get result
680
- $strResult = curl_exec($c);
681
- // Close connection
682
- curl_close($c);
683
- // cURL not available but url fopen allowed
684
- } elseif (ini_get('allow_url_fopen')) {
685
- // Set timeout
686
- $resContext = stream_context_create(array('http'=>array('timeout' => self::$settings->getGlobalOption('connection_timeout'))));
687
- // Get file using file_get_contents
688
- $strResult = @file_get_contents($strURL, false, $strContext);
689
- // Error: Not possible to get remote file
690
- } else $strResult = serialize(array(
691
- 'result' => 'error',
692
- 'message' => 'Remote access to Piwik not possible. Enable allow_url_fopen or CURL.'
693
- ));
694
- // Return result
695
- return $strResult;
696
- }
697
-
698
- /**
699
- * Call PHP API
700
- *
701
- * @param $strParams API call params
702
- */
703
- function callPHP($strParams) {
704
- if (!defined('PIWIK_INCLUDE_PATH'))
705
- return;
706
- if (PIWIK_INCLUDE_PATH === FALSE)
707
- return serialize(array('result' => 'error', 'message' => __('Could not resolve','wp-piwik').' &quot;'.htmlentities(self::$settings->getGlobalOption('piwik_path')).'&quot;: '.__('realpath() returns false','wp-piwik').'.'));
708
- if (file_exists(PIWIK_INCLUDE_PATH . "/index.php"))
709
- require_once PIWIK_INCLUDE_PATH . "/index.php";
710
- if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php"))
711
- require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
712
- if (class_exists('Piwik\FrontController'))
713
- Piwik\FrontController::getInstance()->init();
714
- else serialize(array('result' => 'error', 'message' => __('Class Piwik\FrontController does not exists.','wp-piwik')));
715
- if (class_exists('Piwik\API\Request'))
716
- $objRequest = new Piwik\API\Request($strParams);
717
- else serialize(array('result' => 'error', 'message' => __('Class Piwik\API\Request does not exists.','wp-piwik')));
718
- return $objRequest->process();
719
- }
720
-
721
- /**
722
- * Get remote file
723
- *
724
- * @param String $strURL Remote file URL
725
- */
726
- function getRemoteFile($strURL, $blogURL = '') {
727
- if (self::$settings->getGlobalOption('piwik_mode') == 'php')
728
- return $this->callPHP($strURL.($blogURL?'&url='.$blogURL:''));
729
- else
730
- return $this->callREST($strURL.($blogURL?'&url='.urlencode($blogURL):''));
731
- }
732
-
733
- /**
734
- * Add a new site to Piwik if a new blog was requested,
735
- * or get its ID by URL
736
- */
737
- function addPiwikSite() {
738
- if (isset($_GET['wpmu_show_stats']) && self::$settings->checkNetworkActivation()) {
739
- self::$logger->log('Switch blog ID: '.(int) $_GET['wpmu_show_stats']);
740
- switch_to_blog((int) $_GET['wpmu_show_stats']);
741
- }
742
- self::$logger->log('Get the blog\'s site ID by URL: '.get_bloginfo('url'));
743
- // Check if blog URL already known
744
- $strURL = '&method=SitesManager.getSitesIdFromSiteUrl';
745
- $strURL .= '&format=PHP';
746
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
747
- $aryResult = unserialize($this->getRemoteFile($strURL, get_bloginfo('url')));
748
- if (!empty($aryResult) && isset($aryResult[0]['idsite'])) {
749
- self::$settings->setOption('site_id', (int) $aryResult[0]['idsite']);
750
- // Otherwise create new site
751
- } elseif (self::isConfigured() && !empty($strURL)) {
752
- self::$logger->log('Blog not known yet - create new site');
753
- $strName = get_bloginfo('name');
754
- if (empty($strName)) $strName = get_bloginfo('url');
755
- self::$settings->setOption('name', $strName);
756
- $strURL .= '&method=SitesManager.addSite';
757
- $strURL .= '&siteName='.urlencode($strName).'&urls='.urlencode(get_bloginfo('url'));
758
- $strURL .= '&format=PHP';
759
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
760
- $strResult = unserialize($this->getRemoteFile($strURL, get_bloginfo('url')));
761
- if (!empty($strResult)) self::$settings->setOption('site_id', (int) $strResult);
762
- }
763
- // Store new data if site created
764
- if (self::$settings->getOption('site_id')) {
765
- self::$logger->log('Get the site\'s tracking code');
766
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
767
- } else self::$settings->getOption('tracking_code', '');
768
- self::$settings->save();
769
- if (isset($_GET['wpmu_show_stats']) && self::$settings->checkNetworkActivation()) {
770
- self::$logger->log('Back to current blog');
771
- restore_current_blog();
772
- }
773
- return array('js' => self::$settings->getOption('tracking_code'), 'id' => self::$settings->getOption('site_id'));
774
- }
775
-
776
- /**
777
- * Update a site
778
- */
779
- function updatePiwikSite() {
780
- $strBlogURL = get_bloginfo('url');
781
- // Check if blog URL already known
782
- $strName = get_bloginfo('name');
783
- if (empty($strName)) $strName = $strBlogURL;
784
- self::$settings->setOption('name', $strName);
785
- $strURL = '&method=SitesManager.updateSite';
786
- $strURL .= '&idSite='.self::$settings->getOption('site_id');
787
- $strURL .= '&siteName='.urlencode($strName).'&urls='.urlencode($strBlogURL);
788
- $strURL .= '&format=PHP';
789
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
790
- $strResult = unserialize($this->getRemoteFile($strURL));
791
- // Store new data
792
- self::$settings->getOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
793
- self::$settings->save();
794
- }
795
-
796
- /**
797
- * Apply configured Tracking Code changes
798
- */
799
- function applyJSCodeChanges($strCode) {
800
- self::$logger->log('Apply tracking code changes.');
801
- self::$settings->setOption('last_tracking_code_update', time());
802
- $strCode = html_entity_decode($strCode);
803
- // Change code if js/index.php should be used
804
- if (self::$settings->getGlobalOption('track_mode') == 1) {
805
- $strCode = str_replace('piwik.js', 'js/', $strCode);
806
- $strCode = str_replace('piwik.php', 'js/', $strCode);
807
- } elseif (self::$settings->getGlobalOption('track_mode') == 2) {
808
- $strCode = str_replace('piwik.js', 'piwik.php', $strCode);
809
- $strURL = str_replace('https://', '://', self::$settings->getGlobalOption('piwik_url'));
810
- $strURL = str_replace('http://', '://', $strURL);
811
- $strProxy = str_replace('https://', '://', plugins_url('wp-piwik'));
812
- $strProxy = str_replace('http://', '://', $strProxy);
813
- $strProxy .= '/';
814
- $strCode = str_replace($strURL, $strProxy, $strCode);
815
- }
816
- $strCode = str_replace('//";','/"',$strCode);
817
- if (self::$settings->getGlobalOption('track_cdnurl')||self::$settings->getGlobalOption('track_cdnurlssl')) {
818
- $strCode = str_replace("var d=doc", "var ucdn=(('https:' == document.location.protocol) ? 'https://".(self::$settings->getGlobalOption('track_cdnurlssl')?self::$settings->getGlobalOption('track_cdnurlssl'):self::$settings->getGlobalOption('track_cdnurl'))."/' : 'http://".(self::$settings->getGlobalOption('track_cdnurl')?self::$settings->getGlobalOption('track_cdnurl'):self::$settings->getGlobalOption('track_cdnurlssl'))."/');\nvar d=doc", $strCode);
819
- $strCode = str_replace("g.src=u+", "g.src=ucdn+", $strCode);
820
- }
821
- // Change code if POST is forced to be used
822
- if (self::$settings->getGlobalOption('track_post') && self::$settings->getGlobalOption('track_mode') != 2) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setRequestMethod', 'POST']);\n_paq.push(['trackPageView']);", $strCode);
823
- // Change code if cookies are disabled
824
- if (self::$settings->getGlobalOption('track_across')) {
825
- $referrerParsed = parse_url(get_bloginfo('url'));
826
- $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setCookieDomain', '*.".$referrerParsed['host']."']);\n_paq.push(['trackPageView']);", $strCode);
827
- }
828
- if (self::$settings->getGlobalOption('disable_cookies')) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['disableCookies']);\n_paq.push(['trackPageView']);", $strCode);
829
- if (self::$settings->getGlobalOption('limit_cookies')) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '".self::$settings->getGlobalOption('limit_cookies_visitor')."']);\n_paq.push(['setSessionCookieTimeout', '".self::$settings->getGlobalOption('limit_cookies_session')."']);\n_paq.push(['trackPageView']);", $strCode);
830
- // Store <noscript> code
831
- $aryNoscript = array();
832
- preg_match('/<noscript>(.*)<\/noscript>/', $strCode, $aryNoscript);
833
- if (isset($aryNoscript[0])) {
834
- if (self::$settings->getGlobalOption('track_nojavascript'))
835
- $aryNoscript[0] = str_replace('?idsite', '?rec=1&idsite', $aryNoscript[0]);
836
- self::$settings->setOption('noscript_code', $aryNoscript[0]);
837
- }
838
- if (self::$settings->getGlobalOption('track_datacfasync'))
839
- $strCode = str_replace('<script type', '<script data-cfasync="false" type', $strCode);
840
- // Remove <noscript> code
841
- $strCode = preg_replace('/<noscript>(.*)<\/noscript>/', '', $strCode);
842
- // Return code without empty lines
843
- return preg_replace('/\s+(\r\n|\r|\n)/', '$1', $strCode);
844
- }
845
-
846
- /**
847
- * Create a WordPress dashboard widget
848
- */
849
- function createDashboardWidget($objPost, $aryMetabox) {
850
- // Create description and ID
851
- $strDesc = $strID = '';
852
- $aryConfig = $aryMetabox['args']['aryConfig'];
853
- foreach ($aryConfig['params'] as $strParam)
854
- if (!empty($strParam)) {
855
- $strDesc .= $strParam.', ';
856
- $strID .= '_'.$strParam;
857
- }
858
- // Remove dots from filename
859
- $strFile = str_replace('.', '', $aryMetabox['args']['strFile']);
860
- // Finalize configuration
861
- $aryConf = array_merge($aryConfig, array(
862
- 'id' => $strFile.$strID,
863
- 'desc' => substr($strDesc, 0, -2)));
864
- // Include widget file
865
- if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'dashboard/'.$strFile.'.php'))
866
- include(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'dashboard/'.$strFile.'.php');
867
- }
868
-
869
- /**
870
- * Call Piwik's API
871
- */
872
- function callPiwikAPI($strMethod, $strPeriod='', $strDate='', $intLimit='',$bolExpanded=false, $intId = false, $strFormat = 'PHP', $strPageURL = '', $useCache = true, $strNote = '') {
873
- // Create unique cache key
874
- $strKey = 'wp-piwik_'.md5($strMethod.'_'.$strPeriod.'_'.$strDate.'_'.$intLimit.'_'.self::$settings->getGlobalOption('piwik_token').'_'.self::$settings->getGlobalOption('piwik_url').'_'.$intId.'_'.$strPageURL);
875
- // Call API if data not cached
876
- if (self::$settings->getGlobalOption('cache') && $useCache) {
877
- $result = get_transient($strKey);
878
- self::$logger->log('API method: '.$strMethod.' Fetch call from cache: '.$strKey);
879
- } else $result = false;
880
- if ($strMethod == "SitesManager.getSitesWithAtLeastViewAccess" || false === $result) {
881
- $strToken = self::$settings->getGlobalOption('piwik_token');
882
- // If multisite stats are shown, maybe the super admin wants to show other blog's stats.
883
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && function_exists('wp_get_current_user') && is_super_admin() && isset($_GET['wpmu_show_stats'])) {
884
- $aryOptions = get_blog_option((int) $_GET['wpmu_show_stats'], 'wp-piwik_settings' , array());
885
- if (!empty($aryOptions) && isset($aryOptions['site_id']))
886
- $intSite = $aryOptions['site_id'];
887
- else $intSite = self::$settings->getOption('site_id');
888
- // Otherwise use the current site's id.
889
- } else {
890
- if (!self::$settings->getOption('site_id'))
891
- self::addPiwikSite();
892
- $intSite = self::$settings->getOption('site_id');
893
- }
894
- //die($intSite);
895
- // Create error message if WP-Piwik isn't configured
896
- if (!self::isConfigured()) {
897
- $result = array(
898
- 'result' => 'error',
899
- 'message' => 'Piwik URL/path or auth token not set.'
900
- );
901
- return $result;
902
- }
903
- // Build URL
904
- $strURL = '&method='.$strMethod;
905
- $strURL .= '&idSite='.(int)$intSite.'&period='.$strPeriod.'&date='.$strDate;
906
- $strURL .= '&filter_limit='.$intLimit;
907
- $strURL .= '&token_auth='.$strToken;
908
- $strURL .= '&expanded='.$bolExpanded;
909
- $strURL .= '&format='.$strFormat;
910
- $strURL .= ($strPageURL?'&pageUrl='.urlencode($strPageURL):'');
911
- $strURL .= ($strNote?'&note='.urlencode($strNote):'');
912
- // Fetch data if site exists
913
- if (!empty($intSite) || $strMethod='SitesManager.getSitesWithAtLeastViewAccess') {
914
- self::$logger->log('API method: '.$strMethod.' API call: '.$strURL);
915
- $strResult = (string) $this->getRemoteFile($strURL, get_bloginfo('url'));
916
- $result = ($strFormat == 'PHP'?unserialize($strResult):$strResult);
917
- // Apply tracking code changes if configured
918
- if ($strMethod == 'SitesManager.getJavascriptTag' && !empty($result)) {
919
- $result = is_string($result)?$this->applyJSCodeChanges($result):'<!-- WP-Piwik ERROR: Tracking code not availbale -->'."\n";
920
- }
921
- // Otherwise return error message
922
- } else $result = array('result' => 'error', 'message' => 'Unknown site/blog.');
923
- if (
924
- $strMethod != 'SitesManager.getJavascriptTag' &&
925
- $strDate != 'today' && $strDate != date('Ymd') && substr($strDate, 0, 4) != 'last' &&
926
- self::$settings->getGlobalOption('cache') &&
927
- !(isset($result['result']) && $result['result'] == 'error')&&
928
- !empty($result)
929
- ) set_transient($strKey, $result, WEEK_IN_SECONDS);
930
- }
931
- return $result;
932
- }
933
-
934
- /* TODO: Add post stats
935
- * function display_post_unique_column($aryCols) {
936
- * $aryCols['wp-piwik_unique'] = __('Unique');
937
- * return $aryCols;
938
- * }
939
- *
940
- * function display_post_unique_content($strCol, $intID) {
941
- * if( $strCol == 'wp-piwik_unique' ) {
942
- * }
943
- * }
944
- */
945
-
946
- function onloadStatsPage() {
947
- wp_enqueue_script('common');
948
- wp_enqueue_script('wp-lists');
949
- wp_enqueue_script('postbox');
950
- $strToken = self::$settings->getGlobalOption('piwik_token');
951
- $strPiwikURL = self::$settings->getGlobalOption('piwik_url');
952
- $aryDashboard = array();
953
- // Set default configuration
954
- $arySortOrder = array(
955
- 'side' => array(
956
- 'overview' => array(__('Overview', 'wp-piwik'), 'day', 'yesterday'),
957
- 'seo' => array(__('SEO', 'wp-piwik'), 'day', 'yesterday'),
958
- 'pages' => array(__('Pages', 'wp-piwik'), 'day', 'yesterday'),
959
- 'keywords' => array(__('Keywords', 'wp-piwik'), 'day', 'yesterday', 10),
960
- 'websites' => array(__('Websites', 'wp-piwik'), 'day', 'yesterday', 10),
961
- 'plugins' => array(__('Plugins', 'wp-piwik'), 'day', 'yesterday'),
962
- 'search' => array(__('Site Search Keywords', 'wp-piwik'), 'day', 'yesterday', 10),
963
- 'noresult' => array(__('Site Search without Results', 'wp-piwik'), 'day', 'yesterday', 10),
964
- ),
965
- 'normal' => array(
966
- 'visitors' => array(__('Visitors', 'wp-piwik'), 'day', 'last30'),
967
- 'browsers' => array(__('Browser', 'wp-piwik'), 'day', 'yesterday'),
968
- 'browserdetails' => array(__('Browser Details', 'wp-piwik'), 'day', 'yesterday'),
969
- 'screens' => array(__('Resolution', 'wp-piwik'), 'day', 'yesterday'),
970
- 'systems' => array(__('Operating System', 'wp-piwik'), 'day', 'yesterday')
971
- )
972
- );
973
- // Don't show SEO stats if disabled
974
- if (!self::$settings->getGlobalOption('stats_seo'))
975
- unset($arySortOrder['side']['seo']);
976
-
977
- foreach ($arySortOrder as $strCol => $aryWidgets) {
978
- if (is_array($aryWidgets)) foreach ($aryWidgets as $strFile => $aryParams) {
979
- $aryDashboard[$strCol][$strFile] = array(
980
- 'params' => array(
981
- 'title' => (isset($aryParams[0])?$aryParams[0]:$strFile),
982
- 'period' => (isset($aryParams[1])?$aryParams[1]:''),
983
- 'date' => (isset($aryParams[2])?$aryParams[2]:''),
984
- 'limit' => (isset($aryParams[3])?$aryParams[3]:'')
985
- )
986
- );
987
- if (isset($_GET['date']) && preg_match('/^[0-9]{8}$/', $_GET['date']) && $strFile != 'visitors')
988
- $aryDashboard[$strCol][$strFile]['params']['date'] = $_GET['date'];
989
- elseif ($strFile != 'visitors')
990
- $aryDashboard[$strCol][$strFile]['params']['date'] = self::$settings->getGlobalOption('default_date');
991
- }
992
- }
993
- $intSideBoxCnt = $intContentBox = 0;
994
- foreach ($aryDashboard['side'] as $strFile => $aryConfig) {
995
- $intSideBoxCnt++;
996
- if (preg_match('/(\d{4})(\d{2})(\d{2})/', $aryConfig['params']['date'], $aryResult))
997
- $strDate = $aryResult[1]."-".$aryResult[2]."-".$aryResult[3];
998
- else $strDate = $aryConfig['params']['date'];
999
- add_meta_box(
1000
- 'wp-piwik_stats-sidebox-'.$intSideBoxCnt,
1001
- $aryConfig['params']['title'].' '.($aryConfig['params']['title']!='SEO'?__($strDate, 'wp-piwik'):''),
1002
- array(&$this, 'createDashboardWidget'),
1003
- $this->intStatsPage,
1004
- 'side',
1005
- 'core',
1006
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
1007
- );
1008
- }
1009
- foreach ($aryDashboard['normal'] as $strFile => $aryConfig) {
1010
- if (preg_match('/(\d{4})(\d{2})(\d{2})/', $aryConfig['params']['date'], $aryResult))
1011
- $strDate = $aryResult[1]."-".$aryResult[2]."-".$aryResult[3];
1012
- else $strDate = $aryConfig['params']['date'];
1013
- $intContentBox++;
1014
- add_meta_box(
1015
- 'wp-piwik_stats-contentbox-'.$intContentBox,
1016
- $aryConfig['params']['title'].' '.($aryConfig['params']['title']!='SEO'?__($strDate, 'wp-piwik'):''),
1017
- array(&$this, 'createDashboardWidget'),
1018
- $this->intStatsPage,
1019
- 'normal',
1020
- 'core',
1021
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
1022
- );
1023
- }
1024
- }
1025
-
1026
- // Open stats page as network admin
1027
- function showStatsNetwork() {
1028
- $this->bolNetwork = true;
1029
- $this->showStats();
1030
- }
1031
-
1032
- function showStats() {
1033
- // Disabled time limit if required
1034
- if (self::$settings->getGlobalOption('disable_timelimit') && self::$settings->getGlobalOption('disable_timelimit'))
1035
- set_time_limit(0);
1036
- //we need the global screen column value to be able to have a sidebar in WordPress 2.8
1037
- global $screen_layout_columns;
1038
- if (empty($screen_layout_columns)) $screen_layout_columns = 2;
1039
- /***************************************************************************/ ?>
1040
- <div id="wp-piwik-stats-general" class="wrap">
1041
- <?php screen_icon('options-general'); ?>
1042
- <h2><?php echo (self::$settings->getGlobalOption('plugin_display_name') == 'WP-Piwik'?'Piwik '.__('Statistics', 'wp-piwik'):self::$settings->getGlobalOption('plugin_display_name')); ?></h2>
1043
- <?php /************************************************************************/
1044
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin() && $this->bolNetwork) {
1045
- if (isset($_GET['wpmu_show_stats'])) {
1046
- switch_to_blog((int) $_GET['wpmu_show_stats']);
1047
- // TODO OPTIMIZE
1048
- } else {
1049
- $this->includeFile('settings/sitebrowser');
1050
- return;
1051
- }
1052
- echo '<p>'.__('Currently shown stats:').' <a href="'.get_bloginfo('url').'">'.(int) $_GET['wpmu_show_stats'].' - '.get_bloginfo('name').'</a>.'.' <a href="?page=wp-piwik_stats">Show site overview</a>.</p>'."\n";
1053
- echo '</form>'."\n";
1054
- }
1055
- /***************************************************************************/ ?>
1056
- <form action="admin-post.php" method="post">
1057
- <?php wp_nonce_field('wp-piwik_stats-general'); ?>
1058
- <?php wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false ); ?>
1059
- <?php wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?>
1060
- <input type="hidden" name="action" value="save_wp-piwik_stats_general" />
1061
- <div id="dashboard-widgets" class="metabox-holder columns-<?php echo $screen_layout_columns; ?><?php echo 2 <= $screen_layout_columns?' has-right-sidebar':''; ?>">
1062
- <div id='postbox-container-1' class='postbox-container'>
1063
- <?php $meta_boxes = do_meta_boxes($this->intStatsPage, 'normal', null); ?>
1064
- </div>
1065
-
1066
- <div id='postbox-container-2' class='postbox-container'>
1067
- <?php do_meta_boxes($this->intStatsPage, 'side', null); ?>
1068
- </div>
1069
-
1070
- <div id='postbox-container-3' class='postbox-container'>
1071
- <?php do_meta_boxes($this->intStatsPage, 'column3', null); ?>
1072
- </div>
1073
-
1074
- </div>
1075
- </form>
1076
- </div>
1077
- <script type="text/javascript">
1078
- //<![CDATA[
1079
- jQuery(document).ready( function($) {
1080
- // close postboxes that should be closed
1081
- $('.if-js-closed').removeClass('if-js-closed').addClass('closed');
1082
- // postboxes setup
1083
- postboxes.add_postbox_toggles('<?php echo $this->intStatsPage; ?>');
1084
- });
1085
- //]]>
1086
- </script>
1087
- <?php /************************************************************************/
1088
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
1089
- restore_current_blog();
1090
- }
1091
- }
1092
-
1093
- /* Stats page changes by POST submit
1094
- seen in Heiko Rabe's metabox demo plugin
1095
- http://tinyurl.com/5r5vnzs */
1096
- function onStatsPageSaveChanges() {
1097
- //user permission check
1098
- if ( !current_user_can('manage_options') )
1099
- wp_die( __('Cheatin&#8217; uh?') );
1100
- //cross check the given referer
1101
- check_admin_referer('wp-piwik_stats');
1102
- //process here your on $_POST validation and / or option saving
1103
- //lets redirect the post request into get request (you may add additional params at the url, if you need to show save results
1104
- wp_redirect($_POST['_wp_http_referer']);
1105
- }
1106
-
1107
- /**
1108
- * Add tabs to settings page
1109
- * See http://wp.smashingmagazine.com/2011/10/20/create-tabs-wordpress-settings-pages/
1110
- */
1111
- function showSettingsTabs($bolFull = true, $strCurr = 'homepage') {
1112
- $aryTabs = ($bolFull?array(
1113
- 'homepage' => __('Home','wp-piwik'),
1114
- 'piwik' => __('Piwik Settings','wp-piwik'),
1115
- 'tracking' => __('Tracking','wp-piwik'),
1116
- 'views' => __('Statistics','wp-piwik'),
1117
- 'support' => __('Support','wp-piwik'),
1118
- 'credits' => __('Credits','wp-piwik')
1119
- ):array(
1120
- 'piwik' => __('Piwik Settings','wp-piwik'),
1121
- 'support' => __('Support','wp-piwik'),
1122
- 'credits' => __('Credits','wp-piwik')
1123
  ));
1124
- if (empty($strCurr)) $strCurr = 'homepage';
1125
- elseif (!isset($aryTabs[$strCurr]) && $strCurr != 'sitebrowser') $strCurr = 'piwik';
1126
- echo '<div id="icon-themes" class="icon32"><br></div>';
1127
- echo '<h2 class="nav-tab-wrapper">';
1128
- foreach($aryTabs as $strTab => $strName) {
1129
- $strClass = ($strTab == $strCurr?' nav-tab-active':'');
1130
- echo '<a class="nav-tab'.$strClass.'" href="?page=wp-piwik/classes/WP_Piwik.php&tab='.$strTab.'">'.$strName.'</a>';
1131
- }
1132
- echo '</h2>';
1133
- return $strCurr;
1134
  }
1135
-
1136
- /**
1137
- * Apply & store new settings
1138
- */
1139
- function applySettings() {
1140
- $strTab = (isset($_GET['tab'])?$_GET['tab']:'homepage');
1141
- self::$logger->log('Apply changes: '.$strTab);
1142
- switch ($strTab) {
1143
- case 'views':
1144
- self::$settings->setGlobalOption('plugin_display_name', (!empty($_POST['wp-piwik_displayname'])?htmlentities($_POST['wp-piwik_displayname']):'WP-Piwk'));
1145
- self::$settings->setGlobalOption('dashboard_widget',(isset($_POST['wp-piwik_dbwidget'])?$_POST['wp-piwik_dbwidget']:0));
1146
- self::$settings->setGlobalOption('dashboard_chart',(isset($_POST['wp-piwik_dbchart'])?$_POST['wp-piwik_dbchart']:false));
1147
- self::$settings->setGlobalOption('dashboard_seo',(isset($_POST['wp-piwik_dbseo'])?$_POST['wp-piwik_dbseo']:false));
1148
- self::$settings->setGlobalOption('stats_seo',(isset($_POST['wp-piwik_statsseo'])?$_POST['wp-piwik_statsseo']:false));
1149
- self::$settings->setGlobalOption('piwik_shortcut', (isset($_POST['wp-piwik_piwiklink'])?$_POST['wp-piwik_piwiklink']:false));
1150
- self::$settings->setGlobalOption('default_date', (isset($_POST['wp-piwik_default_date'])?$_POST['wp-piwik_default_date']:'yesterday'));
1151
- self::$settings->setGlobalOption('capability_read_stats', (isset($_POST['wp-piwik_displayto'])?$_POST['wp-piwik_displayto']:array()));
1152
- self::$settings->setGlobalOption('disable_timelimit', (isset($_POST['wp-piwik_disabletimelimit'])?$_POST['wp-piwik_disabletimelimit']:false));
1153
- self::$settings->setGlobalOption('toolbar', (isset($_POST['wp-piwik_toolbar'])?$_POST['wp-piwik_toolbar']:false));
1154
- self::$settings->setGlobalOption('shortcodes', (isset($_POST['wp-piwik_shortcodes'])?$_POST['wp-piwik_shortcodes']:false));
1155
- self::$settings->setGlobalOption('perpost_stats', (isset($_POST['wp-piwik_perpost'])?$_POST['wp-piwik_perpost']:false));
1156
- break;
1157
- case 'tracking':
1158
- self::$settings->setGlobalOption('add_tracking_code', (isset($_POST['wp-piwik_addjs'])?$_POST['wp-piwik_addjs']:false));
1159
- self::$settings->setGlobalOption('track_404', (isset($_POST['wp-piwik_404'])?$_POST['wp-piwik_404']:false));
1160
- self::$settings->setGlobalOption('track_search', (isset($_POST['wp-piwik_search'])?$_POST['wp-piwik_search']:false));
1161
- self::$settings->setGlobalOption('track_mode', (isset($_POST['wp-piwik_trackingmode'])?(int)$_POST['wp-piwik_trackingmode']:0));
1162
- self::$settings->setGlobalOption('track_post', (isset($_POST['wp-piwik_reqpost'])?$_POST['wp-piwik_reqpost']:false));
1163
- self::$settings->setGlobalOption('track_proxy', (isset($_POST['wp-piwik_proxy'])?$_POST['wp-piwik_proxy']:false));
1164
- self::$settings->setGlobalOption('track_cdnurl', trim(isset($_POST['wp-piwik_cdnurl'])?$_POST['wp-piwik_cdnurl']:''));
1165
- self::$settings->setGlobalOption('track_cdnurlssl', trim(isset($_POST['wp-piwik_cdnurlssl'])?$_POST['wp-piwik_cdnurlssl']:self::$settings->getGlobalOption('track_cdnurl')));
1166
- self::$settings->setGlobalOption('track_noscript', (isset($_POST['wp-piwik_noscript'])?$_POST['wp-piwik_noscript']:false));
1167
- self::$settings->setGlobalOption('track_codeposition', (isset($_POST['wp-piwik_codeposition'])?$_POST['wp-piwik_codeposition']:'footer'));
1168
- self::$settings->setGlobalOption('track_nojavascript', (isset($_POST['wp-piwik_nojavascript'])?$_POST['wp-piwik_nojavascript']:false));
1169
- self::$settings->setGlobalOption('track_admin', (isset($_POST['wp-piwik_trackadmin'])?$_POST['wp-piwik_trackadmin']:false));
1170
- self::$settings->setGlobalOption('track_feed', (isset($_POST['wp-piwik_trackfeed'])?$_POST['wp-piwik_trackfeed']:false));
1171
- self::$settings->setGlobalOption('track_feed_goal', (isset($_POST['wp-piwik_trackfeed_goal'])&&!empty($_POST['wp-piwik_trackfeed_goal'])?(int)$_POST['wp-piwik_trackfeed_goal']:''));
1172
- self::$settings->setGlobalOption('track_feed_revenue', (isset($_POST['wp-piwik_trackfeed_revenue'])&&!empty($_POST['wp-piwik_trackfeed_revenue'])?(int)$_POST['wp-piwik_trackfeed_revenue']:''));
1173
- self::$settings->setGlobalOption('track_feed_campaign', (isset($_POST['wp-piwik_trackfeed_campaign'])?$_POST['wp-piwik_trackfeed_campaign']:'feed'));
1174
- self::$settings->setGlobalOption('track_feed_addcampaign', (isset($_POST['wp-piwik_trackfeed_addcampaign'])?$_POST['wp-piwik_trackfeed_addcampaign']:false));
1175
- self::$settings->setGlobalOption('track_datacfasync', (isset($_POST['wp-piwik_datacfasync'])?$_POST['wp-piwik_datacfasync']:false));
1176
- self::$settings->setGlobalOption('track_across', (isset($_POST['wp-piwik_track_across'])?$_POST['wp-piwik_track_across']:false));
1177
- self::$settings->setGlobalOption('add_post_annotations', (isset($_POST['wp-piwik_annotations'])?$_POST['wp-piwik_annotations']:false));
1178
- self::$settings->setGlobalOption('add_customvars_box', (isset($_POST['wp-piwik_customvars'])?$_POST['wp-piwik_customvars']:false));
1179
- self::$settings->setGlobalOption('capability_stealth', (isset($_POST['wp-piwik_filter'])?$_POST['wp-piwik_filter']:array()));
1180
- self::$settings->setGlobalOption('disable_cookies', (isset($_POST['wp-piwik_disable_cookies'])?$_POST['wp-piwik_disable_cookies']:false));
1181
- self::$settings->setGlobalOption('limit_cookies', (isset($_POST['wp-piwik_limit_cookies'])?$_POST['wp-piwik_limit_cookies']:false));
1182
- self::$settings->setGlobalOption('limit_cookies_visitor', (isset($_POST['wp-piwik_limit_cookies_visitor'])?(int)$_POST['wp-piwik_limit_cookies_visitor']:1209600));
1183
- self::$settings->setGlobalOption('limit_cookies_session', (isset($_POST['wp-piwik_limit_cookies_session'])?(int)$_POST['wp-piwik_limit_cookies_session']:0));
1184
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
1185
- break;
1186
- case 'piwik':
1187
- self::$settings->setGlobalOption('piwik_token', (isset($_POST['wp-piwik_token'])?$_POST['wp-piwik_token']:''));
1188
- self::$settings->setGlobalOption('piwik_url', self::checkURL((isset($_POST['wp-piwik_url'])?$_POST['wp-piwik_url']:'')));
1189
- self::$settings->setGlobalOption('piwik_path', (isset($_POST['wp-piwik_path']) && !empty($_POST['wp-piwik_path'])?realpath($_POST['wp-piwik_path']):''));
1190
- self::$settings->setGlobalOption('cache', (isset($_POST['wp-piwik_cache'])?$_POST['wp-piwik_cache']:false));
1191
- self::$settings->setGlobalOption('piwik_mode', (isset($_POST['wp-piwik_mode'])?$_POST['wp-piwik_mode']:'http'));
1192
- self::$settings->setGlobalOption('piwik_useragent', (isset($_POST['wp-piwik_useragent'])?$_POST['wp-piwik_useragent']:'php'));
1193
- self::$settings->setGlobalOption('connection_timeout', (isset($_POST['wp-piwik_timeout'])?(int)$_POST['wp-piwik_timeout']:5));
1194
- self::$settings->setGlobalOption('piwik_useragent_string', (isset($_POST['wp-piwik_useragent_string'])?$_POST['wp-piwik_useragent_string']:'WP-Piwik'));
1195
- self::$settings->setGlobalOption('disable_ssl_verify', (isset($_POST['wp-piwik_disable_ssl_verify'])?$_POST['wp-piwik_disable_ssl_verify']:false));
1196
- if (!self::$settings->checkNetworkActivation()) {
1197
- self::$settings->setGlobalOption('auto_site_config', (isset($_POST['wp-piwik_auto_site_config'])?$_POST['wp-piwik_auto_site_config']:false));
1198
- if (!self::$settings->getGlobalOption('auto_site_config'))
1199
- self::$settings->setOption('site_id', (isset($_POST['wp-piwik_siteid'])?$_POST['wp-piwik_siteid']:self::$settings->getOption('site_id')));
1200
- } else self::$settings->setGlobalOption('auto_site_config', true);
1201
- break;
1202
- }
1203
  if (self::$settings->getGlobalOption('auto_site_config') && self::isConfigured()) {
1204
  if (self::$settings->getGlobalOption('piwik_mode') == 'php' && !defined('PIWIK_INCLUDE_PATH'))
1205
  self::definePiwikConstants();
@@ -1207,136 +289,19 @@ class wp_piwik {
1207
  self::$settings->getOption('tracking_code', $aryReturn['js']);
1208
  self::$settings->getOption('site_id', $aryReturn['id']);
1209
  }
1210
- self::$settings->setGlobalOption('last_settings_update', time());
1211
- }
1212
-
1213
- /**
1214
- * Check & prepare URL
1215
- */
1216
- static function checkURL($strURL) {
1217
- if (empty($strURL)) return '';
1218
- if (substr($strURL, -1, 1) != '/' && substr($strURL, -10, 10) != '/index.php')
1219
- $strURL .= '/';
1220
- return $strURL;
1221
  }
1222
 
1223
- /**
1224
- * Show settings page
1225
- */
1226
- function showSettings() {
1227
- // Define globals and get request vars
1228
- global $pagenow;
1229
- $strTab = (isset($_GET['tab'])?$_GET['tab']:'homepage');
1230
- // Show update message if stats saved
1231
- if (isset($_POST['wp-piwik_settings_submit']) && $_POST['wp-piwik_settings_submit'] == 'Y')
1232
- echo '<div id="message" class="updated fade"><p>'.__('Changes saved','wp-piwik').'</p></div>';
1233
- // Show settings page title
1234
- echo '<div class="wrap"><h2>'.self::$settings->getGlobalOption('plugin_display_name').' '.__('Settings', 'wp-piwik').'</h2>';
1235
- // Show tabs
1236
- $strTab = $this->showSettingsTabs(self::isConfigured(), $strTab);
1237
- if ($strTab != 'sitebrowser') {
1238
- /***************************************************************************/ ?>
1239
- <div class="wp-piwik-donate">
1240
- <p><strong><?php _e('Donate','wp-piwik'); ?></strong></p>
1241
- <p><?php _e('If you like WP-Piwik, you can support its development by a donation:', 'wp-piwik'); ?></p>
1242
- <div>
1243
- <script type="text/javascript">
1244
- var flattr_url = 'http://www.braekling.de/wp-piwik-wpmu-piwik-wordpress';
1245
- </script>
1246
- <script src="http<?php echo (self::isSSL()?'s':''); ?>://api.flattr.com/button/load.js" type="text/javascript"></script>
1247
- </div>
1248
- <div>Paypal
1249
- <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
1250
- <input type="hidden" name="cmd" value="_s-xclick" />
1251
- <input type="hidden" name="hosted_button_id" value="6046779" />
1252
- <input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donateCC_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." />
1253
- <img alt="" border="0" src="https://www.paypal.com/de_DE/i/scr/pixel.gif" width="1" height="1" />
1254
- </form>
1255
- </div>
1256
- <div>
1257
- <a href="http://www.amazon.de/gp/registry/wishlist/111VUJT4HP1RA?reveal=unpurchased&amp;filter=all&amp;sort=priority&amp;layout=standard&amp;x=12&amp;y=14"><?php _e('My Amazon.de wishlist', 'wp-piwik'); ?></a>
1258
- </div>
1259
- <div>
1260
- <?php _e('Please don\'t forget to vote the compatibility at the','wp-piwik'); ?> <a href="http://wordpress.org/extend/plugins/wp-piwik/">WordPress.org Plugin Directory</a>.
1261
- </div>
1262
- </div>
1263
- <?php /***************************************************************************/
1264
- }
1265
- echo '<form class="'.($strTab != 'sitebrowser'?'wp-piwik-settings':'').'" method="post" action="'.admin_url(($pagenow == 'settings.php'?'network/':'').$pagenow.'?page=wp-piwik/classes/WP_Piwik.php&tab='.$strTab).'">';
1266
- echo '<input type="hidden" name="action" value="save_wp-piwik_settings" />';
1267
- wp_nonce_field('wp-piwik_settings');
1268
- // Show settings
1269
- if (($pagenow == 'options-general.php' || $pagenow == 'settings.php') && $_GET['page'] == 'wp-piwik/classes/WP_Piwik.php') {
1270
- echo '<table class="wp-piwik-form-table form-table">';
1271
- // Get tab contents
1272
- $this->includeFile('settings/'.$strTab);
1273
- // Show submit button
1274
- if (!in_array($strTab, array('homepage','credits','support','sitebrowser')))
1275
- echo '<tr><td><p class="submit" style="clear: both;padding:0;margin:0"><input type="submit" name="Submit" class="button-primary" value="'.__('Save settings', 'wp-piwik').'" /><input type="hidden" name="wp-piwik_settings_submit" value="Y" /></p></td></tr>';
1276
- echo '</table>';
1277
- }
1278
- // Close form
1279
- echo '</form></div>';
1280
- }
1281
-
1282
- /**
1283
- * Check if SSL is used
1284
- */
1285
- private static function isSSL() {
1286
- return (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off');
1287
- }
1288
-
1289
- /**
1290
- * Show an error message extended by a support site link
1291
- */
1292
- private static function showErrorMessage($strMessage) {
1293
- echo '<strong class="wp-piwik-error">'.__('An error occured', 'wp-piwik').':</strong> '.$strMessage.' [<a href="'.(self::$settings->checkNetworkActivation()?'network/settings':'options-general').'.php?page=wp-piwik/classes/WP_Piwik.php&tab=support">'.__('Support','wp-piwik').'</a>]';
1294
- }
1295
-
1296
- /**
1297
- * Read a RSS feed
1298
- */
1299
- private static function readRSSFeed($strFeedURL, $intCount = 5) {
1300
- $aryResult = array();
1301
- if (function_exists('simplexml_load_file') && !empty($strFeedURL)) {
1302
- $objXML = @simplexml_load_file($strFeedURL);
1303
- if (empty($strFeedURL) || !$objXML || !isset($objXML->channel[0]->item))
1304
- return array(array('title' => 'Can\'t read RSS feed.','url' => $strFeedURL));
1305
- foreach($objXML->channel[0]->item as $objItem) {
1306
- if( $intCount-- == 0 ) break;
1307
- $aryResult[] = array('title' => $objItem->title[0], 'url' => $objItem->link[0]);
1308
- }
1309
- }
1310
- return $aryResult;
1311
- }
1312
-
1313
- /**
1314
- * Execute test script
1315
- */
1316
- private static function loadTestscript() {
1317
- require_once('../debug/testscript.php');
1318
- }
1319
-
1320
- /**
1321
- * Get a blog's piwik ID
1322
- */
1323
- public static function getSiteID($intBlogID = null) {
1324
- $intResult = self::$settings->getOption('site_id');
1325
- if (self::$settings->checkNetworkActivation() && !empty($intBlogID)) {
1326
- $aryResult = get_blog_option($intBlogID, 'wp-piwik_settings');
1327
- $intResult = $aryResult['site_id'];
1328
- }
1329
- return (is_int($intResult)?$intResult:'n/a');
1330
- }
1331
-
1332
  public static function isConfigured() {
1333
  return (
1334
- self::$settings->getGlobalOption('piwik_token')
 
1335
  && (
1336
  (
1337
  (self::$settings->getGlobalOption('piwik_mode') == 'http') && (self::$settings->getGlobalOption('piwik_url'))
1338
  ) || (
1339
  (self::$settings->getGlobalOption('piwik_mode') == 'php') && (self::$settings->getGlobalOption('piwik_path'))
 
 
1340
  )
1341
  )
1342
  );
@@ -1346,15 +311,19 @@ class wp_piwik {
1346
  return self::$settings->getGlobalOption('revision') && self::$settings->getGlobalOption('revision') < self::$intRevisionId;
1347
  }
1348
 
 
 
 
 
1349
  private function isConfigSubmitted() {
1350
  return isset($_POST['action']) && $_POST['action'] == 'save_wp-piwik_settings';
1351
  }
1352
 
1353
- private function isPHPMode() {
1354
  return self::$settings->getGlobalOption('piwik_mode') && self::$settings->getGlobalOption('piwik_mode') == 'php';
1355
  }
1356
 
1357
- private function isNetworkMode() {
1358
  return self::$settings->checkNetworkActivation();
1359
  }
1360
 
@@ -1367,11 +336,11 @@ class wp_piwik {
1367
  }
1368
 
1369
  private function isTrackingActive() {
1370
- return self::$settings->getGlobalOption('add_tracking_code');
1371
  }
1372
 
1373
  private function isAdminTrackingActive() {
1374
- return self::$settings->getGlobalOption('track_admin');
1375
  }
1376
 
1377
  private function isAddNoScriptCode() {
@@ -1390,47 +359,46 @@ class wp_piwik {
1390
  return self::$settings->getGlobalOption('shortcodes');
1391
  }
1392
 
1393
- private static function definePiwikConstants() {
1394
- define('PIWIK_INCLUDE_PATH', self::$settings->getGlobalOption('piwik_path'));
1395
- define('PIWIK_USER_PATH', self::$settings->getGlobalOption('piwik_path'));
1396
- define('PIWIK_ENABLE_DISPATCH', false);
1397
- define('PIWIK_ENABLE_ERROR_HANDLER', false);
1398
- define('PIWIK_ENABLE_SESSION_START', false);
 
 
 
1399
  }
1400
 
1401
  private function openLogger() {
1402
  switch (WP_PIWIK_ACTIVATE_LOGGER) {
 
 
 
1403
  case 2:
1404
- require_once('WP_Piwik_Logger_File.php');
1405
- self::$logger = new WP_Piwik_Logger_File(__CLASS__);
1406
  break;
1407
  default:
1408
- require_once('WP_Piwik_Logger_Dummy.php');
1409
- self::$logger = new WP_Piwik_Logger_Dummy(__CLASS__);
1410
  }
1411
  }
 
 
 
 
1412
 
1413
  private function closeLogger() {
1414
  self::$logger = null;
1415
  }
1416
 
1417
  private function openSettings() {
1418
- $this->includeFile('classes/WP_Piwik_Settings');
1419
- self::$settings = new WP_Piwik_Settings(self::$logger);
1420
- }
1421
-
1422
- private function subClassConfig() {
1423
- return array(
1424
- 'wp_piwik' => $this,
1425
- 'logger' => self::$logger,
1426
- 'settings' => self::$settings
1427
- );
1428
  }
1429
 
1430
  private function includeFile($strFile) {
1431
  self::$logger->log('Include '.$strFile.'.php');
1432
- if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.$strFile.'.php'))
1433
- include(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.$strFile.'.php');
1434
  }
1435
 
1436
  private function isHiddenUser() {
@@ -1440,24 +408,224 @@ class wp_piwik {
1440
  return current_user_can('wp-piwik_stealth');
1441
  }
1442
 
1443
- private function isCurrentTrackingCode() {
1444
- return (self::$settings->getOption('last_tracking_code_update') < self::$settings->getGlobalOption('last_settings_update'));
1445
  }
1446
 
1447
- function site_header() {
1448
  self::$logger->log('Using deprecated function site_header');
1449
  $this->addJavascriptCode();
1450
  }
1451
 
1452
- function site_footer() {
1453
  self::$logger->log('Using deprecated function site_footer');
1454
  $this->addNoscriptCode();
1455
  }
1456
 
1457
- private function onPostStatusTransition($newStatus, $oldStatus = 'false', $post = null) {
1458
  if ($newStatus == 'publish' && $oldStatus != 'publish' ) {
1459
  add_action('publish_post', array($this, 'addPiwikAnnotation'));
1460
  }
1461
  }
1462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1463
  }
1
  <?php
2
 
3
+ class WP_Piwik {
4
 
5
  private static
6
+ $intRevisionId = 99914,
7
+ $strVersion = '0.10.0.0',
8
  $blog_id,
9
  $intDashboardID = 30,
10
  $strPluginBasename = NULL,
11
  $bolJustActivated = false,
12
  $logger,
13
+ $settings,
14
+ $request;
15
 
 
 
 
 
 
 
16
  public function __construct() {
17
  global $blog_id;
18
  self::$blog_id = (isset($blog_id)?$blog_id:'n/a');
22
  $this->addFilters();
23
  $this->addActions();
24
  $this->addShortcodes();
25
+ if (isset($_POST) && isset($_POST['wp-piwik'])) {
26
+ if (!$this->isPHPMode() && isset($_POST['wp-piwik']['piwik_mode']) && $_POST['wp-piwik']['piwik_mode'] == 'php')
27
+ self::definePiwikConstants();
28
+ self::$settings->applyChanges($_POST['wp-piwik']);
29
+ }
30
  self::$settings->save();
31
  }
32
 
36
 
37
  private function setup() {
38
  self::$strPluginBasename = plugin_basename(__FILE__);
39
+ if (!$this->isInstalled())
40
+ $this->installPlugin();
41
+ elseif ($this->isUpdated())
42
+ $this->updatePlugin();
43
  if ($this->isConfigSubmitted())
44
  $this->applySettings();
45
  if ($this->isPHPMode())
46
  self::definePiwikConstants();
 
47
  }
48
 
49
  private function addActions() {
50
+ add_action('admin_notices', array($this, 'showNotices'));
51
+ add_action('admin_init', array('WP_Piwik\Settings', 'registerSettings'));
52
  add_action('admin_menu', array($this, 'buildAdminMenu'));
53
+ add_action('admin_post_save_wp-piwik_stats', array($this, 'onStatsPageSaveChanges'));
54
+ add_action('load-post.php', array($this, 'addPostMetaboxes'));
55
+ add_action('load-post-new.php', array($this, 'addPostMetaboxes'));
56
+ if ($this->isNetworkMode()) {
57
  add_action('network_admin_menu', array($this, 'buildNetworkAdminMenu'));
58
+ add_action('update_site_option_blogname', array($this, 'onBlogNameChange'));
59
+ add_action('update_site_option_siteurl', array($this, 'onSiteUrlChange'));
60
+ } else {
61
+ add_action('update_option_blogname', array($this, 'onBlogNameChange'));
62
+ add_action('update_option_siteurl', array($this, 'onSiteUrlChange'));
63
+ }
64
  if ($this->isDashboardActive())
65
  add_action('wp_dashboard_setup', array($this, 'extendWordPressDashboard'));
66
  if ($this->isToolbarActive()) {
67
  add_action(is_admin()?'admin_head':'wp_head', array($this, 'loadToolbarRequirements'));
68
+ add_action('admin_bar_menu', array($this, 'extendWordPressToolbar'), 1000);
69
  }
70
  if ($this->isTrackingActive()) {
71
  add_action(self::$settings->getGlobalOption('track_codeposition') == 'footer'?'wp_footer':'wp_head', array($this, 'addJavascriptCode'));
72
  if ($this->isAddNoScriptCode())
73
  add_action('wp_footer', array($this, 'addNoscriptCode'));
74
  if ($this->isAdminTrackingActive())
75
+ add_action(self::$settings->getGlobalOption('track_codeposition') == 'footer'?'admin_footer':'admin_head', array($this, 'addJavascriptCode'));
76
  }
77
  if (self::$settings->getGlobalOption('add_post_annotations'))
78
+ add_action('transition_post_status', array($this, 'onPostStatusTransition'),10, 3);
79
  }
80
 
81
  private function addFilters() {
82
  add_filter('plugin_row_meta', array($this, 'setPluginMeta'), 10, 2);
83
+ add_filter('screen_layout_columns', array($this, 'onScreenLayoutColumns'), 10, 2);
84
  if ($this->isTrackingActive()) {
85
  if ($this->isTrackFeed()) {
86
+ add_filter('the_excerpt_rss', array($this, 'addFeedTracking'));
87
+ add_filter('the_content', array($this, 'addFeedTracking'));
88
  }
89
  if ($this->isAddFeedCampaign())
90
+ add_filter('post_link', array($this, 'addFeedCampaign'));
91
  }
92
  }
93
 
94
  private function addShortcodes() {
95
  if ($this->isAddShortcode())
96
+ add_shortcode('wp-piwik', array($this, 'shortcode'));
97
  }
98
 
99
+ private function installPlugin($isUpdate = false) {
 
 
 
 
100
  self::$logger->log('Running WP-Piwik installation');
101
+ if (!$isUpdate)
102
+ $this->addNotice('install', sprintf(__('%s %s installed.', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), self::$strVersion), __('Next you should connect to Piwik','wp-piwik'));
103
  self::$settings->setGlobalOption('revision', self::$intRevisionId);
104
  self::$settings->setGlobalOption('last_settings_update', time());
105
  }
106
 
107
+ public static function uninstallPlugin() {
108
  self::$logger->log('Running WP-Piwik uninstallation');
109
  if (!defined('WP_UNINSTALL_PLUGIN'))
110
  exit();
111
+ delete_option('wp-piwik_notices');
112
  self::$settings->resetSettings(true);
113
  }
114
 
115
+ private function updatePlugin() {
116
  self::$logger->log('Upgrade WP-Piwik to '.self::$strVersion);
 
117
  $patches = glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'update'.DIRECTORY_SEPARATOR.'*.php');
118
  if (is_array($patches)) {
119
  sort($patches);
123
  self::includeFile('update'.DIRECTORY_SEPARATOR.$patchVersion);
124
  }
125
  }
126
+ $this->addNotice('update', sprintf(__('%s updated to %s.', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), self::$strVersion), __('Please validate your configuration','wp-piwik'));
127
+ $this->installPlugin(true);
 
 
 
 
 
 
 
 
 
128
  }
129
 
130
+ private function addNotice($type, $subject, $text, $stay = false) {
131
+ $notices = get_option('wp-piwik_notices', array());
132
+ $notices[$type] = array('subject' => $subject, 'text' => $text, 'stay' => $stay);
133
+ update_option('wp-piwik_notices', $notices);
134
  }
135
 
136
+ public function showNotices() {
137
+ $link = sprintf('<a href="'.$this->getSettingsURL().'">%s</a>', __('Settings', 'wp-piwik'));
138
+ if ($notices = get_option('wp-piwik_notices')) {
139
+ foreach ($notices as $type => $notice) {
140
+ printf('<div class="updated fade"><p>%s <strong>%s:</strong> %s: %s</p></div>', $notice['subject'], __('Important', 'wp-piwik'), $notice['text'], $link);
141
+ if (!$notice['stay']) unset($notices[$type]);
142
+ }
143
+ }
144
+ update_option('wp-piwik_notices', $notices);
145
+ }
146
+
147
+ private function getSettingsURL() {
148
+ return (self::$settings->checkNetworkActivation()?'settings':'options-general').'.php?page='.self::$strPluginBasename;
149
  }
150
 
151
+ public function addJavascriptCode() {
 
 
152
  if ($this->isHiddenUser()) {
153
+ self::$logger->log('Do not add tracking code to site (user should not be tracked) Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
154
  return;
155
  }
156
+ $trackingCode = new WP_Piwik\TrackingCode($this);
157
+ $trackingCode->is404 = (is_404() && self::$settings->getGlobalOption('track_404'));
158
+ $trackingCode->isSearch = (is_search() && self::$settings->getGlobalOption('track_search'));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  self::$logger->log('Add tracking code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
160
+ echo $trackingCode->getTrackingCode();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  }
162
+
163
+ public function addNoscriptCode() {
164
+ if (self::$settings->getGlobalOption('track_mode') == 'proxy')
165
+ return;
166
+ if ($this->isHiddenUser()) {
167
+ self::$logger->log('Do not add noscript code to site (user should not be tracked) Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
168
+ return;
169
+ }
 
 
170
  self::$logger->log('Add noscript code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
171
  echo self::$settings->getOption('noscript_code')."\n";
172
  }
173
 
174
+ public function addPostMetaboxes() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  if (self::$settings->getGlobalOption('add_customvars_box')) {
176
+ add_action('add_meta_boxes', array(new WP_Piwik\Template\MetaBoxCustomVars($this, self::$settings), 'addMetabox'));
177
+ add_action('save_post', array(new WP_Piwik\Template\MetaBoxCustomVars($this, self::$settings), 'saveCustomVars'), 10, 2);
178
  }
 
179
  if (self::$settings->getGlobalOption('perpost_stats')) {
180
+ add_action('add_meta_boxes', array($this, 'onloadPostPage'));
 
181
  }
182
  }
183
 
184
+ public function buildAdminMenu() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  if (self::isConfigured()) {
186
+ $statsPage = new WP_Piwik\Admin\Statistics($this, self::$settings);
187
+ $this->statsPageId = add_dashboard_page(__('Piwik Statistics', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), 'wp-piwik_read_stats', 'wp-piwik_stats', array($statsPage, 'show'));
188
+
189
+ add_action('admin_print_scripts-'.$this->statsPageId, array($statsPage, 'printAdminScripts'));
190
+ add_action('admin_print_styles-'.$this->statsPageId, array($statsPage, 'printAdminStyles'));
191
+ add_action('admin_head-'.$this->statsPageId, array($statsPage, 'extendAdminHeader'));
192
+ add_action('load-'.$this->statsPageId, array($this, 'onloadStatsPage'));
 
 
 
 
 
 
 
 
 
193
  }
194
  if (!self::$settings->checkNetworkActivation()) {
195
+ $optionsPage = new WP_Piwik\Admin\Settings($this, self::$settings);
196
+ $optionsPageID = add_options_page(self::$settings->getGlobalOption('plugin_display_name'), self::$settings->getGlobalOption('plugin_display_name'), 'activate_plugins', __FILE__, array($optionsPage, 'show'));
197
+ add_action('admin_head-'.$optionsPageID, array($optionsPage, 'extendAdminHeader'));
 
 
 
 
 
 
 
 
 
 
 
198
  }
199
  }
200
 
201
+ public function buildNetworkAdminMenu() {
 
 
 
 
202
  if (self::isConfigured()) {
203
+ $statsPage = new WP_Piwik\Admin\Network($this);
204
+ $pageID = add_dashboard_page(__('Piwik Statistics', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), 'manage_sites', 'wp-piwik_stats', array($statsPage, 'show'));
205
+ $statsPage->add($pageID);
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  }
207
+ $optionsPage = new WP_Piwik\Admin\Settings($this);
208
+ $optionsPageID = add_submenu_page('settings.php', self::$settings->getGlobalOption('plugin_display_name'), self::$settings->getGlobalOption('plugin_display_name'), 'manage_sites', __FILE__, array($optionsPage, 'show'));
209
+ $optionsPage->add($optionsPageID);
 
 
 
 
 
 
 
 
 
210
  }
211
 
212
+ public function extendWordPressDashboard() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  if (current_user_can('wp-piwik_read_stats')) {
214
+ if (self::$settings->getGlobalOption('dashboard_widget') != 'disabled')
215
+ new WP_Piwik\Widget\Overview($this, self::$settings);
216
+ if (self::$settings->getGlobalOption('dashboard_chart'))
217
+ new WP_Piwik\Widget\Chart($this, self::$settings);
 
 
 
 
 
 
 
 
 
 
 
218
  if (self::$settings->getGlobalOption('dashboard_seo'))
219
+ new WP_Piwik\Widget\Seo($this, self::$settings);
220
  }
221
  }
222
 
223
+ public function extendWordPressToolbar($toolbar) {
 
 
 
 
224
  if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
225
+ $id = WP_Piwik\Request::register('VisitsSummary.getUniqueVisitors', array('period' => 'day', 'date' => 'last30'));
226
+ $unique = $this->request($id);
227
+ $graph = "<script type='text/javascript'>var \$jSpark = jQuery.noConflict();\$jSpark(function() {var piwikSparkVals=[".implode(',',$unique)."];\$jSpark('.wp-piwik_dynbar').sparkline(piwikSparkVals, {type: 'bar', barColor: '#ccc', barWidth:2});});</script><span class='wp-piwik_dynbar'>Loading...</span>";
228
+ $toolbar->add_menu(array('id' => 'wp-piwik_stats', 'title' => $graph, 'href' => $this->getStatsURL()));
229
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  }
231
 
232
+ public function setPluginMeta($links, $file) {
233
+ if ($file == 'wp-piwik/wp-piwik.php')
234
+ return array_merge($links,array(sprintf('<a href="%s">%s</a>', self::getSettingsURL(), __('Settings', 'wp-piwik'))));
235
+ return $links;
 
 
 
 
236
  }
237
 
238
+ public function loadToolbarRequirements() {
 
 
 
 
239
  if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
240
+ wp_enqueue_script('wp-piwik-sparkline', $this->getPluginURL().'js/sparkline/jquery.sparkline.min.js', array('jquery'), self::$strVersion);
241
+ wp_enqueue_style('wp-piwik', $this->getPluginURL().'css/wp-piwik-spark.css', array(), self::$strVersion);
 
 
242
  }
243
  }
244
 
245
+ public function addFeedTracking($content) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  global $post;
247
  if(is_feed()) {
248
  self::$logger->log('Add tracking image to feed entry.');
249
+ if (!self::$settings->getOption('site_id')) self::addPiwikSite();
 
250
  $title = the_title(null,null,false);
251
  $posturl = get_permalink($post->ID);
252
  $urlref = get_bloginfo('rss2_url');
253
  $url = self::$settings->getGlobalOption('piwik_url');
254
+ if (substr($url, -10, 10) == '/index.php') $url = str_replace('/index.php', '/piwik.php', $url);
 
255
  else $url .= 'piwik.php';
256
+ $trackingImage = $url.'?idsite='.self::$settings->getOption('site_id').'&amp;rec=1&amp;url='.urlencode($posturl).'&amp;action_name='.urlencode($title).'&amp;urlref='.urlencode($urlref);
 
 
 
257
  $content .= '<img src="'.$trackingImage.'" style="border:0;width:0;height:0" width="0" height="0" alt="" />';
258
  }
259
  return $content;
260
  }
261
 
262
+ public function addFeedCampaign($permalink) {
 
 
 
263
  global $post;
264
  if(is_feed()) {
265
  self::$logger->log('Add campaign to feed permalink.');
269
  return $permalink;
270
  }
271
 
272
+ public function addPiwikAnnotation($postID) {
273
+ $note = 'Published: '.get_post($postID)->post_title.' - URL: '.get_permalink($postID);
274
+ $id = WP_Piwik\Request::register('Annotations.add', array(
275
+ 'idSite' => $this->getPiwikSiteId(),
276
+ 'date' => date('Y-m-d'),
277
+ 'note' => $note
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  ));
279
+ $result = $this->request($id);
280
+ self::$logger->log('Add post annotation. '.$note.' - '.serialize($result));
 
 
 
 
 
 
 
 
281
  }
282
+
283
+ private function applySettings() {
284
+ self::$settings->applyChanges();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  if (self::$settings->getGlobalOption('auto_site_config') && self::isConfigured()) {
286
  if (self::$settings->getGlobalOption('piwik_mode') == 'php' && !defined('PIWIK_INCLUDE_PATH'))
287
  self::definePiwikConstants();
289
  self::$settings->getOption('tracking_code', $aryReturn['js']);
290
  self::$settings->getOption('site_id', $aryReturn['id']);
291
  }
 
 
 
 
 
 
 
 
 
 
 
292
  }
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  public static function isConfigured() {
295
  return (
296
+ self::$settings->getGlobalOption('piwik_token')
297
+ && (self::$settings->getGlobalOption('piwik_mode') != 'disabled')
298
  && (
299
  (
300
  (self::$settings->getGlobalOption('piwik_mode') == 'http') && (self::$settings->getGlobalOption('piwik_url'))
301
  ) || (
302
  (self::$settings->getGlobalOption('piwik_mode') == 'php') && (self::$settings->getGlobalOption('piwik_path'))
303
+ )|| (
304
+ (self::$settings->getGlobalOption('piwik_mode') == 'pro') && (self::$settings->getGlobalOption('piwik_user'))
305
  )
306
  )
307
  );
311
  return self::$settings->getGlobalOption('revision') && self::$settings->getGlobalOption('revision') < self::$intRevisionId;
312
  }
313
 
314
+ private function isInstalled() {
315
+ return self::$settings->getGlobalOption('revision');
316
+ }
317
+
318
  private function isConfigSubmitted() {
319
  return isset($_POST['action']) && $_POST['action'] == 'save_wp-piwik_settings';
320
  }
321
 
322
+ public function isPHPMode() {
323
  return self::$settings->getGlobalOption('piwik_mode') && self::$settings->getGlobalOption('piwik_mode') == 'php';
324
  }
325
 
326
+ public function isNetworkMode() {
327
  return self::$settings->checkNetworkActivation();
328
  }
329
 
336
  }
337
 
338
  private function isTrackingActive() {
339
+ return self::$settings->getGlobalOption('track_mode') != 'disabled';
340
  }
341
 
342
  private function isAdminTrackingActive() {
343
+ return self::$settings->getGlobalOption('track_admin') && is_admin();
344
  }
345
 
346
  private function isAddNoScriptCode() {
359
  return self::$settings->getGlobalOption('shortcodes');
360
  }
361
 
362
+ public static function definePiwikConstants() {
363
+ if (!defined('PIWIK_INCLUDE_PATH')) {
364
+ @header('Content-type: text/xml');
365
+ define('PIWIK_INCLUDE_PATH', self::$settings->getGlobalOption('piwik_path'));
366
+ define('PIWIK_USER_PATH', self::$settings->getGlobalOption('piwik_path'));
367
+ define('PIWIK_ENABLE_DISPATCH', false);
368
+ define('PIWIK_ENABLE_ERROR_HANDLER', false);
369
+ define('PIWIK_ENABLE_SESSION_START', false);
370
+ }
371
  }
372
 
373
  private function openLogger() {
374
  switch (WP_PIWIK_ACTIVATE_LOGGER) {
375
+ case 1:
376
+ self::$logger = new WP_Piwik\Logger\Screen(__CLASS__);
377
+ break;
378
  case 2:
379
+ self::$logger = new WP_Piwik\Logger\File(__CLASS__);
 
380
  break;
381
  default:
382
+ self::$logger = new WP_Piwik\Logger\Dummy(__CLASS__);
 
383
  }
384
  }
385
+
386
+ public static function log($message) {
387
+ self::$logger->log($message);
388
+ }
389
 
390
  private function closeLogger() {
391
  self::$logger = null;
392
  }
393
 
394
  private function openSettings() {
395
+ self::$settings = new WP_Piwik\Settings($this, self::$logger);
 
 
 
 
 
 
 
 
 
396
  }
397
 
398
  private function includeFile($strFile) {
399
  self::$logger->log('Include '.$strFile.'.php');
400
+ if (WP_PIWIK_PATH.$strFile.'.php')
401
+ include(WP_PIWIK_PATH.$strFile.'.php');
402
  }
403
 
404
  private function isHiddenUser() {
408
  return current_user_can('wp-piwik_stealth');
409
  }
410
 
411
+ public function isCurrentTrackingCode() {
412
+ return (self::$settings->getOption('last_tracking_code_update') > self::$settings->getGlobalOption('last_settings_update'));
413
  }
414
 
415
+ public function site_header() {
416
  self::$logger->log('Using deprecated function site_header');
417
  $this->addJavascriptCode();
418
  }
419
 
420
+ public function site_footer() {
421
  self::$logger->log('Using deprecated function site_footer');
422
  $this->addNoscriptCode();
423
  }
424
 
425
+ public function onPostStatusTransition($newStatus, $oldStatus, $post) {
426
  if ($newStatus == 'publish' && $oldStatus != 'publish' ) {
427
  add_action('publish_post', array($this, 'addPiwikAnnotation'));
428
  }
429
  }
430
 
431
+ public function getPluginURL() {
432
+ return trailingslashit(plugins_url().'/wp-piwik/');
433
+ }
434
+
435
+ public function getPluginVersion() {
436
+ return self::$strVersion;
437
+ }
438
+
439
+ public function onScreenLayoutColumns($aryColumns, $strScreen) {
440
+ if ($strScreen == $this->statsPageId)
441
+ $aryColumns[$this->statsPageId] = 3;
442
+ return $aryColumns;
443
+ }
444
+
445
+ function addAdminHeaderTracking() {
446
+ $this->site_header();
447
+ }
448
+
449
+ public function getOption($key) {
450
+ return self::$settings->getOption($key);
451
+ }
452
+
453
+ public function getStatsURL() {
454
+ return admin_url().'?page=wp-piwik_stats';
455
+ }
456
+
457
+ private function loadTestscript() {
458
+ $this->includeFile('debug'.DIRECTORY_SEPARATOR.'testscript');
459
+ }
460
+
461
+ private static function showErrorMessage($message) {
462
+ echo '<strong class="wp-piwik-error">'.__('An error occured', 'wp-piwik').':</strong> '.$message.' [<a href="'.(self::$settings->checkNetworkActivation()?'network/settings':'options-general').'.php?page=wp-piwik/classes/WP_Piwik.php&tab=support">'.__('Support','wp-piwik').'</a>]';
463
+ }
464
+
465
+ public function request($id) {
466
+ if (!isset(self::$request))
467
+ self::$request = (
468
+ self::$settings->getGlobalOption('piwik_mode') == 'http' || self::$settings->getGlobalOption('piwik_mode') == 'pro'?
469
+ new WP_Piwik\Request\Rest($this, self::$settings):
470
+ new WP_Piwik\Request\Php($this, self::$settings)
471
+ );
472
+ return self::$request->perform($id);
473
+ }
474
+
475
+ private static function readRSSFeed($feed, $cnt = 5) {
476
+ $result = array();
477
+ if (function_exists('simplexml_load_file') && !empty($feed)) {
478
+ $xml = @simplexml_load_file($feed);
479
+ if (!xml || !isset($xml->channel[0]->item))
480
+ return array(array('title' => 'Can\'t read RSS feed.','url' => $xml));
481
+ foreach($xml->channel[0]->item as $item) {
482
+ if ($cnt-- == 0) break;
483
+ $result[] = array('title' => $item->title[0], 'url' => $item->link[0]);
484
+ }
485
+ }
486
+ return $result;
487
+ }
488
+
489
+ public function shortcode($attributes) {
490
+ shortcode_atts(array(
491
+ 'title' => '',
492
+ 'module' => 'overview',
493
+ 'period' => 'day',
494
+ 'date' => 'yesterday',
495
+ 'limit' => 10,
496
+ 'width' => '100%',
497
+ 'height' => '200px',
498
+ 'language' => 'en',
499
+ 'range' => false,
500
+ 'key' => 'sum_daily_nb_uniq_visitors'
501
+ ), $attributes);
502
+ new \WP_Piwik\Shortcode($attributes, $this, self::$settings);
503
+ }
504
+
505
+ public function getPiwikSiteId($blogId = null) {
506
+ $result = self::$settings->getOption('site_id', $blogId);
507
+ return (!empty($result) && !self::$settings->getGlobalOption('auto_site_config')?$result:$this->requestPiwikSiteId($blogId));
508
+ }
509
+
510
+ public function getPiwikSiteDetails() {
511
+ $id = WP_Piwik\Request::register('SitesManager.getAllSites', array());
512
+ $piwikSiteDetails = $this->request($id);
513
+ return $piwikSiteDetails;
514
+ }
515
+
516
+ private function requestPiwikSiteId($blogId = null) {
517
+ $isCurrent = !self::$settings->checkNetworkActivation() || empty($blogId);
518
+ if (self::$settings->getGlobalOption('auto_site_config')) {
519
+ $id = WP_Piwik\Request::register('SitesManager.getSitesIdFromSiteUrl', array(
520
+ 'url' => $isCurrent?get_bloginfo('url'):get_blog_details($blogId)->siteurl
521
+ ));
522
+ $result = $this->request($id);
523
+ if (empty($result) || !isset($result[0]))
524
+ $result = null; //$this->addPiwikSite($blogId);
525
+ else
526
+ $result = $result[0]['idsite'];
527
+ } else $result = null;
528
+ self::$logger->log('Get Piwik ID: WordPress site '.($isCurrent?get_bloginfo('url'):get_blog_details($blogId)->$siteurl).' = Piwik ID '.$result);
529
+ if ($result !== null) {
530
+ self::$settings->setOption('site_id', $result, $blogId);
531
+ if (self::$settings->getGlobalOption('track_mode') != 'disabled' && self::$settings->getGlobalOption('track_mode') != 'manually') {
532
+ $code = $this->updateTrackingCode($result, $blogId);
533
+ self::$settings->setOption('tracking_code', $code['script'], $blogId);
534
+ self::$settings->setOption('noscript_code', $code['noscript'], $blogId);
535
+ }
536
+ $this::$settings->save();
537
+ return $result;
538
+ } return 'n/a';
539
+ }
540
+
541
+ private function addPiwikSite($blogId = null) {
542
+ $isCurrent = !self::$settings->checkNetworkActivation() || empty($blogId);
543
+ $id = WP_Piwik\Request::register('SitesManager.addSite', array(
544
+ 'urls' => $isCurrent?get_bloginfo('url'):get_blog_details($blogId)->$siteurl,
545
+ 'siteName' => $isCurrent?get_bloginfo('name'):get_blog_details($blogId)->$blogname
546
+ ));
547
+ $result = $this->request($id);
548
+ self::$logger->log('Get Piwik ID: WordPress site '.($isCurrent?get_bloginfo('url'):get_blog_details($blogId)->$siteurl).' = Piwik ID '.$result);
549
+ if (empty($result) || !isset($result[0]))
550
+ return null;
551
+ else
552
+ return $result[0]['idsite'];
553
+ }
554
+
555
+ private function updatePiwikSite($siteId, $blogId = null) {
556
+ $isCurrent = !self::$settings->checkNetworkActivation() || empty($blogId);
557
+ $id = WP_Piwik\Request::register('SitesManager.updateSite', array(
558
+ 'idSite' => $siteId,
559
+ 'urls' => $isCurrent?get_bloginfo('url'):get_blog_details($blogId)->$siteurl,
560
+ 'siteName' => $isCurrent?get_bloginfo('name'):get_blog_details($blogId)->$blogname
561
+ ));
562
+ $result = $this->request($id);
563
+ self::$logger->log('Update Piwik site: WordPress site '.($isCurrent?get_bloginfo('url'):get_blog_details($blogId)->$siteurl));
564
+ }
565
+
566
+ public function updateTrackingCode($siteId = false, $blogId = null) {
567
+ if (!$siteId)
568
+ $siteId = $this->getPiwikSiteId();
569
+ $id = WP_Piwik\Request::register('SitesManager.getJavascriptTag', array(
570
+ 'idSite' => $siteId,
571
+ 'mergeSubdomains' => self::$settings->getGlobalOption('track_across')?1:0,
572
+ 'mergeAliasUrls' => self::$settings->getGlobalOption('track_across_alias')?1:0,
573
+ 'disableCookies' => self::$settings->getGlobalOption('disable_cookies')?1:0
574
+ ));
575
+ $result = html_entity_decode($this->request($id));
576
+ self::$logger->log('Delivered tracking code: '.$result);
577
+ $result = WP_Piwik\TrackingCode::prepareTrackingCode($result, self::$settings, self::$logger);
578
+ return $result;
579
+ }
580
+
581
+ public function onBlogNameChange($oldValue, $newValue) {
582
+ $this->updatePiwikSite(self::$settings->getOption('site_id'));
583
+ }
584
+
585
+ public function onSiteUrlChange($oldValue, $newValue) {
586
+ $this->updatePiwikSite(self::$settings->getOption('site_id'));
587
+ }
588
+
589
+ public function onloadStatsPage($statsPageId) {
590
+ if (self::$settings->getGlobalOption('disable_timelimit'))
591
+ set_time_limit(0);
592
+ wp_enqueue_script('common');
593
+ wp_enqueue_script('wp-lists');
594
+ wp_enqueue_script('postbox');
595
+ wp_enqueue_script('wp-piwik', $this->getPluginURL().'js/wp-piwik.js', array(), self::$strVersion, true);
596
+ wp_enqueue_script('wp-piwik-jqplot',$this->getPluginURL().'js/jqplot/wp-piwik.jqplot.js', array('jquery'), self::$strVersion);
597
+ new \WP_Piwik\Widget\Chart($this, self::$settings, $this->statsPageId);
598
+ new \WP_Piwik\Widget\Visitors($this, self::$settings, $this->statsPageId);
599
+ new \WP_Piwik\Widget\Overview($this, self::$settings, $this->statsPageId);
600
+ if (self::$settings->getGlobalOption('stats_seo'))
601
+ new \WP_Piwik\Widget\Seo($this, self::$settings, $this->statsPageId);
602
+ new \WP_Piwik\Widget\Pages($this, self::$settings, $this->statsPageId);
603
+ new \WP_Piwik\Widget\Keywords($this, self::$settings, $this->statsPageId);
604
+ new \WP_Piwik\Widget\Referrers($this, self::$settings, $this->statsPageId);
605
+ new \WP_Piwik\Widget\Plugins($this, self::$settings, $this->statsPageId);
606
+ new \WP_Piwik\Widget\Search($this, self::$settings, $this->statsPageId);
607
+ new \WP_Piwik\Widget\Noresult($this, self::$settings, $this->statsPageId);
608
+ new \WP_Piwik\Widget\Browsers($this, self::$settings, $this->statsPageId);
609
+ new \WP_Piwik\Widget\BrowserDetails($this, self::$settings, $this->statsPageId);
610
+ new \WP_Piwik\Widget\Screens($this, self::$settings, $this->statsPageId);
611
+ new \WP_Piwik\Widget\Systems($this, self::$settings, $this->statsPageId);
612
+ }
613
+
614
+ public function onloadPostPage($postPageId) {
615
+ global $post;
616
+ $postUrl = get_permalink($post->ID);
617
+ $this->log('Load per post statistics: '.$postUrl);
618
+ array(new \WP_Piwik\Widget\Post($this, self::$settings, 'post', 'side', 'default', array('url' => $postUrl)), 'show');
619
+ }
620
+
621
+ /* Stats page changes by POST submit
622
+ seen in Heiko Rabe's metabox demo plugin
623
+ http://tinyurl.com/5r5vnzs */
624
+ function onStatsPageSaveChanges() {
625
+ if ( !current_user_can('manage_options') )
626
+ wp_die( __('Cheatin&#8217; uh?') );
627
+ check_admin_referer('wp-piwik_stats');
628
+ wp_redirect($_POST['_wp_http_referer']);
629
+ }
630
+
631
  }
classes/WP_Piwik/Admin.php ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ abstract class Admin {
6
+
7
+ protected static $wpPiwik, $pageID, $settings;
8
+
9
+ public function __construct($wpPiwik, $settings) {
10
+ self::$wpPiwik = $wpPiwik;
11
+ self::$settings = $settings;
12
+ }
13
+
14
+ abstract public function show();
15
+
16
+ abstract public function printAdminScripts();
17
+
18
+ abstract public function extendAdminHeader();
19
+
20
+ public function printAdminStyles() {
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css', array(), self::$wpPiwik->getPluginVersion());
22
+ }
23
+
24
+ public function onLoad() {}
25
+
26
+ }
classes/WP_Piwik/Admin/Network.php ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Admin;
4
+
5
+ class Network extends \WP_Piwik\Admin\Statistics {
6
+
7
+ public function show() {
8
+ parent::show(true);
9
+ }
10
+
11
+ public function printAdminScripts() {
12
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
13
+ wp_enqueue_script('wp-piwik-jqplot', self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'), self::$wpPiwik->getPluginVersion());
14
+ }
15
+
16
+ public function extendAdminHeader() {
17
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.(parent::$wpPiwik->getPluginURL()).'js/jqplot/excanvas.min.js"></script><![endif]-->';
18
+ echo '<link rel="stylesheet" href="'.(parent::$wpPiwik->getPluginURL()).'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
19
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
20
+ }
21
+
22
+ public function onLoad() {
23
+ self::$wpPiwik->onloadStatsPage(self::$pageID);
24
+ }
25
+ }
classes/WP_Piwik/Admin/Settings.php ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Admin;
4
+
5
+ class Settings extends \WP_Piwik\Admin {
6
+
7
+ public function show() {
8
+ global $wp_roles;
9
+ if (isset($_POST) && isset($_POST['wp-piwik']))
10
+ $this->showBox('updated', 'yes', __('Changes saved.'));
11
+ ?>
12
+ <div id="plugin-options-wrap" class="widefat">
13
+ <form method="post">
14
+ <input type="hidden" name="wp-piwik[revision]" value="<?php echo self::$settings->getGlobalOption('revision'); ?>" />
15
+ <?php wp_nonce_field('wp-piwik_settings'); ?>
16
+ <table class="wp-piwik-form">
17
+ <tbody>
18
+ <tr><th width="150px"></th><td></td></tr>
19
+ <?php
20
+ $this->showHeadline(1, 'admin-generic', 'Settings', true);
21
+ $submitButton = '<tr><td colspan="2"><p class="submit"><input name="Submit" type="submit" class="button-primary" value="'.esc_attr__('Save Changes').'" /></p></td></tr>';
22
+
23
+ printf('<tr><td colspan="2">%s</td></tr>', __('Thanks for using WP-Piwik!', 'wp-piwik'));
24
+ //$this->showDonation();
25
+ if (self::$wpPiwik->isConfigured()) {
26
+ $piwikVersion = self::$wpPiwik->request('global.getPiwikVersion');
27
+ if (!empty($piwikVersion) && !is_array($piwikVersion))
28
+ $this->showText(
29
+ sprintf(__('WP-Piwik %s is successfully connected to Piwik %s.', 'wp-piwik'), self::$wpPiwik->getPluginVersion(), $piwikVersion).' '.
30
+ (!self::$wpPiwik->isNetworkMode()?
31
+ sprintf(__('You are running WordPress %s.', 'wp-piwik'), get_bloginfo('version')):
32
+ sprintf(__('You are running a WordPress %s blog network (WPMU). WP-Piwik will handle your sites as different websites.', 'wp-piwik'), get_bloginfo('version'))
33
+ )
34
+ );
35
+ else {
36
+ $this->showBox('error', 'no', sprintf(__('WP-Piwik %s was not able to connect to Piwik using your configuration. Check the &raquo;Connect to Piwik&laquo; section below.', 'wp-piwik'), self::$wpPiwik->getPluginVersion()));
37
+ }
38
+ } else $this->showBox('error', 'no', sprintf(__('WP-Piwik %s has to be connected to Piwik first. Check the &raquo;Connect to Piwik&laquo; section below.', 'wp-piwik'), self::$wpPiwik->getPluginVersion()));
39
+
40
+ $this->showHeadline(2, 'admin-plugins', 'Connect to Piwik');
41
+
42
+ if (!self::$wpPiwik->isConfigured())
43
+ $this->showBox('updated', 'info', sprintf('%s <a href="%s">%s</a> %s <a href="%s">%s</a>.', __('WP-Piwik is a WordPress plugin to show a selection of Piwik stats in your WordPress admin dashboard and to add and configure your Piwik tracking code. To use this you will need your own Piwik instance. If you do not already have a Piwik setup, you have two simple options: use either', 'wp-piwik'), 'http://piwik.org/', __('Self-hosted', 'wp-piwik'), __('or', 'wp-piwik'), 'http://piwik.org/hosting/', __('Cloud-hosted', 'wp-piwik')));
44
+
45
+ if (!function_exists('curl_init') && !ini_get('allow_url_fopen'))
46
+ $this->showBox('error', 'no', __('Neither cURL nor fopen are available. So WP-Piwik can not use the HTTP API and not connect to Piwik Pro.').' '.sprintf('<a href="%s">%s.</a>', 'https://wordpress.org/plugins/wp-piwik/faq/', __('More information', 'wp-piwik')));
47
+
48
+ $description = sprintf('%s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s',
49
+ __('You can choose between three connection methods:', 'wp-piwik'),
50
+ __('Self-hosted (HTTP API, default)', 'wp-piwik'),
51
+ __('This is the default option for a self-hosted Piwik and should work for most configurations. WP-Piwik will connect to Piwk using http(s).', 'wp-piwik'),
52
+ __('Self-hosted (PHP API)', 'wp-piwik'),
53
+ __('Choose this, if your self-hosted Piwik and WordPress are running on the same machine and you know the full server path to your Piwik instance.', 'wp-piwik'),
54
+ __('Cloud-hosted (Piwik Pro)', 'wp-piwik'),
55
+ __('If you are using a cloud-hosted Piwik by Piwik Pro, you can simply use this option.', 'wp-piwik')
56
+ );
57
+ $this->showSelect('piwik_mode', __('Piwik Mode', 'wp-piwik'),
58
+ array(
59
+ 'disabled' => __('Disabled (WP-Piwik will not connect to Piwik)', 'wp-piwik'),
60
+ 'http' => __('Self-hosted (HTTP API, default)', 'wp-piwik'),
61
+ 'php' => __('Self-hosted (PHP API)', 'wp-piwik'),
62
+ 'pro' => __('Cloud-hosted (Piwik Pro)', 'wp-piwik')
63
+ ), $description, '$j(\'tr.wp-piwik-mode-option\').addClass(\'hidden\'); $j(\'#wp-piwik-mode-option-\' + $j(\'#piwik_mode\').val()).removeClass(\'hidden\');', false, '', self::$wpPiwik->isConfigured());
64
+
65
+ $this->showInput('piwik_url', __('Piwik URL', 'wp-piwik'), 'TODO URL description', self::$settings->getGlobalOption('piwik_mode') != 'http', 'wp-piwik-mode-option', 'http', self::$wpPiwik->isConfigured());
66
+ $this->showInput('piwik_path', __('Piwik path', 'wp-piwik'), 'TODO Path description', self::$settings->getGlobalOption('piwik_mode') != 'php', 'wp-piwik-mode-option', 'php', self::$wpPiwik->isConfigured());
67
+ $this->showInput('piwik_user', __('Piwik user', 'wp-piwik'), 'TODO User description', self::$settings->getGlobalOption('piwik_mode') != 'pro', 'wp-piwik-mode-option', 'pro', self::$wpPiwik->isConfigured());
68
+ $this->showInput('piwik_token', __('Auth token', 'wp-piwik'), 'TODO Token description', false, '', '', self::$wpPiwik->isConfigured());
69
+
70
+ // Site configuration
71
+ $piwikSiteId = self::$wpPiwik->isConfigured()?self::$wpPiwik->getPiwikSiteId():false;
72
+ $this->showCheckbox('auto_site_config', __('Auto config', 'wp-piwik'), __('Check this to automatically choose your blog from your Piwik sites by URL. If your blog is not added to Piwik yet, WP-Piwik will add a new site.', 'wp-piwik'), self::$wpPiwik->isConfigured(), '$j(\'tr.wp-piwik-auto-option\').toggle(\'hidden\');'.($piwikSiteId?'$j(\'#site_id\').val('.$piwikSiteId.');':''));
73
+ if (self::$wpPiwik->isConfigured()) {
74
+ $piwikSiteDetails = self::$wpPiwik->getPiwikSiteDetails();
75
+ if (($piwikSiteId == 'n/a'))
76
+ $piwikSiteDescription = 'n/a';
77
+ elseif (!self::$settings->getGlobalOption('auto_site_config'))
78
+ $piwikSiteDescription = __('Save settings to start estimation.', 'wp-piwik');
79
+ else
80
+ $piwikSiteDescription = $piwikSiteDetails[$piwikSiteId]['name'].' ('.$piwikSiteDetails[$piwikSiteId]['main_url'].')';
81
+ echo '<tr class="wp-piwik-auto-option'.(!self::$settings->getGlobalOption('auto_site_config')?' hidden':'').'"><th scope="row">'.__('Determined site', 'wp-piwik').':</th><td>'.$piwikSiteDescription.'</td></tr>';
82
+ if (is_array($piwikSiteDetails))
83
+ foreach ($piwikSiteDetails as $key => $siteData)
84
+ $siteList[$key] = $siteData['name'].' ('.$siteData['main_url'].')';
85
+ $this->showSelect('site_id', __('Select site', 'wp-piwik'), $siteList, 'TODO Choose description', '', self::$settings->getGlobalOption('auto_site_config'), 'wp-piwik-auto-option', true, false);
86
+ }
87
+
88
+ echo $submitButton;
89
+
90
+ // Stats configuration
91
+ if (self::$wpPiwik->isConfigured()) {
92
+ $this->showHeadline(2, 'chart-pie', 'Show Statistics');
93
+
94
+ $this->showSelect('default_date', __('Piwik default date', 'wp-piwik'),
95
+ array(
96
+ 'today' => __('Today', 'wp-piwik'),
97
+ 'yesterday' => __('Yesterday', 'wp-piwik'),
98
+ 'current_month' => __('Current month', 'wp-piwik'),
99
+ 'last_month' => __('Last month', 'wp-piwik'),
100
+ 'current_week' => __('Current week', 'wp-piwik'),
101
+ 'last_week' => __('Last week', 'wp-piwik'),
102
+ ), __('Default date shown on statistics page.', 'wp-piwik')
103
+ );
104
+
105
+ $this->showCheckbox('stats_seo', __('Show SEO data', 'wp-piwik'), __('Display SEO ranking data on statistics page.', 'wp-piwik').' ('.__('Slow!', 'wp-piwik').')');
106
+
107
+ $this->showSelect('dashboard_widget', __('Dashboard overview', 'wp-piwik'),
108
+ array(
109
+ 'disabled' => __('Disabled', 'wp-piwik'),
110
+ 'yesterday' => __('Yesterday', 'wp-piwik'),
111
+ 'today' => __('Today', 'wp-piwik'),
112
+ 'last30' => __('Last 30 days', 'wp-piwik')
113
+ ), __('Enable WP-Piwik dashboard widget &quot;Overview&quot;.', 'wp-piwik')
114
+ );
115
+
116
+ $this->showCheckbox('dashboard_chart', __('Dashboard graph', 'wp-piwik'), __('Enable WP-Piwik dashboard widget &quot;Graph&quot;.', 'wp-piwik'));
117
+
118
+ $this->showCheckbox('dashboard_seo', __('Dashboard SEO', 'wp-piwik'), __('Enable WP-Piwik dashboard widget &quot;SEO&quot;.', 'wp-piwik').' ('.__('Slow!', 'wp-piwik').')');
119
+
120
+ $this->showCheckbox('toolbar', __('Show graph on WordPress Toolbar', 'wp-piwik'), __('Display a last 30 days visitor graph on WordPress\' toolbar.', 'wp-piwik'));
121
+
122
+ echo '<tr><th scope="row"><label for="capability_read_stats">'.__('Display stats to', 'wp-piwik').'</label>:</th><td>';
123
+ $filter = self::$settings->getGlobalOption('capability_read_stats');
124
+ foreach($wp_roles->role_names as $key => $name) {
125
+ echo '<input type="checkbox" '.(isset($filter[$key]) && $filter[$key]?'checked="checked" ':'').'value="1" onchange="$j(\'#capability_read_stats-'.$key.'-input\').val(this.checked?1:0);" />';
126
+ echo '<input id="capability_read_stats-'.$key.'-input" type="hidden" name="wp-piwik[capability_read_stats]['.$key.']" value="'.(int)(isset($filter[$key]) && $filter[$key]).'" />';
127
+ echo $name.' &nbsp; ';
128
+ }
129
+ echo '<span class="dashicons dashicons-editor-help" onclick="$j(\'#capability_read_stats-desc\').toggleClass(\'hidden\');"></span> <p class="description hidden" id="capability_read_stats-desc">'.__('Choose user roles allowed to see the statistics page.', 'wp-piwik').'</p></td></tr>';
130
+
131
+ $this->showCheckbox('perpost_stats', __('Show per post stats', 'wp-piwik'), __('Show stats about single posts at the post edit admin page.', 'wp-piwik'));
132
+
133
+ $this->showCheckbox('piwik_shortcut', __('Piwik shortcut', 'wp-piwik'), __('Display a shortcut to Piwik itself.', 'wp-piwik'));
134
+
135
+ $this->showInput('plugin_display_name', __('WP-Piwik display name', 'wp-piwik'), __('Plugin name shown in WordPress.', 'wp-piwik'));
136
+
137
+ $this->showCheckbox('shortcodes', __('Enable shortcodes', 'wp-piwik'), __('Enable shortcodes in post or page content.', 'wp-piwik'));
138
+
139
+ echo $submitButton;
140
+ }
141
+
142
+ // Tracking Configuration
143
+ if (self::$wpPiwik->isConfigured()) {
144
+
145
+ $isNotTracking = self::$settings->getGlobalOption('track_mode') == 'disabled';
146
+ $isNotGeneratedTracking = $isNotTracking || self::$settings->getGlobalOption('track_mode') == 'manually';
147
+ $fullGeneratedTrackingGroup = 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js wp-piwik-track-option-proxy';
148
+
149
+ $this->showHeadline(2, 'location-alt', 'Enable Tracking');
150
+
151
+ $description = sprintf('%s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s<br /><strong>%s:</strong> %s',
152
+ __('You can choose between four tracking code modes:', 'wp-piwik'),
153
+ __('Disabled', 'wp-piwik'),
154
+ __('WP-Piwik will not add the tracking code. Use this, if you want to add the tracking code to your template files or you use another plugin to add the tracking code.', 'wp-piwik'),
155
+ __('Default tracking', 'wp-piwik'),
156
+ __('TODO', 'wp-piwik'),
157
+ __('Use js/index.php', 'wp-piwik'),
158
+ __('TODO', 'wp-piwik'),
159
+ __('Use proxy script', 'wp-piwik'),
160
+ __('TODO', 'wp-piwik'),
161
+ __('Enter manually', 'wp-piwik'),
162
+ __('TODO', 'wp-piwik')
163
+ );
164
+ $this->showSelect('track_mode', __('Add tracking code', 'wp-piwik'),
165
+ array(
166
+ 'disabled' => __('Disabled', 'wp-piwik'),
167
+ 'default' => __('Default tracking', 'wp-piwik'),
168
+ 'js' => __('Use js/index.php', 'wp-piwik'),
169
+ 'proxy' => __('Use proxy script', 'wp-piwik'),
170
+ 'manually' => __('Enter manually', 'wp-piwik')
171
+ ), $description, '$j(\'tr.wp-piwik-track-option\').addClass(\'hidden\'); $j(\'tr.wp-piwik-track-option-\' + $j(\'#track_mode\').val()).removeClass(\'hidden\'); $j(\'#tracking_code, #noscript_code\').prop(\'readonly\', $j(\'#track_mode\').val() != \'manually\');');
172
+
173
+ $this->showTextarea('tracking_code', __('Tracking code', 'wp-piwik'), 15, 'TODO tracking code desc', $isNotTracking, 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js wp-piwik-track-option-proxy wp-piwik-track-option-manually', true, '', (self::$settings->getGlobalOption('track_mode') != 'manually'), false);
174
+
175
+ $this->showSelect('track_codeposition', __('JavaScript code position', 'wp-piwik'),
176
+ array(
177
+ 'footer' => __('Footer', 'wp-piwik'),
178
+ 'header' => __('Header', 'wp-piwik')
179
+ ), __('Choose whether the JavaScript code is added to the footer or the header.', 'wp-piwik'), '', $isNotTracking, 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js wp-piwik-track-option-proxy wp-piwik-track-option-manually');
180
+
181
+ $this->showTextarea('noscript_code', __('Noscript code', 'wp-piwik'), 2, 'TODO noscript code desc', $isNotTracking, 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js wp-piwik-track-option-proxy wp-piwik-track-option-manually', true, '', (self::$settings->getGlobalOption('track_mode') != 'manually'), false);
182
+
183
+ $this->showCheckbox('track_noscript', __('Add &lt;noscript&gt;', 'wp-piwik'), __('Adds the &lt;noscript&gt; code to your footer.', 'wp-piwik').' '.__('Disabled in proxy mode.', 'wp-piwik'), $isNotGeneratedTracking || self::$settings->getGlobalOption('track_mode') == 'proxy', 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js wp-piwik-track-option-manually');
184
+
185
+ $this->showCheckbox('track_nojavascript', __('Add rec parameter to noscript code', 'wp-piwik'), __('Enable tracking for visitors without JavaScript (not recommended).', 'wp-piwik').' '.sprintf(__('See %sPiwik FAQ%s.', 'wp-piwik'),'<a href="http://piwik.org/faq/how-to/#faq_176">','</a>').' '.__('Disabled in proxy mode.', 'wp-piwik'), $isNotGeneratedTracking || self::$settings->getGlobalOption('track_mode') == 'proxy', 'wp-piwik-track-option wp-piwik-track-option-default wp-piwik-track-option-js');
186
+
187
+ $this->showCheckbox('track_search', __('Track search', 'wp-piwik'), __('Use Piwik\'s advanced Site Search Analytics feature.').' '.sprintf(__('See %sPiwik documentation%s.', 'wp-piwik'),'<a href="http://piwik.org/docs/site-search/#track-site-search-using-the-tracking-api-advanced-users-only">','</a>'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
188
+
189
+ $this->showCheckbox('track_404', __('Track 404', 'wp-piwik'), __('WP-Piwik can automatically add a 404-category to track 404-page-visits.', 'wp-piwik'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
190
+
191
+ $this->showCheckbox('add_post_annotations', __('Add annotation on new post', 'wp-piwik'), __('Add a Piwik annotation on each new post.', 'wp-piwik').' '.sprintf(__('See %sPiwik documentation%s.', 'wp-piwik'),'<a href="http://piwik.org/docs/annotations/">','</a>'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
192
+
193
+ $this->showCheckbox('add_customvars_box', __('Show custom variables box', 'wp-piwik'), __(' Show a &quot;custom variables&quot; edit box on post edit page.', 'wp-piwik').' '.sprintf(__('See %sPiwik documentation%s.', 'wp-piwik'),'<a href="http://piwik.org/docs/custom-variables/">','</a>'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
194
+
195
+ $this->showInput('add_download_extensions', __('Add new file types for download tracking', 'wp-piwik'), __('Add file extensions for download tracking, divided by a vertical bar (&#124;).', 'wp-piwik').' '.sprintf(__('See %sPiwik documentation%s.', 'wp-piwik'),'<a href="https://developer.piwik.org/guides/tracking-javascript-guide#file-extensions-for-tracking-downloads">','</a>'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup);
196
+
197
+ $this->showCheckbox('disable_cookies', __('Disable cookies', 'wp-piwik'), __('Disable all tracking cookies for a visitor.', 'wp-piwik'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup);
198
+
199
+ $this->showCheckbox('limit_cookies', __('Limit cookie lifetime', 'wp-piwik'), __('TODO cookie lifetime desc', 'wp-piwik'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup, true, '$j(\'tr.wp-piwik-cookielifetime-option\').toggle(\'hidden\');');
200
+
201
+ $this->showInput('limit_cookies_visitor', __('Visitor timeout (seconds)', 'wp-piwik'), false, $isNotGeneratedTracking || !self::$settings->getGlobalOption('limit_cookies'), $fullGeneratedTrackingGroup.' wp-piwik-cookielifetime-option');
202
+
203
+ $this->showInput('limit_cookies_session', __('Session timeout (seconds)', 'wp-piwik'), false, $isNotGeneratedTracking || !self::$settings->getGlobalOption('limit_cookies'), $fullGeneratedTrackingGroup.' wp-piwik-cookielifetime-option');
204
+
205
+ $this->showCheckbox('track_admin', __('Track admin pages', 'wp-piwik'), __('Enable to track users on admin pages (remember to configure the tracking filter appropriately).', 'wp-piwik'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
206
+
207
+ echo '<tr class="'.$fullGeneratedTrackingGroup.' wp-piwik-track-option-manually'.($isNotTracking?' hidden':'').'">';
208
+ echo '<th scope="row"><label for="capability_stealth">'.__('Tracking filter', 'wp-piwik').'</label>:</th><td>';
209
+ $filter = self::$settings->getGlobalOption('capability_stealth');
210
+ foreach($wp_roles->role_names as $key => $name)
211
+ echo '<input type="checkbox" '.(isset($filter[$key]) && $filter[$key]?'checked="checked" ':'').'value="1" name="wp-piwik[capability_stealth]['.$key.']" /> '.$name.' &nbsp; ';
212
+ echo '<span class="dashicons dashicons-editor-help" onclick="$j(\'#capability_stealth-desc\').toggleClass(\'hidden\');"></span> <p class="description hidden" id="capability_stealth-desc">'.__('Choose users by user role you do <strong>not</strong> want to track.', 'wp-piwik').'</p></td></tr>';
213
+
214
+ $this->showCheckbox('track_across', __('Track visitors across all subdomains', 'wp-piwik'), __('Adds *.-prefix to cookie domain.', 'wp-piwik'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup);
215
+
216
+ $this->showCheckbox('track_across_alias', __('Track visitors across all alias URLs', 'wp-piwik'), __('Adds *.-prefix to tracked domain.', 'wp-piwik'), $isNotGeneratedTracking, $fullGeneratedTrackingGroup);
217
+
218
+ $this->showCheckbox('track_feed', __('Track RSS feeds', 'wp-piwik'), __('Enable to track posts in feeds via tracking pixel.', 'wp-piwik'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually');
219
+
220
+ $this->showCheckbox('track_feed_addcampaign', __('Track RSS feed links as campaign', 'wp-piwik'), __('This will add Piwik campaign parameters to the RSS feed links.'.' '.sprintf(__('See %sPiwik documentation%s.', 'wp-piwik'),'<a href="http://piwik.org/docs/tracking-campaigns/">','</a>'), 'wp-piwik'), $isNotTracking, $fullGeneratedTrackingGroup.' wp-piwik-track-option-manually', true, '$j(\'tr.wp-piwik-feed_campaign-option\').toggle(\'hidden\');');
221
+
222
+ $this->showInput('track_feed_campaign', __('RSS feed campaign', 'wp-piwik'), __('Keyword: post name.', 'wp-piwik'), $isNotGeneratedTracking || !self::$settings->getGlobalOption('track_feed_addcampaign'), $fullGeneratedTrackingGroup.' wp-piwik-feed_campaign-option');
223
+
224
+ echo $submitButton;
225
+ }
226
+
227
+ $this->showHeadline(2, 'shield', 'Expert Settings');
228
+ $this->showText(__('Usually, you do not need to change these settings. If you want to do so, you should know what you do or you got an expert\'s advice.', 'wp-piwik'));
229
+
230
+ $this->showCheckbox('cache', __('Enable cache', 'wp-piwik'), __('Cache API calls, which not contain today\'s values, for a week.', 'wp-piwik'));
231
+
232
+ $this->showCheckbox('disable_timelimit', __('Disable time limit', 'wp-piwik'), __('Use set_time_limit(0) if stats page causes a time out.', 'wp-piwik'));
233
+
234
+ $this->showInput('connection_timeout', __('Connection timeout', 'wp-piwik'), 'TODO Connection timeout description');
235
+
236
+ $this->showCheckbox('disable_ssl_verify', __('Disable SSL peer verification', 'wp-piwik'), '('.__('not recommended', 'wp-piwik').')');
237
+
238
+ $this->showSelect('piwik_useragent', __('User agent', 'wp-piwik'),
239
+ array(
240
+ 'php' => __('Use the PHP default user agent', 'wp-piwik').(ini_get('user_agent')?'('.ini_get('user_agent').')':' ('.__('empty', 'wp-piwik').')'),
241
+ 'own' => __('Define a specific user agent', 'wp-piwik')
242
+ ), 'TODO User agent description', '$j(\'tr.wp-piwik-useragent-option\').toggleClass(\'hidden\');'
243
+ );
244
+ $this->showInput('piwik_useragent_string', __('Specific user agent', 'wp-piwik'), 'TODO Specific user agent description', self::$settings->getGlobalOption('piwik_useragent') != 'own', 'wp-piwik-useragent-option');
245
+
246
+ $this->showCheckbox('track_datacfasync', __('Add data-cfasync=false', 'wp-piwik'), __('Adds data-cfasync=false to the script tag, e.g., to ask Rocket Loader to ignore the script.'.' '.sprintf(__('See %sCloudFlare Knowledge Base%s.', 'wp-piwik'),'<a href="https://support.cloudflare.com/hc/en-us/articles/200169436-How-can-I-have-Rocket-Loader-ignore-my-script-s-in-Automatic-Mode-">','</a>'), 'wp-piwik'));
247
+
248
+ $this->showInput('track_cdnurl', __('CDN URL', 'wp-piwik'), 'Enter URL if you want to load the tracking code via CDN.');
249
+
250
+ $this->showInput('track_cdnurlssl', __('CDN URL (SSL)', 'wp-piwik'), 'Enter URL if you want to load the tracking code via a separate SSL CDN.');
251
+
252
+ $this->showSelect('force_protocol', __('Force Piwik to use a specific protocol', 'wp-piwik'),
253
+ array(
254
+ 'disabled' => __('Disabled (default)', 'wp-piwik'),
255
+ 'http' => __('http', 'wp-piwik'),
256
+ 'https' => __('https (SSL)', 'wp-piwik')
257
+ ), __('Choose if you want to explicitly force Piwik to use HTTP or HTTPS. Does not work with a CDN URL.', 'wp-piwik')
258
+ );
259
+
260
+ echo $submitButton;
261
+ ?> </tbody>
262
+ </table>
263
+ </form>
264
+ </div>
265
+ <?php
266
+ }
267
+
268
+ private function getDescription($id, $description, $hideDescription = true) {
269
+ return sprintf('<span class="dashicons dashicons-editor-help" onclick="$j(\'#%s-desc\').toggleClass(\'hidden\');"></span> <p class="description'.($hideDescription?' hidden':'').'" id="%1$s-desc">%s</p>', $id, $description);
270
+ }
271
+
272
+ private function showCheckbox($id, $name, $description, $isHidden = false, $groupName = '', $hideDescription = true, $onChange = '') {
273
+ printf('<tr class="'.$groupName.($isHidden?' hidden':'').'"><th scope="row"><label for="%2$s">%s</label>:</th><td><input type="checkbox" value="1"'.(self::$settings->getGlobalOption($id)?' checked="checked"':'').' onchange="$j(\'#%s\').val(this.checked?1:0);%s" /><input id="%2$s" type="hidden" name="wp-piwik[%2$s]" value="'.(int)self::$settings->getGlobalOption($id).'" /> %s</td></tr>', $name, $id, $onChange ,$this->getDescription($id, $description, $hideDescription));
274
+ }
275
+
276
+ private function showTextarea($id, $name, $rows, $description, $isHidden, $groupName, $hideDescription = true, $onChange = '', $isReadonly = false, $global = true) {
277
+ printf('<tr class="'.$groupName.($isHidden?' hidden':'').'"><th scope="row"><label for="%2$s">%s</label>:</th><td><textarea cols="80" rows="'.$rows.'" id="%s" name="wp-piwik[%2$s]" onchange="%s"'.($isReadonly?' readonly="readonly"':'').'>'.($global?self::$settings->getGlobalOption($id):self::$settings->getOption($id)).'</textarea> %s</td></tr>', $name, $id, $onChange ,$this->getDescription($id, $description, $hideDescription));
278
+ }
279
+
280
+ private function showText($text) {
281
+ printf('<tr><td colspan="2"><p>%s</p></td></tr>', $text);
282
+ }
283
+
284
+ private function showInput($id, $name, $description, $isHidden = false, $groupName='', $rowName=false, $hideDescription = true) {
285
+ printf('<tr class="%s%s"%s><th scope="row"><label for="%5$s">%s:</label></th><td><input name="wp-piwik[%s]" id="%5$s" value="%s" /> %s</td></tr>', $isHidden?'hidden ':'', $groupName?$groupName:'', $rowName?' id="'.$groupName.'-'.$rowName.'"':'', $name, $id, self::$settings->getGlobalOption($id), $this->getDescription($id, $description, $hideDescription));
286
+ }
287
+
288
+ private function showSelect($id, $name, $options = array(), $description = '', $onChange = '', $isHidden = false, $groupName = '', $hideDescription = true, $global = true) {
289
+ $optionList = '';
290
+ $default = $global?self::$settings->getGlobalOption($id):self::$settings->getOption($id);
291
+ if (is_array($options))
292
+ foreach ($options as $key => $value)
293
+ $optionList .= sprintf('<option value="%s"'.($key == $default?' selected="selected"':'').'>%s</option>', $key, $value);
294
+ printf ('<tr class="'.$groupName.($isHidden?' hidden':'').'"><th scope="row"><label for="%2$s">%s:</label></th><td><select name="wp-piwik[%s]" id="%2$s" onchange="%s">%s</select> %s</td></tr>', $name, $id, $onChange, $optionList, $this->getDescription($id, $description, $hideDescription));
295
+ }
296
+
297
+ private function showBox($type, $icon, $content) {
298
+ printf('<tr><td colspan="2"><div class="%s"><p><span class="dashicons dashicons-%s"></span> %s</p></div></td></tr>', $type, $icon, $content);
299
+ }
300
+
301
+ private function showHeadline($order, $icon, $headline, $addPluginName = false) {
302
+ echo $this->getHeadline($order, $icon, $headline, $addPluginName = false);
303
+ }
304
+
305
+ private function getHeadline($order, $icon, $headline, $addPluginName = false) {
306
+ printf('<tr><td colspan="2"><h%d><span class="dashicons dashicons-%s"></span> %s%s</h%1$d></td></tr>', $order, $icon, ($addPluginName?self::$settings->getGlobalOption('plugin_display_name').' ':''), __($headline, 'wp-piwik'));
307
+ }
308
+
309
+ private function showDonation() {?>
310
+ <div class="wp-piwik-donate">
311
+ <p><strong><?php _e('Donate','wp-piwik'); ?></strong></p>
312
+ <p><?php _e('If you like WP-Piwik, you can support its development by a donation:', 'wp-piwik'); ?></p>
313
+ <script type="text/javascript">
314
+ /* <![CDATA[ */
315
+ window.onload = function() {
316
+ FlattrLoader.render({
317
+ 'uid': 'flattr',
318
+ 'url': 'http://wp.local',
319
+ 'title': 'Title of the thing',
320
+ 'description': 'Description of the thing'
321
+ }, 'element_id', 'replace');
322
+ }
323
+ /* ]]> */
324
+ </script>
325
+ <div>
326
+ <a class="FlattrButton" style="display:none;" title="WordPress Plugin WP-Piwik" rel="flattr;uid:braekling;category:software;tags:wordpress,piwik,plugin,statistics;" href="https://www.braekling.de/wp-piwik-wpmu-piwik-wordpress">This WordPress plugin adds a Piwik stats site to your WordPress dashboard. It's also able to add the Piwik tracking code to your blog using wp_footer. You need a running Piwik installation and at least view access to your stats.</a>
327
+ </div>
328
+ <div>Paypal
329
+ <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
330
+ <input type="hidden" name="cmd" value="_s-xclick" />
331
+ <input type="hidden" name="hosted_button_id" value="6046779" />
332
+ <input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donateCC_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." />
333
+ <img alt="" border="0" src="https://www.paypal.com/de_DE/i/scr/pixel.gif" width="1" height="1" />
334
+ </form>
335
+ </div>
336
+ <div>
337
+ <a href="http://www.amazon.de/gp/registry/wishlist/111VUJT4HP1RA?reveal=unpurchased&amp;filter=all&amp;sort=priority&amp;layout=standard&amp;x=12&amp;y=14"><?php _e('My Amazon.de wishlist', 'wp-piwik'); ?></a>
338
+ </div>
339
+ <div>
340
+ <?php _e('Please don\'t forget to vote the compatibility at the','wp-piwik'); ?> <a href="http://wordpress.org/extend/plugins/wp-piwik/">WordPress.org Plugin Directory</a>.
341
+ </div>
342
+ </div><?php
343
+ }
344
+
345
+ public function printAdminScripts() {
346
+ wp_enqueue_script('jquery');
347
+ }
348
+
349
+ public function extendAdminHeader() {
350
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
351
+ echo '<script type="text/javascript">/* <![CDATA[ */(function() {var s = document.createElement(\'script\');var t = document.getElementsByTagName(\'script\')[0];s.type = \'text/javascript\';s.async = true;s.src = \'//api.flattr.com/js/0.6/load.js?mode=auto\';t.parentNode.insertBefore(s, t);})();/* ]]> */</script>';
352
+ }
353
+
354
+ }
classes/WP_Piwik/Admin/Sitebrowser.php ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Admin;
4
+
5
+ class Sitebrowser extends WP_List_Table {
6
+
7
+ private $data = array();
8
+
9
+ public function __construct($wpPiwik, $isNetwork = false) {
10
+ $bolCURL = function_exists('curl_init');
11
+ $bolFOpen = ini_get('allow_url_fopen');
12
+ if (!$bolFOpen && !$bolCURL) {
13
+ echo '<table><tr><td colspan="2"><strong>';
14
+ _e('Error: cURL is not enabled and fopen is not allowed to open URLs. WP-Piwik won\'t be able to connect to Piwik.');
15
+ echo '</strong></td></tr></table>';
16
+ } else {
17
+ if (!class_exists('WP_List_Table'))
18
+ require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
19
+ if (isset($_GET['wpmu_show_stats']) && ($_GET['wpmu_show_stats'] == (int) $_GET['wpmu_show_stats'])) {
20
+ $this->addPiwikSite();
21
+ }
22
+ $cnt = $this->prepare_items($isNetwork);
23
+ if ($cnt > 0) $this->display();
24
+ else echo '<p>No site configured yet.</p>';
25
+ }
26
+ }
27
+
28
+ private function get_columns(){
29
+ $columns = array(
30
+ 'id' => __('ID','wp-piwik'),
31
+ 'name' => __('Title','wp-piwik'),
32
+ 'siteurl' => __('URL','wp-piwik'),
33
+ 'piwikid' => __('Site ID (Piwik)','wp-piwik')
34
+ );
35
+ return $columns;
36
+ }
37
+
38
+ private function prepare_items($bolNetwork = false) {
39
+ $current_page = $this->get_pagenum();
40
+ $per_page = 10;
41
+ global $blog_id;
42
+ global $wpdb;
43
+ global $pagenow;
44
+ if (is_plugin_active_for_network('wp-piwik/wp-piwik.php')) {
45
+ $total_items = $wpdb->get_var('SELECT COUNT(*) FROM '.$wpdb->blogs);
46
+ $blogs = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM '.$wpdb->blogs.' ORDER BY blog_id LIMIT %d,%d',(($current_page-1)*$per_page),$per_page));
47
+ foreach ($blogs as $blog) {
48
+ $blogDetails = get_blog_details($blog->blog_id, true);
49
+ $this->data[] = array(
50
+ 'name' => $blogDetails->blogname,
51
+ 'id' => $blogDetails->blog_id,
52
+ 'siteurl' => $blogDetails->siteurl,
53
+ 'piwikid' => WP-Piwik::getSiteID($blogDetails->blog_id)
54
+ );
55
+ }
56
+ } else {
57
+ $blogDetails = get_bloginfo();
58
+ $this->data[] = array(
59
+ 'name' => get_bloginfo('name'),
60
+ 'id' => '-',
61
+ 'siteurl' => get_bloginfo('url'),
62
+ 'piwikid' => WP-Piwik::getSiteID()
63
+ );
64
+ $total_items = 1;
65
+ }
66
+ $columns = $this->get_columns();
67
+ $hidden = array();
68
+ $sortable = array();
69
+ $this->_column_headers = array($columns, $hidden, $sortable);
70
+ $this->set_pagination_args(array(
71
+ 'total_items' => $total_items,
72
+ 'per_page' => $per_page
73
+ ));
74
+ if ($isNetwork) $pagenow = 'settings.php';
75
+ foreach ($this->data as $key => $dataset) {
76
+ if (empty($dataset['piwikid']) || !is_int($dataset['piwikid']))
77
+ $this->data[$key]['piwikid'] = '<a href="'.admin_url(($pagenow == 'settings.php'?'network/':'')).$pagenow.'?page=wp-piwik/wp-piwik.php&tab=sitebrowser'.($dataset['id'] != '-'?'&wpmu_show_stats='.$dataset['id']:'').'">Create Piwik site</a>';
78
+ if ($isNetwork)
79
+ $this->data[$key]['name'] = '<a href="?page=wp-piwik_stats&wpmu_show_stats='.$dataset['id'].'">'.$dataset['name'].'</a>';
80
+ }
81
+ $this->items = $this->data;
82
+ return count($this->items);
83
+ }
84
+
85
+ function column_default( $item, $column_name ) {
86
+ switch( $column_name ) {
87
+ case 'id':
88
+ case 'name':
89
+ case 'siteurl':
90
+ case 'piwikid':
91
+ return $item[$column_name];
92
+ default:
93
+ return print_r($item,true);
94
+ }
95
+ }
96
+ }
classes/WP_Piwik/Admin/Statistics.php ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Admin;
4
+
5
+ class Statistics extends \WP_Piwik\Admin {
6
+
7
+ public function show($isNetwork = false) {
8
+ global $screen_layout_columns;
9
+ if (empty($screen_layout_columns)) $screen_layout_columns = 2;
10
+ if (self::$settings->getGlobalOption('disable_timelimit')) set_time_limit(0);
11
+ echo '<div id="wp-piwik-stats-general" class="wrap">';
12
+ echo '<h2>'.(self::$settings->getGlobalOption('plugin_display_name') == 'WP-Piwik'?'Piwik '.__('Statistics', 'wp-piwik'):self::$settings->getGlobalOption('plugin_display_name')).'</h2>';
13
+ if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin() && $isNetwork) {
14
+ if (isset($_GET['wpmu_show_stats'])) {
15
+ switch_to_blog((int) $_GET['wpmu_show_stats']);
16
+ } else {
17
+ new WP_Piwik\Admin\Sitebrowser(self::$wpPiwik, $isNetwork);
18
+ return;
19
+ }
20
+ echo '<p>'.__('Currently shown stats:').' <a href="'.get_bloginfo('url').'">'.(int) $_GET['wpmu_show_stats'].' - '.get_bloginfo('name').'</a>.'.' <a href="?page=wp-piwik_stats">Show site overview</a>.</p>';
21
+ echo '</form>'."\n";
22
+ }
23
+ echo '<form action="admin-post.php" method="post"><input type="hidden" name="action" value="save_wp-piwik_stats_general" /><div id="dashboard-widgets" class="metabox-holder columns-'.$screen_layout_columns.(2 <= $screen_layout_columns?' has-right-sidebar':'').'">';
24
+ wp_nonce_field('wp-piwik_stats-general');
25
+ wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
26
+ wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
27
+ $columns = array('normal', 'side', 'column3');
28
+ for ($i = 0; $i < 3; $i++) {
29
+ echo '<div id="postbox-container-'.($i+1).'" class="postbox-container">';
30
+ do_meta_boxes(self::$wpPiwik->statsPageId, $columns[$i], null);
31
+ echo '</div>';
32
+ }
33
+ echo '</div></form></div>';
34
+ echo '<script type="text/javascript">//<![CDATA['."\n";
35
+ echo 'jQuery(document).ready(function($) {$(".if-js-closed").removeClass("if-js-closed").addClass("closed"); postboxes.add_postbox_toggles("'.self::$wpPiwik->statsPageId.'");});'."\n";
36
+ echo '//]]></script>'."\n";
37
+ if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
38
+ restore_current_blog();
39
+ }
40
+ }
41
+
42
+ public function printAdminScripts() {
43
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
44
+ wp_enqueue_script('wp-piwik-jqplot', self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'), self::$wpPiwik->getPluginVersion());
45
+ }
46
+
47
+ public function extendAdminHeader() {
48
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.(self::$wpPiwik->getPluginURL()).'js/jqplot/excanvas.min.js"></script><![endif]-->';
49
+ echo '<link rel="stylesheet" href="'.(self::$wpPiwik->getPluginURL()).'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
50
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
51
+ }
52
+
53
+ }
classes/{WP_Piwik_Logger.php → WP_Piwik/Logger.php} RENAMED
@@ -1,6 +1,8 @@
1
  <?php
2
 
3
- abstract class WP_Piwik_Logger {
 
 
4
 
5
  private $loggerName = 'unnamed';
6
  private $loggerContent = array();
1
  <?php
2
 
3
+ namespace WP_Piwik;
4
+
5
+ abstract class Logger {
6
 
7
  private $loggerName = 'unnamed';
8
  private $loggerContent = array();
classes/WP_Piwik/Logger/Dummy.php ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Logger;
4
+
5
+ class Dummy extends \WP_Piwik\Logger {
6
+
7
+ public function loggerOutput($loggerTime, $loggerMessage) {}
8
+
9
+ }
classes/{WP_Piwik_Logger_File.php → WP_Piwik/Logger/File.php} RENAMED
@@ -1,8 +1,8 @@
1
  <?php
2
-
3
- require_once('WP_Piwik_Logger.php');
4
 
5
- class WP_Piwik_Logger_File extends WP_Piwik_Logger {
 
 
6
 
7
  private $loggerFile = null;
8
 
@@ -13,7 +13,7 @@
13
  }
14
 
15
  private function setFilename() {
16
- $this->loggerFile = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.
17
  date('Ymd').'_'.$this->encodeFilename($this->getName()).'.log';
18
  }
19
 
1
  <?php
 
 
2
 
3
+ namespace WP_Piwik\Logger;
4
+
5
+ class File extends \WP_Piwik\Logger {
6
 
7
  private $loggerFile = null;
8
 
13
  }
14
 
15
  private function setFilename() {
16
+ $this->loggerFile = WP_PIWIK_PATH.'logs'.DIRECTORY_SEPARATOR.
17
  date('Ymd').'_'.$this->encodeFilename($this->getName()).'.log';
18
  }
19
 
classes/WP_Piwik/Logger/Screen.php ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Logger;
4
+
5
+ class Screen extends \WP_Piwik\Logger {
6
+
7
+ private $logs = array();
8
+
9
+ private function formatMicrotime($loggerTime) {
10
+ return sprintf('[%6s sec]',number_format($loggerTime,3));
11
+ }
12
+
13
+ public function __construct($loggerName) {
14
+ add_action(is_admin()?'admin_footer':'wp_footer', array($this, 'echoResults'));
15
+ parent::__construct($loggerName);
16
+ }
17
+
18
+ public function loggerOutput($loggerTime, $loggerMessage) {
19
+ $this->logs[] = $this->formatMicrotime($loggerTime).' '.$loggerMessage;
20
+ }
21
+
22
+ public function echoResults() {
23
+ echo '<pre>';
24
+ print_r($this->logs);
25
+ echo '</pre>';
26
+ }
27
+ }
classes/WP_Piwik/Request.php ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ abstract class Request {
6
+
7
+ protected static $wpPiwik, $settings, $requests = array(), $results = array(), $piwikVersion;
8
+
9
+ public function __construct($wpPiwik, $settings) {
10
+ self::$wpPiwik = $wpPiwik;
11
+ self::$settings = $settings;
12
+ self::register('API.getPiwikVersion', array());
13
+ }
14
+
15
+ public static function register($method, $parameter) {
16
+ if ($method == 'API.getPiwikVersion')
17
+ $id = 'global.getPiwikVersion';
18
+ else
19
+ $id = 'method='.$method.self::parameterToString($parameter);
20
+ if (!isset(self::$requests[$id]))
21
+ self::$requests[$id] = array('method' => $method, 'parameter' => $parameter);
22
+ return $id;
23
+ }
24
+
25
+ private static function parameterToString($parameter) {
26
+ $return = '';
27
+ if (is_array($parameter))
28
+ foreach ($parameter as $key => $value)
29
+ $return .= '&'.$key.'='.$value;
30
+ return $return;
31
+ }
32
+
33
+ public function perform($id) {
34
+ self::$wpPiwik->log("Perform request: ".$id);
35
+ if (!isset(self::$requests[$id]))
36
+ return array('result' => 'error', 'message' => 'Request '.$id.' was not registered.');
37
+ elseif (!isset(self::$results[$id])) {
38
+ $this->request($id);
39
+ }
40
+ return isset(self::$results[$id])?self::$results[$id]:false;
41
+ }
42
+
43
+ protected function buildURL($config, $urlDecode = false) {
44
+ $url = 'method='.($config['method']).'&idSite='.self::$settings->getOption('site_id');
45
+ foreach ($config['parameter'] as $key => $value)
46
+ $url .= '&'.$key.'='.($urlDecode?urldecode($value):$value);
47
+ return $url;
48
+ }
49
+
50
+ protected function unserialize($str) {
51
+ self::$wpPiwik->log("Result string: ".$str);
52
+ return ($str == serialize(false) || @unserialize($str) !== false)?unserialize($str):array();
53
+ }
54
+
55
+ abstract protected function request($id);
56
+
57
+ }
classes/WP_Piwik/Request/Php.php ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Request;
4
+
5
+ class Php extends \WP_Piwik\Request {
6
+
7
+ protected function request($id) {
8
+ $count = 0;
9
+ $url = self::$settings->getGlobalOption('piwik_url');
10
+ foreach (self::$requests as $requestID => $config) {
11
+ if (!isset(self::$results[$requestID])) {
12
+ $params = 'module=API&format=php&'.$this->buildURL($config, true);
13
+ $map[$count] = $requestID;
14
+ $result = $this->call($url, $params);
15
+ self::$results[$map[$count]] = $result;
16
+ $count++;
17
+ }
18
+ }
19
+ }
20
+
21
+ private function call($url, $params) {
22
+ if (!defined('PIWIK_INCLUDE_PATH'))
23
+ return;
24
+ if (PIWIK_INCLUDE_PATH === FALSE)
25
+ return serialize(array('result' => 'error', 'message' => __('Could not resolve','wp-piwik').' &quot;'.htmlentities(self::$settings->getGlobalOption('piwik_path')).'&quot;: '.__('realpath() returns false','wp-piwik').'.'));
26
+ if (file_exists(PIWIK_INCLUDE_PATH . "/index.php"))
27
+ require_once PIWIK_INCLUDE_PATH . "/index.php";
28
+ if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php"))
29
+ require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
30
+ if (class_exists('Piwik\FrontController'))
31
+ \Piwik\FrontController::getInstance()->init();
32
+ else serialize(array('result' => 'error', 'message' => __('Class Piwik\FrontController does not exists.','wp-piwik')));
33
+ if (class_exists('Piwik\API\Request'))
34
+ $request = new \Piwik\API\Request($params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
35
+ else serialize(array('result' => 'error', 'message' => __('Class Piwik\API\Request does not exists.','wp-piwik')));
36
+ $result = $request->process();
37
+ if (!headers_sent())
38
+ header("Content-Type: text/html", true);
39
+ return $this->unserialize($result);
40
+ }
41
+ }
classes/WP_Piwik/Request/Rest.php ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Request;
4
+
5
+ class Rest extends \WP_Piwik\Request {
6
+
7
+ protected function request($id) {
8
+ $count = 0;
9
+ $url = self::$settings->getGlobalOption('piwik_mode') == 'http'?
10
+ self::$settings->getGlobalOption('piwik_url'):
11
+ 'https://'.self::$settings->getGlobalOption('piwik_user').'.piwik.pro/';
12
+ $params = 'module=API&method=API.getBulkRequest&format=php';
13
+ foreach (self::$requests as $requestID => $config) {
14
+ if (!isset(self::$results[$requestID])) {
15
+ $params .= '&urls['.$count.']='.urlencode($this->buildURL($config));
16
+ $map[$count] = $requestID;
17
+ $count++;
18
+ }
19
+ }
20
+ $results = (function_exists('curl_init')?$this->curl($url, $params):$this->fopen($url, $params));
21
+ foreach ($results as $num => $result)
22
+ self::$results[$map[$num]] = $result;
23
+ }
24
+
25
+ private function curl($url, $params) {
26
+ $c = curl_init($url);
27
+ curl_setopt($c, CURLOPT_POST, 1);
28
+ curl_setopt($c, CURLOPT_POSTFIELDS, $params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
29
+ curl_setopt($c, CURLOPT_SSL_VERIFYPEER, !self::$settings->getGlobalOption('disable_ssl_verify'));
30
+ curl_setopt($c, CURLOPT_USERAGENT, self::$settings->getGlobalOption('piwik_useragent')=='php'?ini_get('user_agent'):self::$settings->getGlobalOption('piwik_useragent_string'));
31
+ curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
32
+ curl_setopt($c, CURLOPT_HEADER, 0);
33
+ curl_setopt($c, CURLOPT_TIMEOUT, self::$settings->getGlobalOption('connection_timeout'));
34
+ $httpProxyClass = new \WP_HTTP_Proxy();
35
+ if ($httpProxyClass->is_enabled() && $httpProxyClass->send_through_proxy($strURL)) {
36
+ curl_setopt($c, CURLOPT_PROXY, $httpProxyClass->host());
37
+ curl_setopt($c, CURLOPT_PROXYPORT, $httpProxyClass->port());
38
+ if ($httpProxyClass->use_authentication())
39
+ curl_setopt($c, CURLOPT_PROXYUSERPWD, $httpProxyClass->username().':'.$httpProxyClass->password());
40
+ }
41
+ $result = curl_exec($c);
42
+ curl_close($c);
43
+ return $this->unserialize($result);
44
+ }
45
+
46
+ private function fopen($url, $params) {
47
+ $context = stream_context_create(array('http'=>array('timeout' => self::$settings->getGlobalOption('connection_timeout'))));
48
+ $result = @file_get_contents($url.'?'.$params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'), false, $context);
49
+ return unserialize($result);
50
+ }
51
+ }
classes/WP_Piwik/Settings.php ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ class Settings {
6
+
7
+ private static $wpPiwik, $logger, $defaultSettings;
8
+
9
+ private $checkSettings = array(
10
+ 'piwik_url' => 'checkPiwikUrl',
11
+ 'piwik_token' => 'checkPiwikToken',
12
+ 'tracking_code' => 'prepareTrackingCode',
13
+ 'noscript_code' => 'prepareNocscriptCode',
14
+ );
15
+
16
+ private $globalSettings = array(
17
+ // Plugin settings
18
+ 'revision' => 0,
19
+ 'last_settings_update' => 0,
20
+ // User settings: Piwik configuration
21
+ 'piwik_mode' => 'http',
22
+ 'piwik_url' => '',
23
+ 'piwik_path' => '',
24
+ 'piwik_user' => '',
25
+ 'piwik_token' => '',
26
+ 'auto_site_config' => true,
27
+ // User settings: Stats configuration
28
+ 'default_date' => 'yesterday',
29
+ 'stats_seo' => false,
30
+ 'dashboard_widget' => false,
31
+ 'dashboard_chart' => false,
32
+ 'dashboard_seo' => false,
33
+ 'toolbar' => false,
34
+ 'capability_read_stats' => array('administrator' => true),
35
+ 'perpost_stats' => false,
36
+ 'plugin_display_name' => 'WP-Piwik',
37
+ 'piwik_shortcut' => false,
38
+ 'shortcodes' => false,
39
+ // User settings: Tracking configuration
40
+ 'track_mode' => 'disabled',
41
+ 'track_codeposition' => 'footer',
42
+ 'track_noscript' => false,
43
+ 'track_nojavascript' => false,
44
+ 'track_search' => false,
45
+ 'track_404' => false,
46
+ 'add_post_annotations' => false,
47
+ 'add_customvars_box' => false,
48
+ 'add_download_extensions' => '',
49
+ 'disable_cookies' => false,
50
+ 'limit_cookies' => false,
51
+ 'limit_cookies_visitor' => 1209600,
52
+ 'limit_cookies_session' => 0,
53
+ 'track_admin' => false,
54
+ 'capability_stealth' => array(),
55
+ 'track_across' => false,
56
+ 'track_across_alias' => false,
57
+ 'track_feed' => false,
58
+ 'track_feed_addcampaign' => false,
59
+ 'track_feed_campaign' => 'feed',
60
+ // User settings: Expert configuration
61
+ 'cache' => true, //OK
62
+ 'disable_timelimit' => false,
63
+ 'connection_timeout' => 5,
64
+ 'disable_ssl_verify' => false,
65
+ 'piwik_useragent' => 'php',
66
+ 'piwik_useragent_string' => 'WP-Piwik',
67
+ 'track_datacfasync' => false,
68
+ 'track_cdnurl' => '',
69
+ 'track_cdnurlssl' => '',
70
+ 'force_protocol' => 'disabled',
71
+ ),
72
+ $settings = array(
73
+ 'name' => '',
74
+ 'site_id' => NULL,
75
+ 'noscript_code' => '',
76
+ 'tracking_code' => '',
77
+ 'last_tracking_code_update' => 0,
78
+ 'dashboard_revision' => 0
79
+ ),
80
+ $settingsChanged = false;
81
+
82
+ public function __construct($wpPiwik, $logger) {
83
+ self::$wpPiwik = $wpPiwik;
84
+ self::$logger = $logger;
85
+ self::$logger->log('Store default settings');
86
+ self::$defaultSettings = array('globalSettings' => $this->globalSettings, 'settings' => $this->settings);
87
+ self::$logger->log('Load settings');
88
+ foreach ($this->globalSettings as $key => $default) {
89
+ $this->globalSettings[$key] = ($this->checkNetworkActivation()?
90
+ get_site_option('wp-piwik_global-'.$key, $default):
91
+ get_option('wp-piwik_global-'.$key, $default)
92
+ );
93
+ }
94
+ foreach ($this->settings as $key => $default)
95
+ $this->settings[$key] = get_option('wp-piwik-'.$key, $default);
96
+ }
97
+
98
+ public function save() {
99
+ if (!$this->settingsChanged) {
100
+ self::$logger->log('No settings changed yet');
101
+ return;
102
+ }
103
+ self::$logger->log('Save settings');
104
+ foreach ($this->globalSettings as $key => $value) {
105
+ if (is_plugin_active_for_network('wp-piwik/wp-piwik.php'))
106
+ update_site_option('wp-piwik_global-'.$key, $value);
107
+ else
108
+ update_option('wp-piwik_global-'.$key, $value);
109
+ }
110
+ foreach ($this->settings as $key => $value) {
111
+ update_option('wp-piwik-'.$key, $value);
112
+ }
113
+ global $wp_roles;
114
+ if (!is_object($wp_roles))
115
+ $wp_roles = new \WP_Roles();
116
+ if (!is_object($wp_roles)) die("STILL NO OBJECT");
117
+ foreach($wp_roles->role_names as $strKey => $strName) {
118
+ $objRole = get_role($strKey);
119
+ foreach (array('stealth', 'read_stats') as $strCap) {
120
+ $aryCaps = $this->getGlobalOption('capability_'.$strCap);
121
+ if (isset($aryCaps[$strKey]) && $aryCaps[$strKey])
122
+ $objRole->add_cap('wp-piwik_'.$strCap);
123
+ else $objRole->remove_cap('wp-piwik_'.$strCap);
124
+ }
125
+ }
126
+ $this->settingsChanges = false;
127
+ }
128
+
129
+ public function getGlobalOption($key) {
130
+ return isset($this->globalSettings[$key])?$this->globalSettings[$key]:self::$defaultSettings['globalSettings'][$key];
131
+ }
132
+
133
+ public function getOption($key, $blogID = null) {
134
+ if ($this->checkNetworkActivation() && !empty($blogID)) {
135
+ return get_blog_option($blogID, $key);
136
+ }
137
+ return isset($this->settings[$key])?$this->settings[$key]:self::$defaultSettings['settings'][$key];
138
+ }
139
+
140
+ public function setGlobalOption($key, $value) {
141
+ $this->settingsChanged = true;
142
+ self::$logger->log('Changed global option '.$key.': '.(is_array($value)?serialize($value):$value));
143
+ $this->globalSettings[$key] = $value;
144
+ }
145
+
146
+ public function setOption($key, $value, $blogID = null) {
147
+ $this->settingsChanged = true;
148
+ self::$logger->log('Changed option '.$key.': '.$value);
149
+ if ($this->checkNetworkActivation() && !empty($blogID)) {
150
+ add_blog_option($blogID, $key, $value);
151
+ }
152
+ else $this->settings[$key] = $value;
153
+ }
154
+
155
+ public function resetSettings($bolFull = false) {
156
+ self::$logger->log('Reset WP-Piwik settings');
157
+ global $wpdb;
158
+ $keepSettings = array(
159
+ 'piwik_token' => $this->getGlobalOption('piwik_token'),
160
+ 'piwik_url' => $this->getGlobalOption('piwik_url'),
161
+ 'piwik_path' => $this->getGlobalOption('piwik_path'),
162
+ 'piwik_mode' => $this->getGlobalOption('piwik_mode')
163
+ );
164
+ if (is_plugin_active_for_network('wp-piwik/wp-piwik.php')) {
165
+ delete_site_option('wp-piwik_global-settings');
166
+ $aryBlogs = $wpdb->get_results('SELECT blog_id FROM '.$wpdb->blogs.' ORDER BY blog_id');
167
+ foreach ($aryBlogs as $aryBlog)
168
+ foreach ($this->settings as $key => $value)
169
+ delete_blog_option($aryBlog->blog_id, 'wp-piwik-'.$key);
170
+ if (!$bolFull) update_site_option('wp-piwik_global-settings', $keepSettings);
171
+ } else {
172
+ foreach ($this->globalSettings as $key => $value)
173
+ delete_option('wp-piwik_global-'.$key);
174
+ foreach ($this->settings as $key => $value)
175
+ delete_option('wp-piwik-'.$key);
176
+ }
177
+ $this->globalSettings = self::$defaultSettings['globalSettings'];
178
+ $this->settings = self::$defaultSettings['settings'];
179
+ if (!$bolFull) {
180
+ self::$logger->log('Restore connection settings');
181
+ foreach ($keepSettings as $key => $value)
182
+ $this->setGlobalOption($key, $value);
183
+ }
184
+ $this->save();
185
+ }
186
+
187
+ public function checkNetworkActivation() {
188
+ if (!function_exists("is_plugin_active_for_network"))
189
+ require_once(ABSPATH.'wp-admin/includes/plugin.php');
190
+ return is_plugin_active_for_network('wp-piwik/wp-piwik.php');
191
+ }
192
+
193
+ private function applyGlobalOption($id, $value) {
194
+ self::$logger->log('Set '.$id.': '.serialize($this->getGlobalOption($id)).' - '.serialize($value));
195
+ $this->setGlobalOption($id, $value);
196
+ }
197
+
198
+ private function applyOption($id, $value) {
199
+ self::$logger->log('Set '.$id.': '.serialize($this->getOption($id)).' - '.serialize($value));
200
+ $this->setOption($id, $value);
201
+ }
202
+
203
+ public function applyChanges($in) {
204
+ $in = $this->checkSettings($in);
205
+ self::$logger->log('Apply changed settings:');
206
+ foreach (self::$defaultSettings['globalSettings'] as $key => $val)
207
+ $this->applyGlobalOption($key, isset($in[$key]) ? $in[$key]:$val);
208
+ foreach (self::$defaultSettings['settings'] as $key => $val)
209
+ $this->applyOption($key, isset($in[$key]) ? $in[$key]:$val);
210
+ $this->setGlobalOption('last_settings_update', time());
211
+ $this->save();
212
+ }
213
+
214
+ public static function registerSettings() {
215
+ $class = 'WP_Piwik\Settings';
216
+ $stringValidator = array($class, 'validateString');
217
+ $n = 'wp-piwik';
218
+ $g = 'wp-piwik_global-';
219
+ register_setting($n, $g.'piwik_token', $stringValidator);
220
+ register_setting($n, $g.'piwik_url', $stringValidator);
221
+ }
222
+
223
+ public static function validateString($value) {
224
+ return $value;
225
+ }
226
+
227
+ private function checkSettings($in) {
228
+ foreach ($this->checkSettings as $key => $value)
229
+ if (isset($in[$key]))
230
+ $in[$key] = call_user_func_array(array($this, $value), array($in[$key], $in));
231
+ return $in;
232
+ }
233
+
234
+ private function checkPiwikUrl($value, $in) {
235
+ return substr($value,-1,1) != '/'?$value.'/':$value;
236
+ }
237
+
238
+ private function checkPiwikToken($value, $in) {
239
+ return str_replace('&token_auth=', '', $value);
240
+ }
241
+
242
+ private function prepareTrackingCode($value, $in) {
243
+ if ($in['track_mode'] == 'manually' || $in['track_mode'] == 'disabled') {
244
+ $value = stripslashes($value);
245
+ return $value;
246
+ }
247
+ $result = self::$wpPiwik->updateTrackingCode();
248
+ $this->setOption('noscript_code', $result['noscript']);
249
+ return $result['script'];
250
+ }
251
+
252
+ private function prepareNocscriptCode($value, $in) {
253
+ if ($in['track_mode'] == 'manually')
254
+ return stripslashes($value);
255
+ return $value;
256
+ }
257
+
258
+ }
classes/WP_Piwik/Shortcode.php ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ class Shortcode {
6
+
7
+ private $available = array(
8
+ 'opt-out' => 'OptOut',
9
+ 'post' => 'Post',
10
+ 'overview' => 'Overview'
11
+ );
12
+
13
+ public function __construct($attributes, $wpPiwik, $settings) {
14
+ $wpPiwik->log('Check requested shortcode widget '.$attributes['module']);
15
+ if (isset($attributes['module']) && isset($this->available[$attributes['module']])) {
16
+ $wpPiwik->log('Add shortcode widget '.$this->available[$attributes['module']]);
17
+ $class = '\\WP_Piwik\\Widget\\'.$this->available[$attributes['module']];
18
+ $widget = new $class($wpPiwik, $settings, null, null, null, $attributes, true);
19
+ $widget->show();
20
+ }
21
+ }
22
+
23
+ }
classes/{WP_Piwik_Template.php → WP_Piwik/Template.php} RENAMED
@@ -1,13 +1,14 @@
1
  <?php
2
 
3
- class WP_Piwik_Template {
 
 
4
 
5
  public static $logger, $settings, $wpPiwik;
6
 
7
- public function __construct($config) {
8
- self::$logger = $config['logger'];
9
- self::$settings = $config['settings'];
10
- self::$wpPiwik = $config['wp_piwik'];
11
  }
12
 
13
  public function output($array, $key, $default = '') {
@@ -26,7 +27,5 @@
26
  $end = time() + $diff;
27
  $start = time() - 2592000 + $diff;
28
  return date('Y-m-d', $start).','.date('Y-m-d', $end);
29
-
30
  }
31
-
32
  }
1
  <?php
2
 
3
+ namespace WP_Piwik;
4
+
5
+ class Template {
6
 
7
  public static $logger, $settings, $wpPiwik;
8
 
9
+ public function __construct($wpPiwik, $settings) {
10
+ self::$settings = $settings;
11
+ self::$wpPiwik = $wpPiwik;
 
12
  }
13
 
14
  public function output($array, $key, $default = '') {
27
  $end = time() + $diff;
28
  $start = time() - 2592000 + $diff;
29
  return date('Y-m-d', $start).','.date('Y-m-d', $end);
 
30
  }
 
31
  }
classes/WP_Piwik/Template/MetaBoxCustomVars.php ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Template;
4
+
5
+ class MetaBoxCustomVars extends \WP_Piwik\Template {
6
+
7
+ public function addMetabox() {
8
+ add_meta_box(
9
+ 'wp-piwik_post_customvars',
10
+ __('Piwik Custom Variables', 'wp-piwik'),
11
+ array(&$this, 'showCustomvars'),
12
+ 'post',
13
+ 'side',
14
+ 'default'
15
+ );
16
+ }
17
+
18
+ public function showCustomvars($objPost, $objBox ) {
19
+ wp_nonce_field(basename( __FILE__ ), 'wp-piwik_post_customvars_nonce'); ?>
20
+ <table>
21
+ <tr><th></th><th><?php _e('Name', 'wp-piwik'); ?></th><th><?php _e('Value', 'wp-piwik'); ?></th></tr>
22
+ <?php for($i = 1; $i <= 5; $i++) { ?>
23
+ <tr>
24
+ <th><label for="wp-piwik_customvar1"><?php echo $i; ?>: </label></th>
25
+ <td><input class="widefat" type="text" name="wp-piwik_custom_cat<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_cat'.$i, true ) ); ?>" size="200" /></td>
26
+ <td><input class="widefat" type="text" name="wp-piwik_custom_val<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_val'.$i, true ) ); ?>" size="200" /></td>
27
+ </tr>
28
+ <?php } ?>
29
+ </table>
30
+ <p><?php _e('Set custom variables for a page view', 'wp-piwik'); ?>. (<a href="http://piwik.org/docs/custom-variables/"><?php _e('More information', 'wp-piwik'); ?></a>.)</p>
31
+ <?php
32
+ }
33
+
34
+ public function saveCustomVars($intID, $objPost) {
35
+ // Verify the nonce before proceeding.
36
+ if (!isset( $_POST['wp-piwik_post_customvars_nonce'] ) || !wp_verify_nonce( $_POST['wp-piwik_post_customvars_nonce'], basename( __FILE__ ) ) )
37
+ return $intID;
38
+ // Get post type object
39
+ $objPostType = get_post_type_object($objPost->post_type);
40
+ // Check if the current user has permission to edit the post.
41
+ if (!current_user_can($objPostType->cap->edit_post, $intID))
42
+ return $intID;
43
+ $aryNames = array('cat', 'val');
44
+ for ($i = 1; $i <= 5; $i++)
45
+ for ($j = 0; $j <= 1; $j++) {
46
+ // Get data
47
+ $strMetaVal = (isset($_POST['wp-piwik_custom_'.$aryNames[$j].$i])?htmlentities($_POST['wp-piwik_custom_'.$aryNames[$j].$i]):'');
48
+ // Create key
49
+ $strMetaKey = 'wp-piwik_custom_'.$aryNames[$j].$i;
50
+ // Get the meta value of the custom field key
51
+ $strCurVal = get_post_meta($intID, $strMetaKey, true);
52
+ // Add meta val:
53
+ if ($strMetaVal && '' == $strCurVal)
54
+ add_post_meta($intID, $strMetaKey, $strMetaVal, true);
55
+ // Update meta val:
56
+ elseif ($strMetaVal && $strMetaVal != $strCurVal)
57
+ update_post_meta($intID, $strMetaKey, $strMetaVal);
58
+ // Delete meta val:
59
+ elseif (''==$strMetaVal && $strCurVal)
60
+ delete_post_meta($intID, $strMetaKey, $strCurVal);
61
+ }
62
+ }
63
+ }
classes/WP_Piwik/TrackingCode.php ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ class TrackingCode {
6
+
7
+ private static $wpPiwik;
8
+ private $trackingCode;
9
+
10
+ public $is404 = false, $isSearch = false;
11
+
12
+ public function __construct($wpPiwik) {
13
+ self::$wpPiwik = $wpPiwik;
14
+ if (!self::$wpPiwik->getOption('site_id') || !self::$wpPiwik->getOption('tracking_code'))
15
+ self::$wpPiwik->addPiwikSite();
16
+ if (!self::$wpPiwik->isCurrentTrackingCode()) {
17
+ self::$wpPiwik->updateTrackingCode();
18
+ }
19
+ $this->trackingCode = self::$wpPiwik->getOption('tracking_code');
20
+ }
21
+
22
+ public function getTrackingCode() {
23
+ if ($this->is404) $this->apply404Changes();
24
+ if ($this->isSearch) $this->applySearchChanges();
25
+ if (is_single()) $this->addCustomValues();
26
+ return $this->trackingCode;
27
+ }
28
+
29
+ public static function prepareTrackingCode($code, $settings, $logger) {
30
+ $logger->log('Apply tracking code changes:');
31
+ $settings->setOption('last_tracking_code_update', time());
32
+
33
+ if ($settings->getGlobalOption('track_mode') == 'js')
34
+ $code = str_replace(array('piwik.js', 'piwik.php'), 'js/index.php', $code);
35
+ elseif ($settings->getGlobalOption('track_mode') == 'proxy') {
36
+ $code = str_replace('piwik.js', 'piwik.php', $code);
37
+ $url = str_replace(array('https://', 'http://'), '//', $settings->getGlobalOption('piwik_url'));
38
+ $proxy = str_replace(array('https://', 'http://'), '//', plugins_url('wp-piwik').'/proxy').'/';
39
+ $code = str_replace($url, $proxy, $code);
40
+ }
41
+
42
+ /*$strCode = str_replace('//";','/"',$strCode);*/
43
+
44
+ if ($settings->getGlobalOption('track_cdnurl') || $settings->getGlobalOption('track_cdnurlssl'))
45
+ $code = str_replace(array("var d=doc","g.src=u+"), array("var ucdn=(('https:' == document.location.protocol) ? 'https://".($settings->getGlobalOption('track_cdnurlssl')?$settings->getGlobalOption('track_cdnurlssl'):$settings->getGlobalOption('track_cdnurl'))."/' : 'http://".($settings->getGlobalOption('track_cdnurl')?$settings->getGlobalOption('track_cdnurl'):$settings->getGlobalOption('track_cdnurlssl'))."/');\nvar d=doc", "g.src=ucdn+"), $code);
46
+
47
+ if ($settings->getGlobalOption('track_datacfasync'))
48
+ $code = str_replace('<script type', '<script data-cfasync="false" type', $code);
49
+ if ($settings->getGlobalOption('add_download_extensions'))
50
+ $code = str_replace("_paq.push(['trackPageView']);", "_paq.push(['addDownloadExtensions', '".($settings->getGlobalOption('add_download_extensions'))."']);\n_paq.push(['trackPageView']);", $code);
51
+ if ($settings->getGlobalOption('limit_cookies'))
52
+ $code = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '".$settings->getGlobalOption('limit_cookies_visitor')."']);\n_paq.push(['setSessionCookieTimeout', '".$settings->getGlobalOption('limit_cookies_session')."']);\n_paq.push(['trackPageView']);", $code);
53
+ if ($settings->getGlobalOption('force_protocol') != 'disabled')
54
+ $code = str_replace('"//', '"'.$settings->getGlobalOption('force_protocol').'://', $code);
55
+
56
+ if ($settings->getGlobalOption('piwik_mode') == 'pro')
57
+ $code = str_replace('.piwik.pro', '.piwikpro.com', $code);
58
+
59
+ $noScript = array();
60
+ preg_match('/<noscript>(.*)<\/noscript>/', $code, $noScript);
61
+ if (isset($noScript[0])) {
62
+ if ($settings->getGlobalOption('track_nojavascript'))
63
+ $noScript[0] = str_replace('?idsite', '?rec=1&idsite', $noScript[0]);
64
+ $noScript = $noScript[0];
65
+ } else $noScript = '';
66
+ $script = preg_replace('/<noscript>(.*)<\/noscript>/', '', $code);
67
+ $script = preg_replace('/\s+(\r\n|\r|\n)/', '$1', $script);
68
+ $logger->log('Finished tracking code: '.$script);
69
+ $logger->log('Finished noscript code: '.$noScript);
70
+ return array('script' => $script, 'noscript' => $noScript);
71
+ }
72
+
73
+ private function apply404Changes() {
74
+ self::$wpPiwik->log('Apply 404 changes. Blog ID: '.get_current_blog_id().' Site ID: '.self::$wpPiwik->getOption('site_id'));
75
+ $this->trackingCode = str_replace(
76
+ "_paq.push(['trackPageView']);",
77
+ "_paq.push(['setDocumentTitle', '404/URL = '+String(document.location.pathname+document.location.search).replace(/\//g,'%2f') + '/From = ' + String(document.referrer).replace(/\//g,'%2f')]);\n_paq.push(['trackPageView']);",
78
+ $this->trackingCode
79
+ );
80
+ }
81
+
82
+ private function applySearchChanges() {
83
+ self::$wpPiwik->log('Apply search tracking changes. Blog ID: '.get_current_blog_id().' Site ID: '.self::$wpPiwik->getOption('site_id'));
84
+ $objSearch = new \WP_Query("s=" . get_search_query() . '&showposts=-1');
85
+ $intResultCount = $objSearch->post_count;
86
+ $this->trackingCode = str_replace(
87
+ "_paq.push(['trackPageView']);",
88
+ "_paq.push(['trackSiteSearch','".get_search_query()."', false, ".$intResultCount."]);\n_paq.push(['trackPageView']);",
89
+ $this->trackingCode
90
+ );
91
+ }
92
+
93
+ private function addCustomValues() {
94
+ $customVars = '';
95
+ for ($i = 1; $i <= 5; $i++) {
96
+ $postId = get_the_ID();
97
+ $metaKey = get_post_meta($postId, 'wp-piwik_custom_cat'.$i, true);
98
+ $metaVal = get_post_meta($postId, 'wp-piwik_custom_val'.$i, true);
99
+ if (!empty($metaKey) && !empty($metaVal))
100
+ $customVars .= "_paq.push(['setCustomVariable',".$i.", '".$metaKey."', '".$metaVal."', 'page']);\n";
101
+ }
102
+ if (!empty($customVars))
103
+ $this->trackingCode = str_replace(
104
+ "_paq.push(['trackPageView']);",
105
+ $customVars."_paq.push(['trackPageView']);",
106
+ $this->trackingCode
107
+ );
108
+ }
109
+ }
classes/WP_Piwik/Widget.php ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik;
4
+
5
+ abstract class Widget {
6
+
7
+ protected static $wpPiwik, $settings;
8
+
9
+ protected $isShortcode = false, $method = '', $title = '', $context = 'side', $priority = 'core', $parameter = array(), $apiID = array(), $pageId = 'dashboard', $name = 'Value', $limit = 10;
10
+
11
+ public function __construct($wpPiwik, $settings, $pageId = 'dashboard', $context = 'side', $priority = 'default', $params = array(), $isShortcode = false) {
12
+ self::$wpPiwik = $wpPiwik;
13
+ self::$settings = $settings;
14
+ $this->pageId = $pageId;
15
+ $this->context = $context;
16
+ $this->priority = $priority;
17
+ $this->isShortcode = $isShortcode;
18
+ $prefix = ($this->pageId=='dashboard'?self::$settings->getGlobalOption('plugin_display_name').' - ':'');
19
+ $this->configure($prefix, $params);
20
+ if (is_array($this->method))
21
+ foreach ($this->method as $method) {
22
+ $this->apiID[$method] = \WP_Piwik\Request::register($method, $this->parameter);
23
+ self::$wpPiwik->log("Register request: ".$this->apiID[$method]);
24
+ }
25
+ else {
26
+ $this->apiID[$this->method] = \WP_Piwik\Request::register($this->method, $this->parameter);
27
+ self::$wpPiwik->log("Register request: ".$this->apiID[$this->method]);
28
+ }
29
+ if ($this->isShortcode)
30
+ return;
31
+ add_meta_box(
32
+ $this->getName(),
33
+ $this->title,
34
+ array($this, 'show'),
35
+ $pageId,
36
+ $this->context,
37
+ $this->priority
38
+ );
39
+ }
40
+
41
+ protected function configure($prefix = '', $params = array()) {}
42
+
43
+ public function show() {
44
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
45
+ if (!empty($response['result']) && $response['result'] ='error')
46
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
47
+ else {
48
+ if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
49
+ else $unique = 'sum_daily_nb_uniq_visitors';
50
+ $tableHead = array('label' => __($this->name, 'wp-piwik'));
51
+ $tableHead[$unique] = __('Unique', 'wp-piwik');
52
+ if (isset($response[0]['nb_visits']))
53
+ $tableHead['nb_visits'] = __('Visits', 'wp-piwik');
54
+ if (isset($response[0]['nb_hits']))
55
+ $tableHead['nb_hits'] = __('Hits', 'wp-piwik');
56
+ if (isset($response[0]['nb_actions']))
57
+ $tableHead['nb_actions'] = __('Actions', 'wp-piwik');
58
+ $tableBody = array();
59
+ $count = 0;
60
+ foreach ($response as $rowKey => $row) {
61
+ $count++;
62
+ $tableBody[$rowKey] = array();
63
+ foreach ($tableHead as $key => $value)
64
+ $tableBody[$rowKey][] = isset($row[$key])?$row[$key]:'-';
65
+ if ($count == 10) break;
66
+ }
67
+ $this->table($tableHead, $tableBody, null);
68
+ }
69
+ }
70
+
71
+ protected function timeFormat($time) {
72
+ return floor($time/3600).'h '.floor(($time % 3600)/60).'m '.floor(($time % 3600)%60).'s';
73
+ }
74
+
75
+ protected function table($thead, $tbody = array(), $tfoot = array()) {
76
+ echo '<div class="table"><table class="widefat wp-piwik-table">';
77
+ if ($this->isShortcode && $this->title)
78
+ echo '<tr><th colspan="10">'.$this->title.'</th></tr>';
79
+ if (!empty($thead)) $this->tabHead($thead);
80
+ if (!empty($tbody)) $this->tabBody($tbody);
81
+ if (!empty($tfoot)) $this->tabFoot($tfoot);
82
+ echo '</table></div>';
83
+ }
84
+
85
+ private function tabHead($thead) {
86
+ echo '<thead><tr>';
87
+ $count = 0;
88
+ foreach ($thead as $value)
89
+ echo '<th'.($count++?' style="text-align:right"':'').'>'.$value.'</th>';
90
+ echo '</tr></thead>';
91
+ }
92
+
93
+ private function tabBody($tbody) {
94
+ echo '<tbody>';
95
+ foreach ($tbody as $trow)
96
+ $this->tabRow($trow);
97
+ echo '</tbody>';
98
+ }
99
+
100
+ private function tabFoot($tfoot) {
101
+ echo '<tfoot><tr>';
102
+ $count = 0;
103
+ foreach ($tfoot as $value)
104
+ echo '<td'.($count++?' style="text-align:right"':'').'>'.$value.'</td>';
105
+ echo '</tr></tfoot>';
106
+ }
107
+
108
+ private function tabRow($trow) {
109
+ echo '<tr>';
110
+ $count = 0;
111
+ foreach ($trow as $tcell)
112
+ echo '<td'.($count++?' style="text-align:right"':'').'>'.$tcell.'</td>';
113
+ echo '</tr>';
114
+ }
115
+
116
+ protected function getTimeSettings() {
117
+ switch (self::$settings->getGlobalOption('default_date')) {
118
+ case 'today':
119
+ $period = 'day';
120
+ $date = 'today';
121
+ $description = 'today';
122
+ break;
123
+ case 'current_month':
124
+ $period = 'month';
125
+ $date = 'today';
126
+ $description = 'current month';
127
+ break;
128
+ case 'last_month':
129
+ $period = 'month';
130
+ $date = date("Y-m-d", strtotime("last day of previous month"));
131
+ $description = 'last month';
132
+ break;
133
+ case 'current_week':
134
+ $period = 'week';
135
+ $date = 'today';
136
+ $description = 'current week';
137
+ break;
138
+ case 'last_week':
139
+ $period = 'week';
140
+ $date = date("Y-m-d", strtotime("-1 week"));
141
+ $description = 'last week';
142
+ break;
143
+ case 'yesterday':
144
+ $period = 'day';
145
+ $date = 'yesterday';
146
+ $description = 'yesterday';
147
+ break;
148
+ default:
149
+ break;
150
+ }
151
+ return array('period' => $period, 'date' => $date, 'description' => $description);
152
+ }
153
+
154
+ public function getName() {
155
+ return str_replace('\\', '-', get_called_class());;
156
+ }
157
+
158
+ public function pieChart($data) {
159
+ echo '<div id="wp-piwik_stats_'.$this->getName().'_graph" style="height:310px;width:100%"></div>';
160
+ echo '<script type="text/javascript">$plotBrowsers = $j.jqplot("wp-piwik_stats_'.$this->getName().'_graph", [[';
161
+ $list = '';
162
+ foreach ($data as $dataSet)
163
+ $list .= '["'.$dataSet[0].'", '.$dataSet[1].'],';
164
+ echo substr($list, 0, -1);
165
+ echo ']], {seriesDefaults:{renderer:$j.jqplot.PieRenderer, rendererOptions:{sliceMargin:8}},legend:{show:true}});</script>';
166
+ }
167
+
168
+ protected function value($array, $key) {
169
+ return (isset($array[$key])?$array[$key]:'-');
170
+ }
171
+
172
+ }
classes/WP_Piwik/Widget/BrowserDetails.php ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class BrowserDetails extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Browser Details', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'UserSettings.getBrowserVersion';
18
+ $this->context = 'normal';
19
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
20
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
22
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
23
+ }
24
+
25
+ public function addHeaderLines() {
26
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.self::$wpPiwik->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
27
+ echo '<link rel="stylesheet" href="'.self::$wpPiwik->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
28
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
29
+ }
30
+
31
+ public function show() {
32
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
33
+ if (!empty($response['result']) && $response['result'] ='error')
34
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
35
+ else {
36
+ $tableHead = array(__('Browser', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
37
+ if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
38
+ else $unique = 'sum_daily_nb_uniq_visitors';
39
+ $count = 0;
40
+ $sum = 0;
41
+ foreach ($response as $row) {
42
+ $count++;
43
+ $sum += isset($row[$unique])?$row[$unique]:0;
44
+ if ($count < $this->limit)
45
+ $tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
46
+ elseif (!isset($tableBody['Others']))
47
+ $tableBody['Others'] = array($row['label'], $row[$unique], 0);
48
+ else
49
+ $tableBody['Others'][1] += $row[$unique];
50
+ }
51
+ if ($count > $this->limit)
52
+ $tableBody['Others'][0] = __('Others', 'wp-piwik');
53
+
54
+ foreach ($tableBody as $key => $row)
55
+ $tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
56
+
57
+ $this->pieChart($tableBody);
58
+ $this->table($tableHead, $tableBody, null);
59
+ }
60
+ }
61
+
62
+ }
classes/WP_Piwik/Widget/Browsers.php ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Browsers extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Browsers', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'UserSettings.getBrowser';
18
+ $this->context = 'normal';
19
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
20
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
22
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
23
+ }
24
+
25
+ public function addHeaderLines() {
26
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.self::$wpPiwik->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
27
+ echo '<link rel="stylesheet" href="'.self::$wpPiwik->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
28
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
29
+ }
30
+
31
+ public function show() {
32
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
33
+ if (!empty($response['result']) && $response['result'] ='error')
34
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
35
+ else {
36
+ $tableHead = array(__('Browser', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
37
+ if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
38
+ else $unique = 'sum_daily_nb_uniq_visitors';
39
+ $count = 0;
40
+ $sum = 0;
41
+ foreach ($response as $row) {
42
+ $count++;
43
+ $sum += isset($row[$unique])?$row[$unique]:0;
44
+ if ($count < $this->limit)
45
+ $tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
46
+ elseif (!isset($tableBody['Others']))
47
+ $tableBody['Others'] = array($row['label'], $row[$unique], 0);
48
+ else
49
+ $tableBody['Others'][1] += $row[$unique];
50
+ }
51
+ if ($count > $this->limit)
52
+ $tableBody['Others'][0] = __('Others', 'wp-piwik');
53
+
54
+ foreach ($tableBody as $key => $row)
55
+ $tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
56
+
57
+ $this->pieChart($tableBody);
58
+ $this->table($tableHead, $tableBody, null);
59
+ }
60
+ }
61
+
62
+ }
classes/WP_Piwik/Widget/Chart.php ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Chart extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $this->parameter = array(
11
+ 'idSite' => self::$settings->getOption('site_id'),
12
+ 'period' => 'day',
13
+ 'date' => 'last30',
14
+ 'limit' => null
15
+ );
16
+ $this->title = $prefix.__('Visitor Graph', 'wp-piwik').' ('.__($this->parameter['date'],'wp-piwik').')';
17
+ $this->method = array('VisitsSummary.getVisits', 'VisitsSummary.getUniqueVisitors', 'VisitsSummary.getBounceCount', 'VisitsSummary.getActions');
18
+ $this->context = 'normal';
19
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
20
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
22
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
23
+ }
24
+
25
+ public function addHeaderLines() {
26
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.self::$wpPiwik->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
27
+ echo '<link rel="stylesheet" href="'.self::$wpPiwik->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
28
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
29
+ }
30
+
31
+ public function show() {
32
+ $response = array();
33
+ $success = true;
34
+ foreach ($this->method as $method) {
35
+ $response[$method] = self::$wpPiwik->request($this->apiID[$method]);
36
+ if (!empty($response[$method]['result']) && $response[$method]['result'] ='error')
37
+ $success = false;
38
+ }
39
+ if (!$success)
40
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response[$method]['message'], ENT_QUOTES, 'utf-8');
41
+ else {
42
+ $values = $labels = $bounced = $unique = '';
43
+ $count = $uniqueSum = 0;
44
+ if (is_array($response['VisitsSummary.getVisits']))
45
+ foreach ($response['VisitsSummary.getVisits'] as $date => $value) {
46
+ $count++;
47
+ $values .= $value.',';
48
+ $unique .= $response['VisitsSummary.getUniqueVisitors'][$date].',';
49
+ $bounced .= $response['VisitsSummary.getBounceCount'][$date].',';
50
+ $labels .= '['.$count.',"'.substr($date,-2).'"],';
51
+ $uniqueSum += $response['VisitsSummary.getActions'][$date];
52
+ }
53
+ else {
54
+ $values = '0,';
55
+ $labels = '[0,"-"],';
56
+ $unique = '0,';
57
+ $bounced = '0,';
58
+ }
59
+ $average = round($uniqueSum/30,0);
60
+ $values = substr($values, 0, -1);
61
+ $unique = substr($unique, 0, -1);
62
+ $labels = substr($labels, 0, -1);
63
+ $bounced = substr($bounced, 0, -1);
64
+ echo '<div id="wp-piwik_stats_vistors_graph" style="height:220px;"></div>';
65
+ echo '<script type="text/javascript">';
66
+ echo '$j.jqplot("wp-piwik_stats_vistors_graph", [['.$values.'],['.$unique.'],['.$bounced.']],{axes:{yaxis:{min:0, tickOptions:{formatString:"%.0f"}},xaxis:{min:1,max:30,ticks:['.$labels.']}},seriesDefaults:{showMarker:false,lineWidth:1,fill:true,fillAndStroke:true,fillAlpha:0.9,trendline:{show:false,color:"#C00",lineWidth:1.5,type:"exp"}},series:[{color:"#90AAD9",fillColor:"#D4E2ED"},{color:"#A3BCEA",fillColor:"#E4F2FD",trendline:{show:true,label:"Unique visitor trend"}},{color:"#E9A0BA",fillColor:"#FDE4F2"}],});';
67
+ echo '</script>';
68
+ }
69
+ }
70
+
71
+ }
classes/WP_Piwik/Widget/Keywords.php ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Keywords extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Keywords', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'Referrers.getKeywords';
18
+ $this->name = 'Keyword';
19
+ }
20
+
21
+ }
classes/WP_Piwik/Widget/Noresult.php ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Noresult extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Site Search', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'Actions.getSiteSearchNoResultKeywords';
18
+ }
19
+
20
+ public function show() {
21
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
22
+ if (!empty($response['result']) && $response['result'] ='error')
23
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
24
+ else {
25
+ $tableHead = array(__('Keyword', 'wp-piwik'), __('Requests', 'wp-piwik'), __('Bounced', 'wp-piwik'));
26
+ $tableBody = array();
27
+ $count = 0;
28
+ foreach ($response as $row) {
29
+ $count++;
30
+ $tableBody[] = array($row['label'], $row['nb_visits'], $row['bounce_rate']);
31
+ if ($count == 10) break;
32
+ }
33
+ $this->table($tableHead, $tableBody, null);
34
+ }
35
+ }
36
+
37
+ }
classes/WP_Piwik/Widget/OptOut.php ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class OptOut extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $this->parameter = $params;
11
+ }
12
+
13
+ public function show() {
14
+ echo '<iframe frameborder="no" width="'.(isset($this->parameter['width'])?$this->parameter['width']:'').'" height="'.(isset($this->parameter['height'])?$this->parameter['height']:'').'" src="'.self::$settings->getGlobalOption('piwik_url').'index.php?module=CoreAdminHome&action=optOut&language='.(isset($this->parameter['language'])?$this->parameter['language']:'en').'"></iframe>';
15
+ }
16
+
17
+ }
classes/WP_Piwik/Widget/Overview.php ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Overview extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => isset($params['period'])?$params['period']:$timeSettings['period'],
14
+ 'date' => isset($params['date'])?$params['date']: $timeSettings['date'],
15
+ );
16
+ $this->title = !$this->isShortcode?$prefix.__('Overview', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')':($params['title']?$params['title']:'');
17
+ $this->method = 'VisitsSummary.get';
18
+ }
19
+
20
+ public function show() {
21
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
22
+ if (!empty($response['result']) && $response['result'] ='error')
23
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
24
+ else {
25
+ $time = isset($response['sum_visit_length'])?$this->timeFormat($response['sum_visit_length']):'-';
26
+ $avgTime = isset($response['avg_time_on_site'])?$this->timeFormat($response['avg_time_on_site']):'-';
27
+ $tableHead = null;
28
+ $tableBody = array(
29
+ array(__('Visitors', 'wp-piwik').':', $this->value($response, 'nb_visits')),
30
+ array(__('Unique visitors', 'wp-piwik').':', $this->value($response, 'nb_uniq_visitors')),
31
+ array(__('Page views', 'wp-piwik').':', $this->value($response, 'nb_actions').' (&#216; '.$this->value($response, 'nb_actions_per_visit').')'),
32
+ array(__('Max. page views in one visit', 'wp-piwik').':', $this->value($response, 'max_actions')),
33
+ array(__('Total time spent', 'wp-piwik').':', $time),
34
+ array(__('Time/visit', 'wp-piwik').':', $avgTime),
35
+ array(__('Bounce count', 'wp-piwik').':', $this->value($response, 'bounce_count').' ('.$this->value($response, 'bounce_rate').')')
36
+ );
37
+ $tableFoot = (self::$settings->getGlobalOption('piwik_shortcut')?array(__('Shortcut', 'wp-piwik').':', '<a href="'.self::$settings->getGlobalOption('piwik_url').'">Piwik</a>'.(isset($aryConf['inline']) && $aryConf['inline']?' - <a href="?page=wp-piwik_stats">WP-Piwik</a>':'')):null);
38
+ $this->table($tableHead, $tableBody, $tableFoot);
39
+ }
40
+ }
41
+
42
+ }
classes/WP_Piwik/Widget/Pages.php ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Pages extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Pages', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'Actions.getPageTitles';
18
+ $this->name = 'Page';
19
+ }
20
+
21
+ }
classes/WP_Piwik/Widget/Plugins.php ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Plugins extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Plugins', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'UserSettings.getPlugin';
18
+ }
19
+
20
+ public function show() {
21
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
22
+ if (!empty($response['result']) && $response['result'] ='error')
23
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
24
+ else {
25
+ $tableHead = array(__('Plugin', 'wp-piwik'), __('Visits', 'wp-piwik'), __('Percent', 'wp-piwik'));
26
+ $tableBody = array();
27
+ $count = 0;
28
+ foreach ($response as $row) {
29
+ $count++;
30
+ $tableBody[] = array($row['label'], $row['nb_visits'], $row['nb_visits_percentage']);
31
+ if ($count == 10) break;
32
+ }
33
+ $this->table($tableHead, $tableBody, null);
34
+ }
35
+ }
36
+
37
+ }
classes/WP_Piwik/Widget/Post.php ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Post extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ global $post;
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => 'range',
14
+ 'date' => isset($params['range'])?$params['range']:'last30',
15
+ 'key' => isset($params['key'])?$params['key']:null,
16
+ 'pageUrl' => isset($params['url'])?$params['url']:urlencode(get_permalink($post->ID)),
17
+ );
18
+ $this->title = $prefix.__('Overview', 'wp-piwik').' ('.__($this->parameter['date'],'wp-piwik').')';
19
+ $this->method = 'Actions.getPageUrl';
20
+ }
21
+
22
+ public function show() {
23
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
24
+ if (!empty($response['result']) && $response['result'] ='error')
25
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
26
+ else {
27
+ if (isset($response[0]))
28
+ $response = $response[0];
29
+ if ($this->parameter['key']) {
30
+ echo isset($response[$this->parameter['key']])?$response[$this->parameter['key']]:'<em>not defined</em>';
31
+ return;
32
+ }
33
+ $time = isset($response['entry_sum_visit_length'])?$this->timeFormat($response['entry_sum_visit_length']):'-';
34
+ $avgTime = isset($response['avg_time_on_page'])?$this->timeFormat($response['avg_time_on_page']):'-';
35
+ $tableHead = null;
36
+ $tableBody = array(
37
+ array(__('Visitors', 'wp-piwik').':', $this->value($response, 'nb_visits')),
38
+ array(__('Unique visitors', 'wp-piwik').':', $this->value($response, 'sum_daily_nb_uniq_visitors')),
39
+ array(__('Page views', 'wp-piwik').':', $this->value($response, 'nb_hits').' (&#216; '.$this->value($response, 'entry_nb_actions').')'),
40
+ array(__('Total time spent', 'wp-piwik').':', $time),
41
+ array(__('Time/visit', 'wp-piwik').':', $avgTime),
42
+ array(__('Bounce count', 'wp-piwik').':', $this->value($response, 'entry_bounce_count').' ('.$this->value($response, 'bounce_rate').')'),
43
+ array(__('Min. generation time', 'wp-piwik').':', $this->value($response, 'min_time_generation')),
44
+ array(__('Max. generation time', 'wp-piwik').':', $this->value($response, 'max_time_generation'))
45
+ );
46
+ $tableFoot = (self::$settings->getGlobalOption('piwik_shortcut')?array(__('Shortcut', 'wp-piwik').':', '<a href="'.self::$settings->getGlobalOption('piwik_url').'">Piwik</a>'.(isset($aryConf['inline']) && $aryConf['inline']?' - <a href="?page=wp-piwik_stats">WP-Piwik</a>':'')):null);
47
+ $this->table($tableHead, $tableBody, $tableFoot);
48
+ }
49
+ }
50
+
51
+ }
classes/WP_Piwik/Widget/Referrers.php ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Referrers extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Referrers', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'Referrers.getWebsites';
18
+ $this->name = 'Referrer';
19
+ }
20
+
21
+ }
classes/WP_Piwik/Widget/Screens.php ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Screens extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Resolutions', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'UserSettings.getResolution';
18
+ $this->context = 'normal';
19
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
20
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
22
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
23
+ }
24
+
25
+ public function addHeaderLines() {
26
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.self::$wpPiwik->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
27
+ echo '<link rel="stylesheet" href="'.self::$wpPiwik->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
28
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
29
+ }
30
+
31
+ public function show() {
32
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
33
+ if (!empty($response['result']) && $response['result'] ='error')
34
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
35
+ else {
36
+ $tableHead = array(__('Resolution', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
37
+ if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
38
+ else $unique = 'sum_daily_nb_uniq_visitors';
39
+ $count = 0;
40
+ $sum = 0;
41
+ foreach ($response as $row) {
42
+ $count++;
43
+ $sum += isset($row[$unique])?$row[$unique]:0;
44
+ if ($count < $this->limit)
45
+ $tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
46
+ elseif (!isset($tableBody['Others']))
47
+ $tableBody['Others'] = array($row['label'], $row[$unique], 0);
48
+ else
49
+ $tableBody['Others'][1] += $row[$unique];
50
+ }
51
+ if ($count > $this->limit)
52
+ $tableBody['Others'][0] = __('Others', 'wp-piwik');
53
+
54
+ foreach ($tableBody as $key => $row)
55
+ $tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
56
+
57
+ $this->pieChart($tableBody);
58
+ $this->table($tableHead, $tableBody, null);
59
+ }
60
+ }
61
+
62
+ }
classes/WP_Piwik/Widget/Search.php ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Search extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $timeSettings = $this->getTimeSettings();
11
+ $this->parameter = array(
12
+ 'idSite' => self::$settings->getOption('site_id'),
13
+ 'period' => $timeSettings['period'],
14
+ 'date' => $timeSettings['date']
15
+ );
16
+ $this->title = $prefix.__('Site Search', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
17
+ $this->method = 'Actions.getSiteSearchKeywords';
18
+ }
19
+
20
+ public function show() {
21
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
22
+ if (!empty($response['result']) && $response['result'] ='error')
23
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
24
+ else {
25
+ $tableHead = array(__('Keyword', 'wp-piwik'), __('Requests', 'wp-piwik'), __('Bounced', 'wp-piwik'));
26
+ $tableBody = array();
27
+ $count = 0;
28
+ foreach ($response as $row) {
29
+ $count++;
30
+ $tableBody[] = array($row['label'], $row['nb_visits'], $row['bounce_rate']);
31
+ if ($count == 10) break;
32
+ }
33
+ $this->table($tableHead, $tableBody, null);
34
+ }
35
+ }
36
+
37
+ }
classes/WP_Piwik/Widget/Seo.php ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Seo extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $this->parameter = array(
11
+ 'url' => get_bloginfo('url')
12
+ );
13
+ $this->title = $prefix.__('SEO', 'wp-piwik');
14
+ $this->method = 'SEO.getRank';
15
+ }
16
+
17
+ public function show() {
18
+ $response = null; //self::$wpPiwik->request($this->apiID[$this->method]);
19
+ if (!empty($response['result']) && $response['result'] ='error')
20
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
21
+ else {
22
+ echo '<div class="table"><table class="widefat"><tbody>';
23
+ if (is_array($response))
24
+ foreach ($response as $val)
25
+ echo '<tr><td>'.$val[0].'</td><td>'.$val[1].'</td></tr>';
26
+ else echo '<tr><td>SEO module currently not available.</td></tr>';
27
+ echo '</tbody></table></div>';
28
+ }
29
+ }
30
+
31
+ }
classes/WP_Piwik/Widget/Systems.php ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Systems extends \WP_Piwik\Widget {
6
+
7
+ protected function configure($prefix = '', $params = array()) {
8
+ $timeSettings = $this->getTimeSettings();
9
+ $this->parameter = array(
10
+ 'idSite' => self::$settings->getOption('site_id'),
11
+ 'period' => $timeSettings['period'],
12
+ 'date' => $timeSettings['date']
13
+ );
14
+ $this->title = $prefix.__('Operation Systems', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
15
+ $this->method = 'UserSettings.getOS';
16
+ $this->context = 'normal';
17
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
18
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
19
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
20
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
21
+ }
22
+
23
+ public function addHeaderLines() {
24
+ echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.self::$wpPiwik->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
25
+ echo '<link rel="stylesheet" href="'.self::$wpPiwik->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
26
+ echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
27
+ }
28
+
29
+ public function show() {
30
+ $response = self::$wpPiwik->request($this->apiID[$this->method]);
31
+ if (!empty($response['result']) && $response['result'] ='error')
32
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
33
+ else {
34
+ $tableHead = array(__('Operation System', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
35
+ if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
36
+ else $unique = 'sum_daily_nb_uniq_visitors';
37
+ $count = 0;
38
+ $sum = 0;
39
+ foreach ($response as $row) {
40
+ $count++;
41
+ $sum += isset($row[$unique])?$row[$unique]:0;
42
+ if ($count < $this->limit)
43
+ $tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
44
+ elseif (!isset($tableBody['Others']))
45
+ $tableBody['Others'] = array($row['label'], $row[$unique], 0);
46
+ else
47
+ $tableBody['Others'][1] += $row[$unique];
48
+ }
49
+ if ($count > $this->limit)
50
+ $tableBody['Others'][0] = __('Others', 'wp-piwik');
51
+
52
+ foreach ($tableBody as $key => $row)
53
+ $tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
54
+
55
+ $this->pieChart($tableBody);
56
+ $this->table($tableHead, $tableBody, null);
57
+ }
58
+ }
59
+
60
+ }
classes/WP_Piwik/Widget/Visitors.php ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace WP_Piwik\Widget;
4
+
5
+ class Visitors extends \WP_Piwik\Widget {
6
+
7
+ public $className = __CLASS__;
8
+
9
+ protected function configure($prefix = '', $params = array()) {
10
+ $this->parameter = array(
11
+ 'idSite' => self::$settings->getOption('site_id'),
12
+ 'period' => 'day',
13
+ 'date' => 'last30',
14
+ 'limit' => null
15
+ );
16
+ $this->title = $prefix.__('Visitors', 'wp-piwik').' ('.__($this->parameter['date'],'wp-piwik').')';
17
+ $this->method = array('VisitsSummary.getVisits', 'VisitsSummary.getUniqueVisitors', 'VisitsSummary.getBounceCount', 'VisitsSummary.getActions');
18
+ $this->context = 'normal';
19
+ wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
20
+ wp_enqueue_script('wp-piwik-jqplot',self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
21
+ wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
22
+ add_action('admin_head-index.php', array($this, 'addHeaderLines'));
23
+ }
24
+
25
+ public function show() {
26
+ $response = array();
27
+ $success = true;
28
+ foreach ($this->method as $method) {
29
+ $response[$method] = self::$wpPiwik->request($this->apiID[$method]);
30
+ if (!empty($response[$method]['result']) && $response[$method]['result'] ='error')
31
+ $success = false;
32
+ }
33
+ if (!$success)
34
+ echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response[$method]['message'], ENT_QUOTES, 'utf-8');
35
+ else {
36
+ $data = array();
37
+ foreach ($response['VisitsSummary.getVisits'] as $key => $value)
38
+ $data[] = array(
39
+ $key,
40
+ $value,
41
+ $response['VisitsSummary.getUniqueVisitors'][$key]?$response['VisitsSummary.getUniqueVisitors'][$key]:'-',
42
+ $response['VisitsSummary.getBounceCount'][$key]?$response['VisitsSummary.getBounceCount'][$key]:'-',
43
+ $response['VisitsSummary.getActions'][$key]?$response['VisitsSummary.getActions'][$key]:'-'
44
+ );
45
+ $this->table(
46
+ array(__('Date', 'wp-piwik'), __('Visits', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Bounced', 'wp-piwik'), __('Page Views', 'wp-piwik')),
47
+ array_reverse($data)
48
+ );
49
+ }
50
+
51
+ }
52
+
53
+ }
classes/WP_Piwik_Logger_Dummy.php DELETED
@@ -1,9 +0,0 @@
1
- <?php
2
-
3
- require_once('WP_Piwik_Logger.php');
4
-
5
- class WP_Piwik_Logger_Dummy extends WP_Piwik_Logger {
6
-
7
- public function loggerOutput($loggerTime, $loggerMessage) {}
8
-
9
- }
 
 
 
 
 
 
 
 
 
classes/WP_Piwik_MetaBox_PerPost_Stats.php DELETED
@@ -1,47 +0,0 @@
1
- <?php
2
-
3
- require_once('WP_Piwik_Template.php');
4
-
5
- class WP_Piwik_MetaBox_PerPost_Stats extends WP_Piwik_Template {
6
-
7
- function addMetabox() {
8
- add_meta_box(
9
- 'wp-piwik_post_perpoststats',
10
- __('Piwik Statistics (last 30 days)', 'wp-piwik'),
11
- array(&$this, 'showStats'),
12
- 'post',
13
- 'side',
14
- 'default'
15
- );
16
- }
17
-
18
- private function getStats($range = false) {
19
- global $post;
20
- $postURL = get_permalink($post->ID);
21
- $range = ($range?$range:$this->getRangeLast30());
22
- self::$logger->log('Load per post statistics: '.$postURL);
23
- return self::$wpPiwik->callPiwikAPI('Actions.getPageUrl', 'range', $range, null, false, false, 'PHP', $postURL, false);
24
- }
25
-
26
- function showStats() {
27
- $data = $this->getStats();
28
- if (!isset($data[0])) return;
29
- echo '<table>';
30
- $this->tabRow(__('Visitors', 'wp-piwik').':',$data[0]['nb_visits']);
31
- $this->tabRow(__('Unique visitors', 'wp-piwik').':', $data[0]['sum_daily_nb_uniq_visitors']);
32
- $this->tabRow(__('Page views', 'wp-piwik').':', $data[0]['nb_hits']);
33
- $this->tabRow(__('Time/visit', 'wp-piwik').':', $data[0]['avg_time_on_page']);
34
- $this->tabRow(__('Bounce count', 'wp-piwik').':', $this->output($data[0], 'entry_bounce_count', 0).' ('.$data[0]['bounce_rate'].')');
35
- $this->tabRow(__('Exit count', 'wp-piwik').':', $this->output($data[0], 'exit_nb_visits', 0).' ('.$data[0]['exit_rate'].')');
36
- if (isset($data[0]['avg_time_generation']))
37
- $this->tabRow(__('Avg. generation time', 'wp-piwik').':', $data[0]['avg_time_generation']);
38
- echo '</table>';
39
- }
40
-
41
- function getValue($range, $key) {
42
- $data = $this->getStats($range);
43
- if (!isset($data[0]) || !isset($data[0][$key])) return '-';
44
- else return $data[0][$key];
45
- }
46
-
47
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/WP_Piwik_Settings.php DELETED
@@ -1,163 +0,0 @@
1
- <?php
2
-
3
- class WP_Piwik_Settings {
4
-
5
- private static $logger, $defaultSettings;
6
-
7
- private $globalSettings = array(
8
- 'revision' => 90921,
9
- 'plugin_display_name' => 'WP-Piwik',
10
- 'add_tracking_code' => false,
11
- 'last_settings_update' => 0,
12
- 'piwik_token' => '',
13
- 'piwik_url' => '',
14
- 'piwik_path' => '',
15
- 'piwik_mode' => 'http',
16
- 'piwik_useragent' => 'php',
17
- 'piwik_useragent_string' => 'WP-Piwik',
18
- 'connection_timeout' => 5,
19
- 'dashboard_widget' => false,
20
- 'dashboard_chart' => false,
21
- 'dashboard_seo' => false,
22
- 'stats_seo' => false,
23
- 'capability_stealth' => array(),
24
- 'capability_read_stats' => array('administrator' => true),
25
- 'piwik_shortcut' => false,
26
- 'default_date' => 'yesterday',
27
- 'auto_site_config' => true,
28
- 'track_404' => false,
29
- 'track_search' => false,
30
- 'track_mode' => 0,
31
- 'track_post' => false,
32
- 'track_proxy' => false,
33
- 'track_admin' => false,
34
- 'track_feed' => false,
35
- 'track_feed_goal' => '',
36
- 'track_feed_revenue' => '',
37
- 'track_feed_campaign' => 'feed',
38
- 'track_feed_addcampaign' => 'false',
39
- 'track_cdnurlssl' => '',
40
- 'track_noscript' => false,
41
- 'track_nojavascript' => false,
42
- 'track_codeposition' => 'footer',
43
- 'track_datacfasync' => false,
44
- 'track_across' => false,
45
- 'track_across_alias' => false,
46
- 'limit_cookies' => false,
47
- 'limit_cookies_visitor' => 1209600,
48
- 'limit_cookies_session' => 0,
49
- 'add_post_annotations' => false,
50
- 'add_customvars_box' => true,
51
- 'disable_timelimit' => false,
52
- 'disable_ssl_verify' => false,
53
- 'disable_cookies' => false,
54
- 'toolbar' => false,
55
- 'shortcodes' => false,
56
- 'cache' => true,
57
- 'perpost_stats' => false
58
- ),
59
- $settings = array(
60
- 'name' => '',
61
- 'tracking_code' => '',
62
- 'site_id' => NULL,
63
- 'last_tracking_code_update' => 0,
64
- 'dashboard_revision' => 0,
65
- 'noscript_code' => ''
66
- ),
67
- $settingsChanged = false;
68
-
69
- public function __construct($objLogger) {
70
- self::$logger = $objLogger;
71
- self::$logger->log('Store default settings');
72
- self::$defaultSettings = array('globalSettings' => $this->globalSettings, 'settings' => $this->settings);
73
- self::$logger->log('Load settings');
74
- $this->globalSettings = ($this->checkNetworkActivation()?
75
- get_site_option('wp-piwik_global-settings', $this->globalSettings):
76
- get_option('wp-piwik_global-settings', $this->globalSettings)
77
- );
78
- $this->settings = get_option('wp-piwik_settings',$this->settings);
79
- }
80
-
81
- public function save() {
82
- if (!$this->settingsChanged) {
83
- self::$logger->log('No settings changed yet');
84
- return;
85
- }
86
- self::$logger->log('Save settings');
87
- if (is_plugin_active_for_network('wp-piwik/wp-piwik.php'))
88
- update_site_option('wp-piwik_global-settings', $this->globalSettings);
89
- else
90
- update_option('wp-piwik_global-settings', $this->globalSettings);
91
- update_option('wp-piwik_settings', $this->settings);
92
- global $wp_roles;
93
- if (!is_object($wp_roles))
94
- $wp_roles = new WP_Roles();
95
- if (!is_object($wp_roles)) die("STILL NO OBJECT");
96
- foreach($wp_roles->role_names as $strKey => $strName) {
97
- $objRole = get_role($strKey);
98
- foreach (array('stealth', 'read_stats') as $strCap) {
99
- $aryCaps = $this->getGlobalOption('capability_'.$strCap);
100
- if (isset($aryCaps[$strKey]) && $aryCaps[$strKey])
101
- $objRole->add_cap('wp-piwik_'.$strCap);
102
- else $objRole->remove_cap('wp-piwik_'.$strCap);
103
- }
104
- }
105
- $this->settingsChanges = false;
106
- }
107
-
108
- public function getGlobalOption($key) {
109
- return isset($this->globalSettings[$key])?$this->globalSettings[$key]:self::$defaultSettings['globalSettings'][$key];
110
- }
111
-
112
- public function getOption($key) {
113
- return isset($this->settings[$key])?$this->settings[$key]:self::$defaultSettings['settings'][$key];
114
- }
115
-
116
- public function setGlobalOption($key, $value) {
117
- $this->settingsChanged = true;
118
- self::$logger->log('Changed global option '.$key.': '.(is_array($value)?serialize($value):$value));
119
- $this->globalSettings[$key] = $value;
120
- }
121
-
122
- public function setOption($key, $value) {
123
- $this->settingsChanged = true;
124
- self::$logger->log('Changed option '.$key.': '.$value);
125
- $this->settings[$key] = $value;
126
- }
127
-
128
- public function resetSettings($bolFull = false) {
129
- self::$logger->log('Reset WP-Piwik settings');
130
- global $wpdb;
131
- $keepSettings = array(
132
- 'piwik_token' => $this->getGlobalOption('piwik_token'),
133
- 'piwik_url' => $this->getGlobalOption('piwik_url'),
134
- 'piwik_path' => $this->getGlobalOption('piwik_path'),
135
- 'piwik_mode' => $this->getGlobalOption('piwik_mode')
136
- );
137
- if (is_plugin_active_for_network('wp-piwik/wp-piwik.php')) {
138
- delete_site_option('wp-piwik_global-settings');
139
- $aryBlogs = $wpdb->get_results('SELECT blog_id FROM '.$wpdb->blogs.' ORDER BY blog_id');
140
- foreach ($aryBlogs as $aryBlog)
141
- delete_blog_option($aryBlog->blog_id, 'wp-piwik_settings');
142
- if (!$bolFull) update_site_option('wp-piwik_global-settings', $keepSettings);
143
- } else {
144
- delete_option('wp-piwik_global-settings');
145
- delete_option('wp-piwik_settings');
146
- }
147
- $this->globalSettings = self::$defaultSettings['globalSettings'];
148
- $this->settings = self::$defaultSettings['settings'];
149
- if (!$bolFull) {
150
- self::$logger->log('Restore connection settings');
151
- foreach ($keepSettings as $key => $value)
152
- $this->setGlobalOption($key, $value);
153
- }
154
- $this->save();
155
- }
156
-
157
- public function checkNetworkActivation() {
158
- if (!function_exists("is_plugin_active_for_network")) {
159
- require_once(ABSPATH.'wp-admin/includes/plugin.php');
160
- }
161
- return is_plugin_active_for_network('wp-piwik/wp-piwik.php');
162
- }
163
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.php CHANGED
@@ -6,4 +6,4 @@
6
  1: Log to screen
7
  2: Log to file (logs/YYYYMMDD_wp-piwik.log)
8
  */
9
- define('WP_PIWIK_ACTIVATE_LOGGER', 0);
6
  1: Log to screen
7
  2: Log to file (logs/YYYYMMDD_wp-piwik.log)
8
  */
9
+ define('WP_PIWIK_ACTIVATE_LOGGER', 0);
dashboard/.htaccess DELETED
@@ -1 +0,0 @@
1
- Deny from all
 
dashboard/browserdetails.php DELETED
@@ -1,68 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:BrowserDetails
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'UserSettings.getBrowserVersion',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Browser Details', 'wp-piwik');
13
- $strValues = '';
14
- $intCount = 0; $intMore = 0; $intSum = 0;
15
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] ='error')
16
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
17
- else {
18
- if (is_array($aryConf['data']))
19
- foreach ($aryConf['data'] as $key => $aryValues) {
20
- $intCount++;
21
- if ($intCount <= 9) $strValues .= '["'.$aryValues['label'].'",'.$aryValues['nb_uniq_visitors'].'],';
22
- else $intMore += $aryValues['nb_uniq_visitors'];
23
- $intSum += $aryValues['nb_uniq_visitors'];
24
- }
25
- if ($intMore) $strValues .= '["'.__('Others', 'wp-piwik').'",'.$intMore.'],';
26
- $strValues = substr($strValues, 0, -1);
27
- if ($intSum) {
28
- /***************************************************************************/ ?>
29
- <div class="wp-piwik-graph-wide">
30
- <div id="wp-piwik_stats_browserdetails_graph" style="height:310px;width:100%"></div>
31
- </div>
32
- <?php /************************************************************************/
33
- }
34
- /***************************************************************************/ ?>
35
- <div class="table">
36
- <table class="widefat wp-piwik-table">
37
- <thead>
38
- <tr>
39
- <th><?php _e('Browser', 'wp-piwik'); ?></th>
40
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
41
- <th class="n"><?php _e('Percent', 'wp-piwik'); ?></th>
42
- </tr>
43
- </thead>
44
- <tbody>
45
- <?php /************************************************************************/
46
- if ($intSum)
47
- foreach ($aryConf['data'] as $aryValues)
48
- echo '<tr><td>'.
49
- $aryValues['label'].
50
- '</td><td class="n">'.
51
- $aryValues['nb_uniq_visitors'].
52
- '</td><td class="n">'.
53
- number_format($aryValues['nb_uniq_visitors']/$intSum*100, 2).
54
- '%</td></tr>';
55
- else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
56
- unset($aryTmp);
57
- /***************************************************************************/ ?>
58
- </tbody>
59
- </table>
60
- </div>
61
- <script type="text/javascript">
62
- $plotBrowsers = $j.jqplot('wp-piwik_stats_browserdetails_graph', [[<?php echo $strValues; ?>]], {
63
- seriesDefaults:{renderer:$j.jqplot.PieRenderer, rendererOptions:{sliceMargin:8}},
64
- legend:{show:true}
65
- });
66
- </script>
67
- <?php
68
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/browsers.php DELETED
@@ -1,69 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Browser
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'UserSettings.getBrowser',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
-
13
- $aryConf['title'] = __('Browser', 'wp-piwik');
14
- $strValues = '';
15
- $intCount = 0; $intMore = 0; $intSum = 0;
16
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] ='error')
17
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
18
- else {
19
- if (is_array($aryConf['data']))
20
- foreach ($aryConf['data'] as $key => $aryValues) {
21
- $intCount++;
22
- if ($intCount <= 9) $strValues .= '["'.$aryValues['label'].'",'.$aryValues['nb_uniq_visitors'].'],';
23
- else $intMore += $aryValues['nb_uniq_visitors'];
24
- $intSum += $aryValues['nb_uniq_visitors'];
25
- }
26
- if ($intMore) $strValues .= '["'.__('Others', 'wp-piwik').'",'.$intMore.'],';
27
- $strValues = substr($strValues, 0, -1);
28
- if ($intSum) {
29
- /***************************************************************************/ ?>
30
- <div class="wp-piwik-graph-wide">
31
- <div id="wp-piwik_stats_browsers_graph" style="height:310px;width:100%"></div>
32
- </div>
33
- <?php /************************************************************************/
34
- }
35
- /***************************************************************************/ ?>
36
- <div class="table">
37
- <table class="widefat wp-piwik-table">
38
- <thead>
39
- <tr>
40
- <th><?php _e('Browser', 'wp-piwik'); ?></th>
41
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
42
- <th class="n"><?php _e('Percent', 'wp-piwik'); ?></th>
43
- </tr>
44
- </thead>
45
- <tbody>
46
- <?php /************************************************************************/
47
- if ($intSum)
48
- foreach ($aryConf['data'] as $aryValues)
49
- echo '<tr><td>'.
50
- $aryValues['label'].
51
- '</td><td class="n">'.
52
- $aryValues['nb_uniq_visitors'].
53
- '</td><td class="n">'.
54
- number_format($aryValues['nb_uniq_visitors']/$intSum*100, 2).
55
- '%</td></tr>';
56
- else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
57
- unset($aryTmp);
58
- /***************************************************************************/ ?>
59
- </tbody>
60
- </table>
61
- </div>
62
- <script type="text/javascript">
63
- $plotBrowsers = $j.jqplot('wp-piwik_stats_browsers_graph', [[<?php echo $strValues; ?>]], {
64
- seriesDefaults:{renderer:$j.jqplot.PieRenderer, rendererOptions:{sliceMargin:8}},
65
- legend:{show:true}
66
- });
67
- </script>
68
- <?php
69
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/index.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- // Nothing to see...
 
 
dashboard/keywords.php DELETED
@@ -1,30 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Keywords
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'Referers.getKeywords',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Keywords', 'wp-piwik');
13
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
14
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
15
- else {
16
- /***************************************************************************/ ?>
17
- <table class="widefat">
18
- <thead>
19
- <tr><th><?php _e('Keyword', 'wp-piwik'); ?></th><th><?php _e('Unique', 'wp-piwik'); ?></th></tr>
20
- </thead>
21
- <tbody>
22
- <?php /************************************************************************/
23
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues)
24
- echo '<tr><td>'.$aryValues['label'].'</td><td>'.$aryValues['nb_uniq_visitors'].'</td></tr>';
25
- else echo '<tr><td colspan="2">'.__('No data available.', 'wp-piwik').'</td></tr>';
26
- /***************************************************************************/ ?>
27
- </tbody>
28
- </table>
29
- <?php /************************************************************************/
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/noresult.php DELETED
@@ -1,30 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:SiteSearchNoResults
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'Actions.getSiteSearchNoResultKeywords',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Site Search without Results', 'wp-piwik');
13
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
14
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
15
- else {
16
- /***************************************************************************/ ?>
17
- <table class="widefat">
18
- <thead>
19
- <tr><th><?php _e('Keyword', 'wp-piwik'); ?></th><th><?php _e('Requests', 'wp-piwik'); ?></th><th><?php _e('Bounced', 'wp-piwik'); ?></th></tr>
20
- </thead>
21
- <tbody>
22
- <?php /************************************************************************/
23
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues)
24
- echo '<tr><td>'.$aryValues['label'].'</td><td>'.$aryValues['nb_visits'].'</td><td>'.$aryValues['bounce_rate'].'</td></tr>';
25
- else echo '<tr><td colspan="2">'.__('No data available.', 'wp-piwik').'</td></tr>';
26
- /***************************************************************************/ ?>
27
- </tbody>
28
- </table>
29
- <?php /************************************************************************/
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/overview.php DELETED
@@ -1,70 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Overview
4
- **********************************/
5
- $aryTmp = array(
6
- 'bounce_count' => 0,
7
- 'max_actions' => 0,
8
- 'nb_actions' => 0,
9
- 'nb_uniq_visitors' => 0,
10
- 'nb_visits' => 0,
11
- 'nb_visits_converted' => 0,
12
- 'sum_visit_length' => 0,
13
- 'bounce_rate' => 0,
14
- 'nb_actions_per_visit' => 0,
15
- 'avg_time_on_site' => 0
16
- );
17
- $aryConf['data'] = $this->callPiwikAPI(
18
- 'VisitsSummary.get',
19
- $aryConf['params']['period'],
20
- $aryConf['params']['date'],
21
- $aryConf['params']['limit']
22
- );
23
- $aryConf['title'] = __('Overview', 'wp-piwik');
24
-
25
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] ='error')
26
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
27
- else {
28
- if ($aryConf['params']['date'] == 'last30') {
29
- $intValCnt = 0;
30
- if (is_array($aryConf['data']))
31
- foreach ($aryConf['data'] as $aryDay)
32
- foreach ($aryDay as $strKey => $strValue) {
33
- $intValCnt++;
34
- if (!in_array($strKey, array('max_actions','bounce_rate','nb_actions_per_visit','avg_time_on_site')))
35
- if (isset($aryTmp[$strKey])) $aryTmp[$strKey] += $strValue;
36
- elseif ($aryTmp[$strKey] < $strValue)
37
- $aryTmp[$strKey] = $strValue;
38
- }
39
- $aryConf['data'] = $aryTmp;
40
- if ($intValCnt > 1 && $aryConf['data']['nb_visits'] >0) $aryConf['data']['bounce_rate'] = round($aryConf['data']['bounce_count']/$aryConf['data']['nb_visits']*100).'%';
41
- }
42
- if (empty($aryConf['data'])) $aryConf['data'] = $aryTmp;
43
- /***************************************************************************/ ?>
44
- <div class="table">
45
- <table class="widefat">
46
- <tbody>
47
- <?php /************************************************************************/
48
- $strTime =
49
- floor($aryConf['data']['sum_visit_length']/3600).'h '.
50
- floor(($aryConf['data']['sum_visit_length'] % 3600)/60).'m '.
51
- floor(($aryConf['data']['sum_visit_length'] % 3600) % 60).'s';
52
- $strAvgTime =
53
- floor($aryConf['data']['avg_time_on_site']/3600).'h '.
54
- floor(($aryConf['data']['avg_time_on_site'] % 3600)/60).'m '.
55
- floor(($aryConf['data']['avg_time_on_site'] % 3600) % 60).'s';
56
- echo '<tr><td>'.__('Visitors', 'wp-piwik').':</td><td>'.$aryConf['data']['nb_visits'].'</td></tr>';
57
- echo '<tr><td>'.__('Unique visitors', 'wp-piwik').':</td><td>'.$aryConf['data']['nb_uniq_visitors'].'</td></tr>';
58
- echo '<tr><td>'.__('Page views', 'wp-piwik').':</td><td>'.$aryConf['data']['nb_actions'].' (&#216; '.$aryConf['data']['nb_actions_per_visit'].')</td></tr>';
59
- echo '<tr><td>'.__('Max. page views in one visit', 'wp-piwik').':</td><td>'.$aryConf['data']['max_actions'].'</td></tr>';
60
- echo '<tr><td>'.__('Total time spent', 'wp-piwik').':</td><td>'.$strTime.'</td></tr>';
61
- echo '<tr><td>'.__('Time/visit', 'wp-piwik').':</td><td>'.$strAvgTime.'</td></tr>';
62
- echo '<tr><td>'.__('Bounce count', 'wp-piwik').':</td><td>'.$aryConf['data']['bounce_count'].' ('.$aryConf['data']['bounce_rate'].')</td></tr>';
63
- if (self::$settings->getGlobalOption('piwik_shortcut'))
64
- echo '<tr><td>'.__('Shortcut', 'wp-piwik').':</td><td><a href="'.self::$settings->getGlobalOption('piwik_url').'">Piwik</a>'.(isset($aryConf['inline']) && $aryConf['inline']?' - <a href="?page=wp-piwik_stats">WP-Piwik</a>':'').'</td></tr>';
65
- /***************************************************************************/ ?>
66
- </tbody>
67
- </table>
68
- </div>
69
- <?php /************************************************************************/
70
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/pages.php DELETED
@@ -1,57 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Pages
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'Actions.getPageTitles',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $intMax = 9;
13
- $aryConf['title'] = __('Pages', 'wp-piwik');
14
-
15
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
16
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
17
- else {
18
- /***************************************************************************/ ?>
19
- <div class="table">
20
- <table class="widefat wp-piwik-table">
21
- <thead>
22
- <tr>
23
- <th><?php _e('Page', 'wp-piwik'); ?></th>
24
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
25
- <th class="n"><?php _e('Visits', 'wp-piwik'); ?></th>
26
- </tr>
27
- </thead>
28
- <tbody>
29
- <?php /************************************************************************/
30
- $intCount = 0; $aryOthers = array('u' => 0, 'v' => 0);
31
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues) {
32
- $intCount++;
33
- if ($intCount > $intMax) {
34
- $aryOthers['u'] += (isset($aryValues['nb_uniq_visitors'])?$aryValues['nb_uniq_visitors']:0);
35
- $aryOthers['v'] += (isset($aryValues['nb_visits'])?$aryValues['nb_visits']:0);
36
- } else echo '<tr><td>'.
37
- $aryValues['label'].
38
- '</td><td class="n">'.
39
- $aryValues['nb_uniq_visitors'].
40
- '</td><td class="n">'.
41
- $aryValues['nb_visits'].
42
- '</td></tr>';
43
- } else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
44
- if (!empty($aryOthers['v'])) echo '<tr><td>'.
45
- __('Others', 'wp-piwik').
46
- '</td><td class="n">'.
47
- $aryOthers['u'].
48
- '</td><td class="n">'.
49
- $aryOthers['v'].
50
- '</td></tr>';
51
-
52
- /***************************************************************************/ ?>
53
- </tbody>
54
- </table>
55
- </div>
56
- <?php /************************************************************************/
57
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/plugins.php DELETED
@@ -1,58 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Plugins
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'UserSettings.getPlugin',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Plugins', 'wp-piwik');
13
-
14
- $aryOverview = $this->callPiwikAPI(
15
- 'VisitsSummary.get',
16
- $aryConf['params']['period'],
17
- $aryConf['params']['date'],
18
- $aryConf['params']['limit']
19
- );
20
-
21
- $intTotalVisits = (isset($aryOverview['nb_visits'])?$aryOverview['nb_visits']:0);
22
-
23
- unset($aryOverview);
24
-
25
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
26
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
27
- else {
28
- /***************************************************************************/ ?>
29
- <div class="table">
30
- <table class="widefat wp-piwik-table">
31
- <thead>
32
- <tr>
33
- <th><?php _e('Plugins', 'wp-piwik'); ?></th>
34
- <th class="n"><?php _e('Visits', 'wp-piwik'); ?></th>
35
- <th class="n"><?php _e('Percent', 'wp-piwik'); ?></th>
36
- </tr>
37
- </thead>
38
- <tbody>
39
- <?php /************************************************************************/
40
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues)
41
- echo '<tr><td>'.
42
- $aryValues['label'].
43
- '</td><td class="n">'.
44
- $aryValues['nb_visits'].
45
- '</td><td class="n">'.
46
- ($intTotalVisits != 0?
47
- number_format(($aryValues['nb_visits']/$intTotalVisits*100),2):
48
- '0.00%'
49
- ).
50
- '%</td></tr>';
51
- else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
52
- unset($aryTmp);
53
- /***************************************************************************/ ?>
54
- </tbody>
55
- </table>
56
- </div>
57
- <?php /************************************************************************/
58
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/screens.php DELETED
@@ -1,68 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Screens
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'UserSettings.getResolution',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Resolution', 'wp-piwik');
13
- $strValues = '';
14
- $intCount = 0; $intMore = 0; $intSum = 0;
15
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] ='error')
16
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
17
- else {
18
- if (is_array($aryConf['data']))
19
- foreach ($aryConf['data'] as $key => $aryValues) {
20
- $intCount++;
21
- if ($intCount <= 9) $strValues .= '["'.$aryValues['label'].'",'.$aryValues['nb_uniq_visitors'].'],';
22
- else $intMore += $aryValues['nb_uniq_visitors'];
23
- $intSum += $aryValues['nb_uniq_visitors'];
24
- }
25
- if ($intMore) $strValues .= '["'.__('Others', 'wp-piwik').'",'.$intMore.'],';
26
- $strValues = substr($strValues, 0, -1);
27
- if ($intSum) {
28
- /***************************************************************************/ ?>
29
- <div class="wp-piwik-graph-wide">
30
- <div id="wp-piwik_stats_screens_graph" style="height:310px;width:100%"></div>
31
- </div>
32
- <?php /************************************************************************/
33
- }
34
- /***************************************************************************/ ?>
35
- <div class="table">
36
- <table class="widefat wp-piwik-table">
37
- <thead>
38
- <tr>
39
- <th><?php _e('Resolution', 'wp-piwik'); ?></th>
40
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
41
- <th class="n"><?php _e('Percent', 'wp-piwik'); ?></th>
42
- </tr>
43
- </thead>
44
- <tbody>
45
- <?php /************************************************************************/
46
- if ($intSum)
47
- foreach ($aryConf['data'] as $aryValues)
48
- echo '<tr><td>'.
49
- $aryValues['label'].
50
- '</td><td class="n">'.
51
- $aryValues['nb_uniq_visitors'].
52
- '</td><td class="n">'.
53
- number_format($aryValues['nb_uniq_visitors']/$intSum*100, 2).
54
- '%</td></tr>';
55
- else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
56
- unset($aryTmp);
57
- /***************************************************************************/ ?>
58
- </tbody>
59
- </table>
60
- </div>
61
- <script type="text/javascript">
62
- $plotScreens = $j.jqplot('wp-piwik_stats_screens_graph', [[<?php echo $strValues; ?>]], {
63
- seriesDefaults:{renderer:$j.jqplot.PieRenderer, rendererOptions:{sliceMargin:8}},
64
- legend:{show:true}
65
- });
66
- </script>
67
- <?php
68
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/search.php DELETED
@@ -1,30 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:SiteSearch
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'Actions.getSiteSearchKeywords',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Site Search Keywords', 'wp-piwik');
13
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
14
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
15
- else {
16
- /***************************************************************************/ ?>
17
- <table class="widefat">
18
- <thead>
19
- <tr><th><?php _e('Keyword', 'wp-piwik'); ?></th><th><?php _e('Requests', 'wp-piwik'); ?></th><th><?php _e('Bounced', 'wp-piwik'); ?></th></tr>
20
- </thead>
21
- <tbody>
22
- <?php /************************************************************************/
23
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues)
24
- echo '<tr><td>'.$aryValues['label'].'</td><td>'.$aryValues['nb_visits'].'</td><td>'.$aryValues['bounce_rate'].'</td></tr>';
25
- else echo '<tr><td colspan="2">'.__('No data available.', 'wp-piwik').'</td></tr>';
26
- /***************************************************************************/ ?>
27
- </tbody>
28
- </table>
29
- <?php /************************************************************************/
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/seo.php DELETED
@@ -1,36 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:SEO
4
- **********************************/
5
- $aryConf['data'] = $GLOBALS['wp_piwik']->callPiwikAPI(
6
- 'SEO.getRank',
7
- $aryConf['params']['period'],
8
- $aryConf['params']['date'],
9
- $aryConf['params']['limit'],
10
- false,
11
- false,
12
- 'csv'
13
- );
14
-
15
- if (substr($aryConf['data'], 0, 6) == 'Error:') {
16
- $strMessage = str_replace('Error:', '', $aryConf['data']);
17
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($strMessage, ENT_QUOTES, 'utf-8');
18
- } else {
19
-
20
- $aryConf['title'] = __('SEO', 'wp-piwik');
21
- $aryLines = explode("\n", $aryConf['data']);
22
- foreach ($aryLines as $strLine)
23
- $aryData[] = explode(',', $strLine);
24
- unset($aryData[0]);
25
- /***************************************************************************/ ?>
26
- <div class="table">
27
- <table class="widefat">
28
- <tbody>
29
- <?php foreach ($aryData as $aryVal) { ?>
30
- <tr><td><?php echo $aryVal[0]; ?></td><td><?php echo $aryVal[1]; ?></td></tr>
31
- <?php } ?>
32
- </tbody>
33
- </table>
34
- </div>
35
- <?php /************************************************************************/
36
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/systems.php DELETED
@@ -1,69 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Systems
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'UserSettings.getOS',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Operating System', 'wp-piwik');
13
- $strValues = '';
14
- $intCount = 0; $intMore = 0; $intSum = 0;
15
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] ='error')
16
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
17
- else {
18
- if (is_array($aryConf['data']))
19
- foreach ($aryConf['data'] as $key => $aryValues) {
20
- $intCount++;
21
- if ($intCount <= 9) $strValues .= '["'.$aryValues['label'].'",'.$aryValues['nb_uniq_visitors'].'],';
22
- else $intMore += $aryValues['nb_uniq_visitors'];
23
- $intSum += $aryValues['nb_uniq_visitors'];
24
- }
25
- if ($intMore) $strValues .= '["'.__('Others', 'wp-piwik').'",'.$intMore.'],';
26
- $strValues = substr($strValues, 0, -1);
27
-
28
- if ($intSum) {
29
- /***************************************************************************/ ?>
30
- <div class="wp-piwik-graph-wide">
31
- <div id="wp-piwik_stats_systems_graph" style="height:310px;width:100%"></div>
32
- </div>
33
- <?php /************************************************************************/
34
- }
35
- /***************************************************************************/ ?>
36
- <div class="table">
37
- <table class="widefat wp-piwik-table">
38
- <thead>
39
- <tr>
40
- <th><?php _e('Operating System', 'wp-piwik'); ?></th>
41
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
42
- <th class="n"><?php _e('Percent', 'wp-piwik'); ?></th>
43
- </tr>
44
- </thead>
45
- <tbody>
46
- <?php /************************************************************************/
47
- if ($intSum)
48
- foreach ($aryConf['data'] as $aryValues)
49
- echo '<tr><td>'.
50
- $aryValues['label'].
51
- '</td><td class="n">'.
52
- $aryValues['nb_uniq_visitors'].
53
- '</td><td class="n">'.
54
- number_format($aryValues['nb_uniq_visitors']/$intSum*100, 2).
55
- '%</td></tr>';
56
- else echo '<tr><td colspan="3">'.__('No data available.', 'wp-piwik').'</td></tr>';
57
- unset($aryTmp);
58
- /***************************************************************************/ ?>
59
- </tbody>
60
- </table>
61
- </div>
62
- <script type="text/javascript">
63
- $plotSystems = $j.jqplot('wp-piwik_stats_systems_graph', [[<?php echo $strValues; ?>]], {
64
- seriesDefaults:{renderer:$j.jqplot.PieRenderer, rendererOptions:{sliceMargin:8}},
65
- legend:{show:true}
66
- });
67
- </script>
68
- <?php
69
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/visitors.php DELETED
@@ -1,99 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Vistors
4
- **********************************/
5
-
6
- $aryConf['data']['Visitors'] = $this->callPiwikAPI(
7
- 'VisitsSummary.getVisits',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['data']['Unique'] = $this->callPiwikAPI(
13
- 'VisitsSummary.getUniqueVisitors',
14
- $aryConf['params']['period'],
15
- $aryConf['params']['date'],
16
- $aryConf['params']['limit']
17
- );
18
- $aryConf['data']['Bounced'] = $this->callPiwikAPI(
19
- 'VisitsSummary.getBounceCount',
20
- $aryConf['params']['period'],
21
- $aryConf['params']['date'],
22
- $aryConf['params']['limit']
23
- );
24
- $aryConf['data']['Actions'] = $this->callPiwikAPI(
25
- 'VisitsSummary.getActions',
26
- $aryConf['params']['period'],
27
- $aryConf['params']['date'],
28
- $aryConf['params']['limit']
29
- );
30
-
31
- if (isset($aryConf['data']['Visitors']['result']) && $aryConf['data']['Visitors']['result'] ='error')
32
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['Visitors']['message'], ENT_QUOTES, 'utf-8');
33
- else {
34
- $strValues = $strLabels = $strBounced = $strValuesU = $strCounter = '';
35
- $intUSum = $intCount = 0;
36
- if (is_array($aryConf['data']['Visitors']))
37
- foreach ($aryConf['data']['Visitors'] as $strDate => $intValue) {
38
- $intCount++;
39
- $strValues .= $intValue.',';
40
- $strValuesU .= $aryConf['data']['Unique'][$strDate].',';
41
- $strBounced .= $aryConf['data']['Bounced'][$strDate].',';
42
- $strLabels .= '['.$intCount.',"'.substr($strDate,-2).'"],';
43
- $intUSum += $aryConf['data']['Unique'][$strDate];
44
- }
45
- else {$strValues = '0,'; $strLabels = '[0,"-"],'; $strValuesU = '0,'; $strBounced = '0,'; }
46
- $intAvg = round($intUSum/30,0);
47
- $strValues = substr($strValues, 0, -1);
48
- $strValuesU = substr($strValuesU, 0, -1);
49
- $strLabels = substr($strLabels, 0, -1);
50
- $strBounced = substr($strBounced, 0, -1);
51
- $strCounter = substr($strCounter, 0, -1);
52
-
53
- /***************************************************************************/ ?>
54
- <div class="wp-piwik-graph-wide" title="<?php _e('The graph contains the values shown in the table below (visitors / unique / bounces). The red line show a linear trendline (unique).', 'wp-piwik'); ?>">
55
- <div id="wp-piwik_stats_vistors_graph" style="height:220px;<?php if (!isset($aryConf['inline']) || $aryConf['inline'] != true) { ?>width:100%<?php } ?>"></div>
56
- </div>
57
- <?php if (!isset($aryConf['inline']) || $aryConf['inline'] != true) { ?>
58
- <div class="table">
59
- <table class="widefat wp-piwik-table">
60
- <thead>
61
- <tr>
62
- <th><?php _e('Date', 'wp-piwik'); ?></th>
63
- <th class="n"><?php _e('Visits', 'wp-piwik'); ?></th>
64
- <th class="n"><?php _e('Unique', 'wp-piwik'); ?></th>
65
- <th class="n"><?php _e('Bounced', 'wp-piwik'); ?></th>
66
- <th class="n"><?php _e('Page Views', 'wp-piwik'); ?></th>
67
- </tr>
68
- </thead>
69
- <tbody style="cursor:pointer;">
70
- <?php /************************************************************************/
71
- if (is_array($aryConf['data']['Visitors'])) {
72
- $aryTmp = array_reverse($aryConf['data']['Visitors']);
73
- foreach ($aryTmp as $strDate => $intValue)
74
- echo '<tr onclick="javascript:datelink(\''.urlencode('wp-piwik_stats').'\',\''.str_replace('-', '', $strDate).'\',\''.(isset($_GET['wpmu_show_stats'])?(int) $_GET['wpmu_show_stats']:'').'\');"><td>'.$strDate.'</td><td class="n">'.
75
- $intValue.'</td><td class="n">'.
76
- $aryConf['data']['Unique'][$strDate].
77
- '</td><td class="n">'.
78
- $aryConf['data']['Bounced'][$strDate].
79
- '</td><td class="n">'.
80
- $aryConf['data']['Actions'][$strDate].
81
- '</td></tr>'."\n";
82
- }
83
- echo '<tr><td class="n" colspan="4"><strong>'.__('Unique TOTAL', 'wp-piwik').'</strong> '.__('Sum', 'wp-piwik').': '.$intUSum.' '.__('Avg', 'wp-piwik').': '.$intAvg.'</td></tr>';
84
- unset($aryTmp);
85
- /***************************************************************************/ ?>
86
- </tbody>
87
- </table>
88
- </div>
89
- <?php } ?>
90
- <script type="text/javascript">
91
- $plotVisitors = $j.jqplot('wp-piwik_stats_vistors_graph', [[<?php echo $strValues; ?>],[<?php echo $strValuesU; ?>],[<?php echo $strBounced;?>]],
92
- {
93
- axes:{yaxis:{min:0, tickOptions:{formatString:'%.0f'}},xaxis:{min:1,max:30,ticks:[<?php echo $strLabels; ?>]}},
94
- seriesDefaults:{showMarker:false,lineWidth:1,fill:true,fillAndStroke:true,fillAlpha:0.9,trendline:{show:false,color:'#C00',lineWidth:1.5,type:'exp'}},
95
- series:[{color:'#90AAD9',fillColor:'#D4E2ED'},{color:'#A3BCEA',fillColor:'#E4F2FD',trendline:{show:true,label:'Unique visitor trend'}},{color:'#E9A0BA',fillColor:'#FDE4F2'}],
96
- });
97
- </script>
98
- <?php
99
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dashboard/websites.php DELETED
@@ -1,34 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Stats:Websites
4
- **********************************/
5
-
6
- $aryConf['data'] = $this->callPiwikAPI(
7
- 'Referers.getWebsites',
8
- $aryConf['params']['period'],
9
- $aryConf['params']['date'],
10
- $aryConf['params']['limit']
11
- );
12
- $aryConf['title'] = __('Websites', 'wp-piwik');
13
-
14
- if (isset($aryConf['data']['result']) && $aryConf['data']['result'] = 'error')
15
- echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($aryConf['data']['message'], ENT_QUOTES, 'utf-8');
16
- else {
17
- /***************************************************************************/ ?>
18
- <table class="widefat">
19
- <thead>
20
- <tr>
21
- <th><?php _e('Website', 'wp-piwik'); ?></th>
22
- <th><?php _e('Unique', 'wp-piwik'); ?></th>
23
- </tr>
24
- </thead>
25
- <tbody>
26
- <?php /************************************************************************/
27
- if (is_array($aryConf['data'])) foreach ($aryConf['data'] as $aryValues)
28
- echo '<tr><td>'.$aryValues['label'].'</td><td>'.$aryValues['nb_uniq_visitors'].'</td></tr>';
29
- else echo '<tr><td colspan="2">'.__('No data available.', 'wp-piwik').'</td></tr>';
30
- /***************************************************************************/ ?>
31
- </tbody>
32
- </table>
33
- <?php /************************************************************************/
34
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
piwik.php DELETED
@@ -1,126 +0,0 @@
1
- <?php
2
-
3
- require('../../../wp-load.php');
4
- require_once('classes/WP_Piwik_Settings.php');
5
- require_once('classes/WP_Piwik_Logger_Dummy.php');
6
-
7
- $logger = new WP_Piwik_Logger_Dummy(__CLASS__);
8
- $settings = new WP_Piwik_Settings($logger);
9
-
10
- /* PIWIK PROXY SCRIPT */
11
-
12
- /* == Description ==
13
- This script allows to track statistics using Piwik, without revealing the
14
- Piwik Server URL. This is useful for users who track multiple websites
15
- in the same Piwik server, but don't want to show in the source code of all tracked
16
- websites the Piwik server URL.
17
-
18
- == Requirements ==
19
- To run this properly you will need
20
- - Piwik server latest version
21
- - One or several website(s) to track with this Piwik server, for example http://trackedsite.com
22
- - The website to track must run on a server with PHP5 support
23
- - In your php.ini you must check that the following is set: "allow_url_fopen = On"
24
-
25
- == How to track trackedsite.com in your Piwik without revealing the Piwik server URL? ==
26
-
27
- 1) In your Piwik server, login as Super user
28
- 2) create a user, set the login for example: "UserTrackingAPI"
29
- 3) Assign this user "admin" permission on all websites you wish to track without showing the Piwik URL
30
- 4) Copy the "token_auth" for this user, and paste it below in this file, in $TOKEN_AUTH = "xyz"
31
- 5) In this file, below this help test, edit $PIWIK_URL variable and change http://piwik-server.com/piwik/ with the URL to your Piwik server.
32
- 6) Upload this modified piwik.php file in the website root directory, for example at: http://trackedsite.com/piwik.php
33
- This file (http://trackedsite.com/piwik.php) will be called by the Piwik Javascript,
34
- instead of calling directly the (secret) Piwik Server URL (http://piwik-server.com/piwik/).
35
- 7) You now need to add the modified Piwik Javascript Code to the footer of your pages at http://trackedsite.com/
36
- Go to Piwik > Settings > Websites > Show Javascript Tracking Code.
37
- Copy the Javascript snippet. Then, edit this code and change the last lines to the following:
38
- [...]
39
- (function() {
40
- var u=(("https:" == document.location.protocol) ? "https" : "http") + "://trackedsite.com/";
41
- _paq.push(["setTrackerUrl", u+"piwik.php"]);
42
- var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript";
43
- g.defer=true; g.async=true; g.src=u+"piwik.php"; s.parentNode.insertBefore(g,s);
44
- })();
45
- </script>
46
- <!-- End Piwik Code -->
47
-
48
- What's changed in this code snippet compared to the normal Piwik code?
49
- A) the (secret) Piwik URL is now replaced by your website URL
50
- B) the "piwik.js" becomes "piwik.php" because this piwik.php proxy script will also display and proxy the Javascript file
51
- C) the <noscript> part of the code at the end is removed,
52
- since it is not currently used by Piwik, and it contains the (secret) Piwik URL which you want to hide.
53
- 8) Paste the modified Piwik Javascript code in your website "trackedsite.com" pages you wish to track.
54
- This modified Javascript Code will then track visits/pages/conversions by calling trackedsite.com/piwik.php
55
- which will then automatically call your (hidden) Piwik Server URL.
56
- 9) Done!
57
- At this stage, example.com should be tracked by your Piwik without showing the Piwik server URL.
58
- Repeat the steps 6), 7) and 8) for each website you wish to track in Piwik.
59
- */
60
-
61
- // Edit the line below, and replace http://piwik-server.com/piwik/
62
- // with your Piwik URL ending with a slash.
63
- // This URL will never be revealed to visitors or search engines.
64
- $PIWIK_URL = $settings->getGlobalOption('piwik_url');
65
-
66
- // Edit the line below, and replace xyz by the token_auth for the user "UserTrackingAPI"
67
- // which you created when you followed instructions above.
68
- $TOKEN_AUTH = $settings->getGlobalOption('piwik_token');
69
-
70
- // Maximum time, in seconds, to wait for the Piwik server to return the 1*1 GIF
71
- $timeout = 5;
72
-
73
-
74
-
75
- // DO NOT MODIFY BELOW
76
- // ---------------------------
77
- // 1) PIWIK.JS PROXY: No _GET parameter, we serve the JS file
78
- if(empty($_GET))
79
- {
80
- $modifiedSince = false;
81
- if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
82
- {
83
- $modifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
84
- // strip any trailing data appended to header
85
- if (false !== ($semicolon = strpos($modifiedSince, ';')))
86
- {
87
- $modifiedSince = strtotime(substr($modifiedSince, 0, $semicolon));
88
- }
89
- }
90
- // Re-download the piwik.js once a day maximum
91
- $lastModified = time()-86400;
92
-
93
- // set HTTP response headers
94
- header('Vary: Accept-Encoding');
95
-
96
- // Returns 304 if not modified since
97
- if (!empty($modifiedSince) && $modifiedSince < $lastModified)
98
- {
99
- header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
100
- }
101
- else
102
- {
103
- header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
104
- @header('Content-Type: application/javascript; charset=UTF-8');
105
- if( $piwikJs = file_get_contents($PIWIK_URL.'piwik.js')) {
106
- echo $piwikJs;
107
- } else {
108
- header($_SERVER['SERVER_PROTOCOL'] . '505 Internal server error');
109
- }
110
- }
111
- exit;
112
- }
113
-
114
- // 2) PIWIK.PHP PROXY: GET parameters found, this is a tracking request, we redirect it to Piwik
115
- $url = $PIWIK_URL."piwik.php?cip=".@$_SERVER['REMOTE_ADDR']."&token_auth=".$TOKEN_AUTH.'&';
116
- foreach($_GET as $key=>$value) {
117
- $url .= $key .'='.urlencode($value).'&';
118
- }
119
- header("Content-Type: image/gif");
120
- $stream_options = array('http' => array(
121
- 'user_agent' => @$_SERVER['HTTP_USER_AGENT'],
122
- 'header' => "Accept-Language: " . @str_replace(array("\n","\t","\r"), "", $_SERVER['HTTP_ACCEPT_LANGUAGE']) . "\r\n" ,
123
- 'timeout' => $timeout
124
- ));
125
- $ctx = stream_context_create($stream_options);
126
- echo file_get_contents($url, 0, $ctx);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
proxy/config.php ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ require('../../../../wp-load.php');
4
+ require_once('../classes/WP_Piwik/Settings.php');
5
+ require_once('../classes/WP_Piwik/Logger.php');
6
+ require_once('../classes/WP_Piwik/Logger/Dummy.php');
7
+
8
+ $logger = new WP_Piwik\Logger\Dummy(__CLASS__);
9
+ $settings = new WP_Piwik\Settings(null, $logger);
10
+
11
+ $PIWIK_URL = $settings->getGlobalOption('piwik_url');
12
+ $TOKEN_AUTH = $settings->getGlobalOption('piwik_token');
13
+ $timeout = $settings->getGlobalOption('connection_timeout');
14
+ ini_set('display_errors',0);
{classes → proxy}/index.php RENAMED
File without changes
proxy/piwik.php ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Piwik - free/libre analytics platform
4
+ * Piwik Proxy Hide URL
5
+ *
6
+ * @link http://piwik.org/faq/how-to/#faq_132
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+ if (file_exists('config.php')) {
10
+ include 'config.php';
11
+ }
12
+ // -----
13
+ // Important: read the instructions in README.md or at:
14
+ // https://github.com/piwik/piwik/tree/master/misc/proxy-hide-piwik-url#piwik-proxy-hide-url
15
+ // -----
16
+ // Edit the line below, and replace http://your-piwik-domain.example.org/piwik/
17
+ // with your Piwik URL ending with a slash.
18
+ // This URL will never be revealed to visitors or search engines.
19
+ if (! isset($PIWIK_URL)) {
20
+ $PIWIK_URL = 'http://your-piwik-domain.example.org/piwik/';
21
+ }
22
+ // Edit the line below, and replace xyz by the token_auth for the user "UserTrackingAPI"
23
+ // which you created when you followed instructions above.
24
+ if (! isset($TOKEN_AUTH)) {
25
+ $TOKEN_AUTH = 'xyz';
26
+ }
27
+ // Maximum time, in seconds, to wait for the Piwik server to return the 1*1 GIF
28
+ if (! isset($timeout)) {
29
+ $timeout = 5;
30
+ }
31
+ function sendHeader($header, $replace = true)
32
+ {
33
+ headers_sent() || header($header, $replace);
34
+ }
35
+ function arrayValue($array, $key, $value = null)
36
+ {
37
+ if (!empty($array[$key])) {
38
+ $value = $array[$key];
39
+ }
40
+ return $value;
41
+ }
42
+ function getContents($url, $options = false)
43
+ {
44
+ if (ini_get('allow_url_fopen')) {
45
+ $ctx = ($options?stream_context_create($options):NULL);
46
+ return file_get_contents($url, 0, $ctx);
47
+ } elseif (function_exists('curl_version'))
48
+ return piwikFileGetContentsCurl($url, $options);
49
+ else return 'Neither url_fopen nor cURL is available. Please enable at least one of them.';
50
+ }
51
+ function piwikFileGetContentsCurl($url, $options)
52
+ {
53
+ $ch = curl_init();
54
+ curl_setopt($ch, CURLOPT_HEADER, 0);
55
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
56
+ curl_setopt($ch, CURLOPT_USERAGENT, $options['http']['user_agent']);
57
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $options['http']['header']);
58
+ curl_setopt($ch, CURLOPT_TIMEOUT, $options['http']['timeout']);
59
+ curl_setopt($ch, CURLOPT_URL, $url);
60
+ $data = curl_exec($ch);
61
+ curl_close($ch);
62
+ return $data;
63
+ }
64
+ // DO NOT MODIFY BELOW
65
+ // ---------------------------
66
+ // 1) PIWIK.JS PROXY: No _GET parameter, we serve the JS file
67
+ if (empty($_GET)) {
68
+ $modifiedSince = false;
69
+ if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
70
+ $modifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
71
+ // strip any trailing data appended to header
72
+ if (false !== ($semicolon = strpos($modifiedSince, ';'))) {
73
+ $modifiedSince = substr($modifiedSince, 0, $semicolon);
74
+ }
75
+ $modifiedSince = strtotime($modifiedSince);
76
+ }
77
+ // Re-download the piwik.js once a day maximum
78
+ $lastModified = time() - 86400;
79
+ // set HTTP response headers
80
+ sendHeader('Vary: Accept-Encoding');
81
+ // Returns 304 if not modified since
82
+ if (!empty($modifiedSince) && $modifiedSince > $lastModified) {
83
+ sendHeader(sprintf("%s 304 Not Modified", $_SERVER['SERVER_PROTOCOL']));
84
+ } else {
85
+ sendHeader('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
86
+ sendHeader('Content-Type: application/javascript; charset=UTF-8');
87
+ if ($piwikJs = getContents($PIWIK_URL . 'piwik.js')) {
88
+ echo $piwikJs;
89
+ } else {
90
+ sendHeader($_SERVER['SERVER_PROTOCOL'] . '505 Internal server error');
91
+ }
92
+ }
93
+ exit;
94
+ }
95
+ @ini_set('magic_quotes_runtime', 0);
96
+ // 2) PIWIK.PHP PROXY: GET parameters found, this is a tracking request, we redirect it to Piwik
97
+ $url = sprintf("%spiwik.php?cip=%s&token_auth=%s&", $PIWIK_URL, getVisitIp(), $TOKEN_AUTH);
98
+ foreach ($_GET as $key => $value) {
99
+ $url .= urlencode($key ). '=' . urlencode($value) . '&';
100
+ }
101
+ sendHeader("Content-Type: image/gif");
102
+ $stream_options = array('http' => array(
103
+ 'user_agent' => arrayValue($_SERVER, 'HTTP_USER_AGENT', ''),
104
+ 'header' => sprintf("Accept-Language: %s\r\n", str_replace(array("\n", "\t", "\r"), "", arrayValue($_SERVER, 'HTTP_ACCEPT_LANGUAGE', ''))),
105
+ 'timeout' => $timeout
106
+ ));
107
+ if (version_compare(PHP_VERSION, '5.3.0', '<')) {
108
+ // PHP 5.2 breaks with the new 204 status code so we force returning the image every time
109
+ echo getContents($url . '&send_image=1', $stream_options);
110
+ } else {
111
+ // PHP 5.3 and above
112
+ $content = getContents($url, $stream_options);
113
+ // Forward the HTTP response code
114
+ if (!headers_sent() && isset($http_response_header[0])) {
115
+ header($http_response_header[0]);
116
+ }
117
+ echo $content;
118
+ }
119
+ function getVisitIp()
120
+ {
121
+ $matchIp = '/^([0-9]{1,3}\.){3}[0-9]{1,3}$/';
122
+ $ipKeys = array(
123
+ 'HTTP_X_FORWARDED_FOR',
124
+ 'HTTP_CLIENT_IP',
125
+ 'HTTP_CF_CONNECTING_IP',
126
+ );
127
+ foreach($ipKeys as $ipKey) {
128
+ if (isset($_SERVER[$ipKey])
129
+ && preg_match($matchIp, $_SERVER[$ipKey])) {
130
+ return $_SERVER[$ipKey];
131
+ }
132
+ }
133
+ return arrayValue($_SERVER, 'REMOTE_ADDR');
134
+ }
readme.txt CHANGED
@@ -1,9 +1,9 @@
1
  === WP-Piwik ===
2
 
3
  Contributors: Braekling
4
- Requires at least: 3.0
5
- Tested up to: 4.1.1
6
- Stable tag: 0.9.9.14
7
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6046779
8
  Tags: statistics, stats, analytics, piwik, wpmu
9
 
@@ -13,10 +13,10 @@ This plugin adds a Piwik stats site to your WordPress or WordPress multisite das
13
 
14
  This plugin adds a Piwik stats site to your WordPress dashboard. It's also able to add the Piwik tracking code to your blog using wp_footer.
15
 
16
- You need a running **Piwik 2.7.0 or higher** installation and at least view access to your stats. Also **PHP 5.3 or higher** is strictly required.
17
-
18
- Look at the [Piwik website](http://piwik.org/) to get further information about Piwik.
19
 
 
 
20
  *This plugin is not created or provided by the Piwik project team.*
21
 
22
  Languages: English, German, Albanian, Azerbaijani, Belorussian, Chinese (simplified), Dutch, French, Greek, Italian, Lithuanian, Norwegian, Persian, Romanian, Russian, Spanish, Swedish, Ukrainian
@@ -58,15 +58,15 @@ Thank you all!
58
 
59
  = Where can I find the Piwik URL and the Piwik auth token? =
60
 
61
- WP-Piwik requires Piwik. If you did not install Piwik yet, first get it at the [Piwik website](http://www.piwik.org).
62
 
63
- If Piwik works, you'll be able to configure WP-Piwik: The Piwik URL is the same URL you use to access your Piwik, e.g. for the demo site: http://demo.piwik.org. The auth token is some kind of secret password, which allows WP-Piwik to get the necessary data from Piwik. The super user's auth token, i.e. a full access password for your Piwik, can be found on Piwik's API site. You can find a detailed description [here](http://peepbo.de/board/viewtopic.php?f=5&t=10).
64
 
65
  = How to reset/remove all WP-Piwik settings without uninstalling? =
66
 
67
  Login to your admin dashboard and open http://YOUR_BLOG_URL/wp-admin/options-general.php?page=wp-piwik/wp-piwik.php&tab=support&mode=resetconfirmed&full=1
68
 
69
- = Tracking does not work on HostGator! =
70
 
71
  Try to enable the "avoid mod_security" option (WP-Piwik settings, Tracking tab) or create a mod_security whitelist.
72
 
@@ -121,17 +121,43 @@ Add WP-Piwik to your /wp-content/plugins folder and enable it as [Network Plugin
121
 
122
  == Upgrade Notice ==
123
 
124
- Please update Piwik if not done yet (Piwik 2.7 or higher is recommended). If you update Piwik and use the "add tracking code" feature, please also update your WP-Piwik tracking code: Just open the WP-Piwik tracking code settings and save them again.
125
 
126
  == Changelog ==
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  = 0.9.9.14 =
129
- * Fixes some commit errors in 0.9.9.13.
130
 
131
  = 0.9.9.13 =
132
  * Improvement: Only activate/ load admin components if an admin page is actually loaded. Thanks to Michael!
133
  * Bugfix: Proxy tracking will work again. Piwik 2.7 or higher is recommended.
134
- * Bugfix: Avoid a PHP notice in dashboard.
135
  * NOTE: If you update Piwik and use the "add tracking code" feature, please also update your WP-Piwik tracking code: Just open the WP-Piwik tracking code settings and save them again.
136
 
137
  = 0.9.9.12 =
1
  === WP-Piwik ===
2
 
3
  Contributors: Braekling
4
+ Requires at least: 4.0
5
+ Tested up to: 4.2
6
+ Stable tag: 0.9.9.18
7
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6046779
8
  Tags: statistics, stats, analytics, piwik, wpmu
9
 
13
 
14
  This plugin adds a Piwik stats site to your WordPress dashboard. It's also able to add the Piwik tracking code to your blog using wp_footer.
15
 
16
+ To use this plugin you will need your own Piwik instance. If you do not already have a Piwik setup, you have two simple options: use either [Self-hosted](http://piwik.org/) (**Piwik 2.7.0 or higher**) or [Cloud-hosted](http://piwik.org/hosting/).
 
 
17
 
18
+ **PHP 5.3 or higher** is strictly required.
19
+
20
  *This plugin is not created or provided by the Piwik project team.*
21
 
22
  Languages: English, German, Albanian, Azerbaijani, Belorussian, Chinese (simplified), Dutch, French, Greek, Italian, Lithuanian, Norwegian, Persian, Romanian, Russian, Spanish, Swedish, Ukrainian
58
 
59
  = Where can I find the Piwik URL and the Piwik auth token? =
60
 
61
+ To use this plugin you will need your own Piwik instance. If you do not already have a Piwik setup, you have two simple options: use either [Self-hosted](http://piwik.org/) or [Cloud-hosted](http://piwik.org/hosting/).
62
 
63
+ As soon as Piwik works, you'll be able to configure WP-Piwik: The Piwik URL is the same URL you use to access your Piwik, e.g. for the demo site: http://demo.piwik.org. The auth token is some kind of secret password, which allows WP-Piwik to get the necessary data from Piwik. To get your auth token, log in to Piwik, click at your user name (top right) and click at "API" (left sidebar menu). E.g., on (this demo site)[http://demo.piwik.org/index.php?module=API&action=listAllAPI&idSite=7&period=day&date=yesterday] you can see the auth token "anonymous".
64
 
65
  = How to reset/remove all WP-Piwik settings without uninstalling? =
66
 
67
  Login to your admin dashboard and open http://YOUR_BLOG_URL/wp-admin/options-general.php?page=wp-piwik/wp-piwik.php&tab=support&mode=resetconfirmed&full=1
68
 
69
+ = Tracking does not work on HostGator! / The test script shows an empty response. =
70
 
71
  Try to enable the "avoid mod_security" option (WP-Piwik settings, Tracking tab) or create a mod_security whitelist.
72
 
121
 
122
  == Upgrade Notice ==
123
 
124
+ Please update Piwik if not done yet (Piwik 2.7 or higher is recommended).
125
 
126
  == Changelog ==
127
 
128
+ = 0.9.9.18 =
129
+ * Improvement: Define additional file extensions for tracking downloads
130
+ * Improvement: Added a POT file to support translators (Note: 1.0 will change a lot, so please don't spend too much time in translating the current version, e.g., by creating an all new translation. With 1.0 I will also offer a translation platform to support your work.)
131
+ * Improvement: If necessary, you can force Piwik to use HTTP or HTTPS now (e.g., to avoid redirections from http to https)
132
+ * Avoided a naming collision with Woo Theme
133
+
134
+ = 0.9.9.17 =
135
+ * Improvement: Updated the Piwik proxy script and added cURL support if url_fopen is not available
136
+ * Bugfix: Setup bug, see https://wordpress.org/support/topic/piwik-urlpath-not-saved
137
+ * Bugfix: CDN URL notice, see https://wordpress.org/support/topic/tracking-cdn-blank-gives-php-notice-which-breaks-the-trackback-js-code
138
+ * Bugfix: Fixed zlib compression notice, see https://wordpress.org/support/topic/v09914-is-bad
139
+ * Bugfix: Proxy script label links to proxy script checkbox
140
+ * Fixed a typo in German language file
141
+
142
+ = 0.9.9.16 =
143
+ * Bugfix: PHP API causes plain text output issue (see 0.9.9.11)
144
+ * Bugfix: Shortcode output translated
145
+
146
+ = 0.9.9.15 =
147
+ * Bugfix: One more commit error
148
+ * Bugfix: Adding up problem related to the overview widget
149
+ * Bugfix: Fixes missing brackets on ob_start
150
+ * Hotfix: Adds /0.9.9.15 to js/index.php to force a reload
151
+ * Bugifx: Replaced broken support link
152
+ * Added a bitcoin donation link
153
+
154
  = 0.9.9.14 =
155
+ * Bugfix: Commit errors in 0.9.9.13
156
 
157
  = 0.9.9.13 =
158
  * Improvement: Only activate/ load admin components if an admin page is actually loaded. Thanks to Michael!
159
  * Bugfix: Proxy tracking will work again. Piwik 2.7 or higher is recommended.
160
+ * Bugfix: Avoid a PHP notice in dashboard
161
  * NOTE: If you update Piwik and use the "add tracking code" feature, please also update your WP-Piwik tracking code: Just open the WP-Piwik tracking code settings and save them again.
162
 
163
  = 0.9.9.12 =
settings/.htaccess DELETED
@@ -1 +0,0 @@
1
- Deny from all
 
settings/homepage.php DELETED
@@ -1,11 +0,0 @@
1
- <?php
2
- $strVersion = $this->callPiwikAPI('API.getPiwikVersion');
3
- // http://wordpress.org/support/rss/tags/wp-piwik
4
- ?><tr><td><strong><?php _e('Thanks for using WP-Piwik!', 'wp-piwik'); ?></strong></td></tr>
5
- <tr><td><?php
6
- if (is_array($strVersion) && $strVersion['result'] == 'error') self::showErrorMessage($strVersion['message']);
7
- elseif (empty($strVersion)) self::showErrorMessage('Piwik did not answer. Please check your entered Piwik URL.');
8
- else echo __('You are using Piwik','wp-piwik').' '.$strVersion.' '.__('and', 'wp-piwik').' WP-Piwik '.self::$strVersion.(is_plugin_active_for_network('wp-piwik/wp-piwik.php')?' '.__('in network mode', 'wp-piwik'):'').'.';
9
- ?></td></tr>
10
- <tr><td><?php _e('Auto site configuration is','wp-piwik'); ?> <strong><?php echo (self::$settings->getGlobalOption('auto_site_config')?__('enabled','wp-piwik'):__('disabled','wp-piwik')); ?>.</strong></td></tr>
11
- <tr><td><?php _e('Tracking code insertion is','wp-piwik'); ?> <strong><?php echo (self::$settings->getGlobalOption('add_tracking_code')?__('enabled','wp-piwik'):__('disabled','wp-piwik')); ?>.</strong></td></tr>
 
 
 
 
 
 
 
 
 
 
 
settings/index.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- // Nothing to see...
 
 
settings/sitebrowser.php DELETED
@@ -1,99 +0,0 @@
1
- <?php
2
- $bolCURL = function_exists('curl_init');
3
- $bolFOpen = ini_get('allow_url_fopen');
4
- if (!$bolFOpen && !$bolCURL) {
5
- ?><tr>
6
- <td colspan="2">
7
- <strong><?php _e('Error: cURL is not enabled and fopen is not allowed to open URLs. WP-Piwik won\'t be able to connect to Piwik.'); ?></strong>
8
- </td>
9
- </tr><?php } else { ?>
10
- </table>
11
- <?php
12
- if (!class_exists('WP_List_Table'))
13
- require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
14
-
15
- if (isset($_GET['wpmu_show_stats']) && ($_GET['wpmu_show_stats'] == (int) $_GET['wpmu_show_stats'])) {
16
- $this->addPiwikSite();
17
- }
18
-
19
- // See wpengineer.com/2426/wp_list_table-a-step-by-step-guide/
20
- class SiteBrowser extends WP_List_Table {
21
-
22
- var $aryData = array();
23
-
24
- function get_columns(){
25
- $columns = array(
26
- 'id' => __('ID','wp-piwik'),
27
- 'name' => __('Title','wp-piwik'),
28
- 'siteurl' => __('URL','wp-piwik'),
29
- 'piwikid' => __('Site ID (Piwik)','wp-piwik')
30
- );
31
- return $columns;
32
- }
33
-
34
- function prepare_items($bolNetwork = false) {
35
- $current_page = $this->get_pagenum();
36
- $per_page = 10;
37
- global $blog_id;
38
- global $wpdb;
39
- global $pagenow;
40
- if (is_plugin_active_for_network('wp-piwik/wp-piwik.php')) {
41
- $total_items = $wpdb->get_var('SELECT COUNT(*) FROM '.$wpdb->blogs);
42
- $aryBlogs = $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM '.$wpdb->blogs.' ORDER BY blog_id LIMIT %d,%d',(($current_page-1)*$per_page),$per_page));
43
- foreach ($aryBlogs as $aryBlog) {
44
- $objBlog = get_blog_details($aryBlog->blog_id, true);
45
- $this->aryData[] = array(
46
- 'name' => $objBlog->blogname,
47
- 'id' => $objBlog->blog_id,
48
- 'siteurl' => $objBlog->siteurl,
49
- 'piwikid' => WP_Piwik::getSiteID($objBlog->blog_id)
50
- );
51
- }
52
- } else {
53
- $objBlog = get_bloginfo();
54
- $this->aryData[] = array(
55
- 'name' => get_bloginfo('name'),
56
- 'id' => '-',
57
- 'siteurl' => get_bloginfo('url'),
58
- 'piwikid' => WP_Piwik::getSiteID()
59
- );
60
- $total_items = 1;
61
- }
62
- $columns = $this->get_columns();
63
- $hidden = array();
64
- $sortable = array();
65
- $this->_column_headers = array($columns, $hidden, $sortable);
66
- $this->set_pagination_args(array(
67
- 'total_items' => $total_items,
68
- 'per_page' => $per_page
69
- ));
70
- if ($bolNetwork) $pagenow = 'settings.php';
71
- foreach ($this->aryData as $intKey => $aryDataset) {
72
- if (empty($aryDataset['piwikid']) || !is_int($aryDataset['piwikid']))
73
- $this->aryData[$intKey]['piwikid'] = '<a href="'.admin_url(($pagenow == 'settings.php'?'network/':'')).$pagenow.'?page=wp-piwik/wp-piwik.php&tab=sitebrowser'.($aryDataset['id'] != '-'?'&wpmu_show_stats='.$aryDataset['id']:'').'">Create Piwik site</a>';
74
- if ($bolNetwork)
75
- $this->aryData[$intKey]['name'] = '<a href="?page=wp-piwik_stats&wpmu_show_stats='.$aryDataset['id'].'">'.$aryDataset['name'].'</a>';
76
- }
77
- $this->items = $this->aryData;
78
- return count($this->items);
79
- }
80
-
81
- function column_default( $item, $column_name ) {
82
- switch( $column_name ) {
83
- case 'id':
84
- case 'name':
85
- case 'siteurl':
86
- case 'piwikid':
87
- return $item[$column_name];
88
- default:
89
- return print_r($item,true);
90
- }
91
- }
92
- }
93
- $objSiteBrowser = new SiteBrowser();
94
- $intCnt = $objSiteBrowser->prepare_items($this->bolNetwork);
95
- if ($intCnt > 0) $objSiteBrowser->display();
96
- else echo '<p>No site configured yet.</p>'
97
- ?>
98
- <table>
99
- <?php } ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
settings/support.php CHANGED
@@ -1,5 +1,5 @@
1
  <tr>
2
- <td><a href="http://wordpress.org/tags/wp-piwik?forum_id=10"><?php _e('WordPress.org forum about WP-Piwik','wp-piwik'); ?></a></td>
3
  </tr>
4
  <tr>
5
  <td><?php _e('Please don\'t forget to vote the compatibility at the','wp-piwik'); ?> <a href="http://wordpress.org/extend/plugins/wp-piwik/">WordPress.org Plugin Directory</a>.</td>
@@ -29,7 +29,7 @@
29
  self::loadTestscript();
30
  break;
31
  case 'reset':
32
- echo '<p class="wp-piwik-eyecatcher"><strong class="wp-piwik-error">'.__('Please confirm your reset request','wp-piwik').':</strong> <a href="?page=wp-piwik/wp-piwik.php&tab=support&mode=resetconfirmed">'.__('YES, please reset <strong>all</strong> WP-Piwik settings <strong>except</strong> auth token and Piwi URL.', 'wp-piwik').'</a></p>';
33
  break;
34
  case 'resetconfirmed':
35
  // Increase time limit before resetting
@@ -42,9 +42,9 @@
42
  ?>
43
  <p><strong><?php _e('Get more debug information', 'wp-piwik'); ?>:</strong></p>
44
  <ol>
45
- <li><a href="?page=wp-piwik/wp-piwik.php&tab=support&mode=testscript"><?php _e('Run test script','wp-piwik'); ?></a></li>
46
- <li><a href="?page=wp-piwik/wp-piwik.php&tab=sitebrowser"><?php _e('Get site configuration details','wp-piwik'); ?></a></li>
47
- <li><a href="?page=wp-piwik/wp-piwik.php&tab=support&mode=reset"><?php _e('Reset WP-Piwik settings except auth token and Piwik URL','wp-piwik'); ?></a> (<?php _e('This will not affect Piwik itself. Resetting large networks may take some minutes.', 'wp-piwik'); ?>)</li>
48
  </ol>
49
  <?php } else echo '<p>'.__('You have to enter your auth token and the Piwik URL before you can access more debug functions.', 'wp-piwik').'</p>'; ?>
50
  </td>
1
  <tr>
2
+ <td><a href="http://wordpress.org/support/plugin/wp-piwik"><?php _e('WordPress.org forum about WP-Piwik','wp-piwik'); ?></a></td>
3
  </tr>
4
  <tr>
5
  <td><?php _e('Please don\'t forget to vote the compatibility at the','wp-piwik'); ?> <a href="http://wordpress.org/extend/plugins/wp-piwik/">WordPress.org Plugin Directory</a>.</td>
29
  self::loadTestscript();
30
  break;
31
  case 'reset':
32
+ echo '<p class="wp-piwik-eyecatcher"><strong class="wp-piwik-error">'.__('Please confirm your reset request','wp-piwik').':</strong> <a href="?page=wp-piwik/classes/WP-Piwik.php&tab=support&mode=resetconfirmed">'.__('YES, please reset <strong>all</strong> WP-Piwik settings <strong>except</strong> auth token and Piwi URL.', 'wp-piwik').'</a></p>';
33
  break;
34
  case 'resetconfirmed':
35
  // Increase time limit before resetting
42
  ?>
43
  <p><strong><?php _e('Get more debug information', 'wp-piwik'); ?>:</strong></p>
44
  <ol>
45
+ <li><a href="?page=wp-piwik/classes/WP-Piwik.php&tab=support&mode=testscript"><?php _e('Run test script','wp-piwik'); ?></a></li>
46
+ <li><a href="?page=wp-piwik/classes/WP-Piwik.php&tab=sitebrowser"><?php _e('Get site configuration details','wp-piwik'); ?></a></li>
47
+ <li><a href="?page=wp-piwik/classes/WP-Piwik.php&tab=support&mode=reset"><?php _e('Reset WP-Piwik settings except auth token and Piwik URL','wp-piwik'); ?></a> (<?php _e('This will not affect Piwik itself. Resetting large networks may take some minutes.', 'wp-piwik'); ?>)</li>
48
  </ol>
49
  <?php } else echo '<p>'.__('You have to enter your auth token and the Piwik URL before you can access more debug functions.', 'wp-piwik').'</p>'; ?>
50
  </td>
shortcodes/.htaccess DELETED
@@ -1 +0,0 @@
1
- Deny from all
 
shortcodes/overview.php DELETED
@@ -1,45 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Short:Overview
4
- **********************************/
5
- $aryData = $this->callPiwikAPI('VisitsSummary.get',
6
- $this->aryAttributes['period'],
7
- $this->aryAttributes['date'],
8
- $this->aryAttributes['limit']
9
- );
10
-
11
- $this->strResult = '<table><tr><th colspan="2">'.__('Overview', 'wp-piwik').($this->aryAttributes['title']?' '.$this->aryAttributes['title']:'').'</th></tr>';
12
-
13
- if (is_array($aryData)) {
14
- if (isset($aryData['result']) && $aryData['result'] == 'error')
15
- $this->strResult .= '<tr><td>'.__('Error', 'wp-piwik').':'.'</td><td>'.$aryData['message'].'</td></tr>';
16
- else {
17
- if (is_array(current($aryData))) {
18
- $aryTmp = array();
19
- foreach ($aryData as $aryValues)
20
- foreach($aryValues as $strKey => $intValue)
21
- if (isset($aryTmp[$strKey])) $aryTmp[$strKey] += $intValue;
22
- else $aryTmp[$strKey] = $intValue;
23
- $aryTmp['bounce_rate'] = ($aryTmp['nb_uniq_visitors']==0?0:round($aryTmp['bounce_count']/$aryTmp['nb_visits']*100,2)).'%';
24
- $aryData = $aryTmp;
25
- }
26
- $aryData = summize($aryData);
27
- $strTime =
28
- floor($aryData['sum_visit_length']/3600).'h '.
29
- floor(($aryData['sum_visit_length'] % 3600)/60).'m '.
30
- floor(($aryData['sum_visit_length'] % 3600) % 60).'s';
31
- $strAvgTime =
32
- floor($aryData['avg_time_on_site']/3600).'h '.
33
- floor(($aryData['avg_time_on_site'] % 3600)/60).'m '.
34
- floor(($aryData['avg_time_on_site'] % 3600) % 60).'s';
35
- $this->strResult .= '<tr><td>'.__('Visitors', 'wp-piwik').':'.'</td><td>'.$aryData['nb_visits'].'</td></tr>';
36
- $this->strResult .= '<tr><td>'.__('Unique visitors', 'wp-piwik').':'.'</td><td>'.$aryData['nb_uniq_visitors'].'</td></tr>';
37
- $this->strResult .= '<tr><td>'.__('Page views', 'wp-piwik').':'.'</td><td>'.$aryData['nb_actions'].' (&#216; '.$aryData['nb_actions_per_visit'].')</td></tr>';
38
- $this->strResult .= '<tr><td>'.__('Max. page views in one visit', 'wp-piwik').':'.'</td><td>'.$aryData['max_actions'].'</td></tr>';
39
- $this->strResult .= '<tr><td>'.__('Total time spent', 'wp-piwik').':'.'</td><td>'.$strTime.'</td></tr>';
40
- $this->strResult .= '<tr><td>'.__('Time/visit', 'wp-piwik').':'.'</td><td>'.$strAvgTime.'</td></tr>';
41
- $this->strResult .= '<tr><td>'.__('Bounce count', 'wp-piwik').':'.'</td><td>'.$aryData['bounce_count'].' ('.$aryData['bounce_rate'].')</td></tr>';
42
- }
43
- } else $this->strResult .= '<tr><td>'.__('No data available', 'wp-piwik').'</td></tr>';
44
-
45
- $this->strResult .= '</table>';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shortcodes/post.php DELETED
@@ -1,6 +0,0 @@
1
- <?php
2
- /*********************************
3
- WP-Piwik::Short:Post
4
- **********************************/
5
- $perPostClass = new WP_Piwik_Template_MetaBoxPerPostStats($this->subClassConfig());
6
- $this->strResult = $perPostClass->getValue($this->aryAttributes['range'], $this->aryAttributes['key']);
 
 
 
 
 
 
update/80502.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('default_date', 'yesterday');
 
 
update/80602.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('dashboard_chart', false);
 
 
update/80800.php CHANGED
@@ -1,2 +1,2 @@
1
  <?php
2
- self::$settings->setGlobalOption('piwik_url', self::checkURL(self::$settings->getGlobalOption('piwik_url')));
1
  <?php
2
+ self::$settings->setGlobalOption('piwik_url', self::$settings->getGlobalOption('piwik_url').((substr($strURL, -1, 1) != '/' && substr($strURL, -10, 10) != '/index.php')?'/':''));
update/90001.php CHANGED
@@ -1,13 +1,8 @@
1
  <?php
2
  $aryWPMUConfig = get_site_option('wpmu-piwik_global-settings',false);
3
- if (is_plugin_active_for_network('wp-piwik/wp-piwik.php') && $aryWPMUConfig) {
4
  foreach ($aryWPMUConfig as $key => $value)
5
  self::$settings->setGlobalOption($key, $value);
6
  delete_site_option('wpmu-piwik_global-settings');
7
  self::$settings->setGlobalOption('auto_site_config', true);
8
- } else self::$settings->setGlobalOption('auto_site_config', false);
9
- self::$settings->setGlobalOption('dashboard_seo', false);
10
- self::$settings->setGlobalOption('stats_seo', false);
11
- self::$settings->setGlobalOption('track_404', self::$settings->getOption('track_404'));
12
- self::$settings->setGlobalOption('track_compress', false);
13
- self::$settings->setGlobalOption('track_post', false);
1
  <?php
2
  $aryWPMUConfig = get_site_option('wpmu-piwik_global-settings',false);
3
+ if (self::$settings->checkNetworkActivation() && $aryWPMUConfig) {
4
  foreach ($aryWPMUConfig as $key => $value)
5
  self::$settings->setGlobalOption($key, $value);
6
  delete_site_option('wpmu-piwik_global-settings');
7
  self::$settings->setGlobalOption('auto_site_config', true);
8
+ } else self::$settings->setGlobalOption('auto_site_config', false);
 
 
 
 
 
update/90206.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('disable_timelimit', false);
 
 
update/90405.php DELETED
@@ -1,5 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('piwik_mode', 'http');
3
- self::$settings->setGlobalOption('piwik_path', '');
4
- self::$settings->setGlobalOption('toolbar', false);
5
- self::$settings->setGlobalOption('disable_cookies', false);
 
 
 
 
 
update/90601.php DELETED
@@ -1,3 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('piwik_useragent', 'php');
3
- self::$settings->setGlobalOption('piwik_useragent_string', 'WP-Piwik');
 
 
 
update/90700.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('shortcodes', false);
 
 
update/90801.php CHANGED
@@ -1,6 +1,4 @@
1
  <?php
2
- self::$settings->setGlobalOption('track_search', false);
3
- self::$settings->setGlobalOption('connection_timeout', 5);
4
  if (self::$settings->getGlobalOption('track_compress'))
5
  self::$settings->setGlobalOption('track_mode', 1);
6
  else
1
  <?php
 
 
2
  if (self::$settings->getGlobalOption('track_compress'))
3
  self::$settings->setGlobalOption('track_mode', 1);
4
  else
update/90821.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_cdnurl', '');
 
 
update/90910.php DELETED
@@ -1,3 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_cdnurlssl', self::$settings->getGlobalOption('track_cdnurl'));
3
- self::$settings->setGlobalOption('track_noscript', false);
 
 
 
update/90920.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('plugin_display_name', 'WP-Piwik');
 
 
update/90940.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_nojavascript', false);
 
 
update/90961.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('cache', true);
 
 
update/90971.php DELETED
@@ -1,3 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_admin', false);
3
- self::$settings->setGlobalOption('perpost_stats', false);
 
 
 
update/90980.php DELETED
@@ -1,6 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_feed', false);
3
- self::$settings->setGlobalOption('track_feed_goal', false);
4
- self::$settings->setGlobalOption('track_feed_revenue', false);
5
- self::$settings->setGlobalOption('track_feed_campaign', 'feed');
6
- self::$settings->setGlobalOption('track_feed_addcampaign', false);
 
 
 
 
 
 
update/91007.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- self::$settings->setGlobalOption('track_codeposition', 'footer');
 
 
update/index.php DELETED
@@ -1,2 +0,0 @@
1
- <?php
2
- // Nothing to see...
 
 
wp-piwik.php CHANGED
@@ -6,9 +6,12 @@ Plugin URI: http://wordpress.org/extend/plugins/wp-piwik/
6
 
7
  Description: Adds Piwik stats to your dashboard menu and Piwik code to your wordpress header.
8
 
9
- Version: 0.9.9.14
10
  Author: Andr&eacute; Br&auml;kling
11
  Author URI: http://www.braekling.de
 
 
 
12
 
13
  ******************************************************************************************
14
  Copyright (C) 2009-2015 Andre Braekling (email: webmaster@braekling.de)
@@ -33,1513 +36,31 @@ if (!function_exists ('add_action')) {
33
  exit();
34
  }
35
 
36
- //require_once(ABSPATH.'wp-includes/pluggable.php');
 
37
 
38
- if (!class_exists('wp_piwik')) {
39
- class wp_piwik {
40
-
41
- private static
42
- $intRevisionId = 94000,
43
- $strVersion = '0.9.9.13',
44
- $blog_id,
45
- $intDashboardID = 30,
46
- $strPluginBasename = NULL,
47
- $bolJustActivated = false,
48
- $logger,
49
- $settings;
50
-
51
- private
52
- $intStatsPage = NULL,
53
- $bolNetwork = false,
54
- $aryAttributes = array(),
55
- $strResult = '';
56
-
57
- public function __construct() {
58
- global $blog_id;
59
- self::$blog_id = (isset($blog_id)?$blog_id:'n/a');
60
- $this->openLogger();
61
- $this->openSettings();
62
- $this->setup();
63
- $this->addFilters();
64
- $this->addActions();
65
- $this->addShortcodes();
66
- self::$settings->save();
67
- }
68
-
69
- public function __destruct() {
70
- $this->closeLogger();
71
- }
72
-
73
- private function setup() {
74
- self::$strPluginBasename = plugin_basename(__FILE__);
75
- register_activation_hook(__FILE__, array($this, 'installPlugin'));
76
- if ($this->isUpdated())
77
- $this->upgradePlugin();
78
- if ($this->isConfigSubmitted())
79
- $this->applySettings();
80
- if ($this->isPHPMode())
81
- self::definePiwikConstants();
82
- if (is_admin())
83
- $this->loadLanguage();
84
- }
85
-
86
- private function addActions() {
87
- if (is_admin()) {
88
- add_action('admin_menu', array($this, 'buildAdminMenu'));
89
- add_action('admin_post_save_wp-piwik_stats', array(&$this, 'onStatsPageSaveChanges'));
90
- add_action('load-post.php', array(&$this, 'postMetaboxes'));
91
- add_action('load-post-new.php', array(&$this, 'postMetaboxes'));
92
- if ($this->isNetworkMode())
93
- add_action('network_admin_menu', array($this, 'buildNetworkAdminMenu'));
94
- if ($this->isDashboardActive())
95
- add_action('wp_dashboard_setup', array($this, 'extendWordPressDashboard'));
96
- if (self::$settings->getGlobalOption('add_post_annotations'))
97
- add_action('transition_post_status', array($this, 'onPostStatusTransition'),10,3);
98
- }
99
- if ($this->isToolbarActive()) {
100
- // is_admin_bar_showing() would be great to use, but it will break P3 Plugin Performance Profiler (https://wordpress.org/plugins/p3-profiler/)
101
- add_action(is_admin()?'admin_head':'wp_head', array($this, 'loadToolbarRequirements'));
102
- add_action('admin_bar_menu', array(&$this, 'extendWordPressToolbar'), 1000);
103
- }
104
- if ($this->isTrackingActive()) {
105
- if (!is_admin()) {
106
- add_action(self::$settings->getGlobalOption('track_codeposition') == 'footer'?'wp_footer':'wp_head', array($this, 'addJavascriptCode'));
107
- if ($this->isAddNoScriptCode())
108
- add_action('wp_footer', array($this, 'addNoscriptCode'));
109
- }
110
- else {
111
- if ($this->isAdminTrackingActive())
112
- add_action('admin_head', array($this, 'addAdminHeaderTracking'));
113
- }
114
- }
115
- }
116
-
117
- private function addFilters() {
118
- if (is_admin()) {
119
- add_filter('plugin_row_meta', array($this, 'setPluginMeta'), 10, 2);
120
- add_filter('screen_layout_columns', array(&$this, 'onScreenLayoutColumns'), 10, 2);
121
- }
122
- else {
123
- if ($this->isTrackingActive()) {
124
- if ($this->isTrackFeed()) {
125
- add_filter('the_excerpt_rss', array(&$this, 'addFeedTracking'));
126
- add_filter('the_content', array(&$this, 'addFeedTracking'));
127
- }
128
- if ($this->isAddFeedCampaign())
129
- add_filter('post_link', array(&$this, 'addFeedCampaign'));
130
- }
131
- }
132
- }
133
-
134
- private function addShortcodes() {
135
- if ($this->isAddShortcode())
136
- add_shortcode('wp-piwik', array(&$this, 'shortcode'));
137
- }
138
-
139
- private function loadLanguage() {
140
- load_plugin_textdomain('wp-piwik', false, dirname(self::$strPluginBasename)."/languages/");
141
- }
142
-
143
- function installPlugin() {
144
- self::$logger->log('Running WP-Piwik installation');
145
- add_action('admin_notices', array($this, 'updateMessage'));
146
- self::$bolJustActivated = true;
147
- self::$settings->setGlobalOption('revision', self::$intRevisionId);
148
- self::$settings->setGlobalOption('last_settings_update', time());
149
- }
150
-
151
- static function uninstallPlugin() {
152
- self::$logger->log('Running WP-Piwik uninstallation');
153
- if (!defined('WP_UNINSTALL_PLUGIN'))
154
- exit();
155
- self::$settings->resetSettings(true);
156
- }
157
-
158
- function upgradePlugin() {
159
- self::$logger->log('Upgrade WP-Piwik to '.self::$strVersion);
160
- add_action('admin_notices', array($this, 'updateMessage'));
161
- $patches = glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'update'.DIRECTORY_SEPARATOR.'*.php');
162
- if (is_array($patches)) {
163
- sort($patches);
164
- foreach ($patches as $patch) {
165
- $patchVersion = (int) pathinfo($patch, PATHINFO_FILENAME);
166
- if ($patchVersion && self::$settings->getGlobalOption('revision') < $patchVersion)
167
- self::includeFile('update'.DIRECTORY_SEPARATOR.$patchVersion);
168
- }
169
- }
170
- $this->installPlugin();
171
- }
172
-
173
- function updateMessage() {
174
- $text = sprintf(__('%s %s installed.', 'wp-piwik'), self::$settings->getGlobalOption('plugin_display_name'), self::$strVersion);
175
- $notice = (!self::isConfigured()?
176
- __('Next you should connect to Piwik','wp-piwik'):
177
- __('Please validate your configuration','wp-piwik')
178
- );
179
- $link = sprintf('<a href="'.$this->getSettingsURL().'?page=%s">%s</a>', self::$strPluginBasename, __('Settings', 'wp-piwik'));
180
- printf('<div class="updated fade"><p>%s<strong>%s:</strong> %s: %s</p></div>', $text, __('Important', 'wp-piwik'), $notice, $link);
181
- }
182
-
183
- function getSettingsURL() {
184
- return (self::$settings->checkNetworkActivation()?'settings':'options-general').'.php';
185
- }
186
-
187
- private function updateTrackingCode() {
188
- if (!self::$settings->getOption('site_id') || !self::$settings->getOption('tracking_code'))
189
- $this->addPiwikSite();
190
- if ($this->isCurrentTrackingCode()) {
191
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
192
- self::$settings->save();
193
- }
194
- }
195
-
196
- /* -- </REFACTORED><OLD> -- */
197
-
198
- function addJavascriptCode() {
199
- if ($this->isHiddenUser()) {
200
- self::$logger->log('Do not add tracking code to site header (user should not be tracked) Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
201
- return;
202
- }
203
- $this->updateTrackingCode();
204
-
205
- // Change code if 404
206
- if (is_404() && self::$settings->getGlobalOption('track_404')) {
207
- self::$logger->log('Apply 404 changes. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
208
- $strTrackingCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setDocumentTitle', '404/URL = '+String(document.location.pathname+document.location.search).replace(/\//g,'%2f') + '/From = ' + String(document.referrer).replace(/\//g,'%2f')]);\n_paq.push(['trackPageView']);", self::$settings->getOption('tracking_code'));
209
- }
210
- // Change code if search result
211
- elseif (is_search() && self::$settings->getGlobalOption('track_search')) {
212
- self::$logger->log('Apply search tracking changes. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
213
- $objSearch = new WP_Query("s=" . get_search_query() . '&showposts=-1');
214
- $intResultCount = $objSearch->post_count;
215
- $strTrackingCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['trackSiteSearch','".get_search_query()."', false, ".$intResultCount."]);\n_paq.push(['trackPageView']);", self::$settings->getOption('tracking_code'));
216
- // Use default tracking code
217
- } else
218
- $strTrackingCode = self::$settings->getOption('tracking_code');
219
- // Send tracking code
220
- self::$logger->log('Add tracking code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
221
- // Add custom variables if set:
222
- if (is_single()) {
223
- $strCustomVars = '';
224
- for ($i = 1; $i <= 5; $i++) {
225
- // Get post ID
226
- $intID = get_the_ID();
227
- // Get key
228
- $strMetaKey = get_post_meta($intID, 'wp-piwik_custom_cat'.$i, true);
229
- // Get value
230
- $strMetaVal = get_post_meta($intID, 'wp-piwik_custom_val'.$i, true);
231
- if (!empty($strMetaKey) && !empty($strMetaVal))
232
- $strCustomVars .= "_paq.push(['setCustomVariable',".$i.", '".$strMetaKey."', '".$strMetaVal."', 'page']);\n";
233
- }
234
- if (!empty($strCustomVars)) $strTrackingCode = str_replace("_paq.push(['trackPageView']);", $strCustomVars."_paq.push(['trackPageView']);", $strTrackingCode);
235
- }
236
- echo $strTrackingCode;
237
- $strName = get_bloginfo('name');
238
- if (self::$settings->getOption('name') != $strName)
239
- $this->updatePiwikSite();
240
- }
241
-
242
- function addNoscriptCode() {
243
- // Hotfix: Custom capability problem with WP multisite
244
- if (is_multisite()) {
245
- foreach (self::$settings->getGlobalOption('capability_stealth') as $strKey => $strVal)
246
- if ($strVal && current_user_can($strKey))
247
- return;
248
- // Don't add tracking code?
249
- } elseif (current_user_can('wp-piwik_stealth')) return;
250
- // Send tracking code
251
- self::$logger->log('Add noscript code. Blog ID: '.self::$blog_id.' Site ID: '.self::$settings->getOption('site_id'));
252
- echo self::$settings->getOption('noscript_code')."\n";
253
- }
254
-
255
- /**
256
- * Shortcode function
257
- **/
258
-
259
- function shortcode($aryAttributes) {
260
- $this->aryAttributes = shortcode_atts(
261
- array(
262
- 'title' => '',
263
- 'module' => 'overview',
264
- 'period' => 'day',
265
- 'date' => 'yesterday',
266
- 'limit' => 10,
267
- 'width' => '100%',
268
- 'height' => '200px',
269
- 'language' => 'en',
270
- 'range' => false,
271
- 'key' => 'sum_daily_nb_uniq_visitors'
272
- ), $aryAttributes);
273
- switch ($this->aryAttributes['module']) {
274
- case 'opt-out':
275
- $this->strResult = '<iframe frameborder="no" width="'.$this->aryAttributes['width'].'" height="'.$this->aryAttributes['height'].'" src="'.self::$settings->getGlobalOption('piwik_url').'index.php?module=CoreAdminHome&action=optOut&language='.$this->aryAttributes['language'].'"></iframe>';
276
- break;
277
- case 'post':
278
- self::includeFile('shortcodes/post');
279
- break;
280
- case 'overview':
281
- default:
282
- self::includeFile('shortcodes/overview');
283
- }
284
- return $this->strResult;
285
- }
286
-
287
- /**
288
- * Add metaboxes to posts
289
- */
290
- function postMetaboxes() {
291
- if (self::$settings->getGlobalOption('add_customvars_box')) {
292
- add_action('add_meta_boxes', array(&$this, 'postAddMetaboxes'));
293
- add_action('save_post', array(&$this, 'postCustomvarsSave'), 10, 2);
294
- }
295
- // Show per post stats if enabled
296
- if (self::$settings->getGlobalOption('perpost_stats')) {
297
- $this->includeFile('classes/WP_Piwik_MetaBox_PerPost_Stats');
298
- add_action('add_meta_boxes', array(new WP_Piwik_MetaBox_PerPost_Stats($this->subClassConfig()), 'addMetabox'));
299
- }
300
- }
301
-
302
- /**
303
- * Create post meta boxes
304
- */
305
- function postAddMetaboxes() {
306
- add_meta_box(
307
- 'wp-piwik_post_customvars',
308
- __('Piwik Custom Variables', 'wp-piwik'),
309
- array(&$this, 'postCustomvars'),
310
- 'post',
311
- 'side',
312
- 'default'
313
- );
314
- }
315
-
316
- /**
317
- * Display custom variables meta box
318
- */
319
- function postCustomvars($objPost, $objBox ) {
320
- wp_nonce_field(basename( __FILE__ ), 'wp-piwik_post_customvars_nonce'); ?>
321
- <table>
322
- <tr><th></th><th><?php _e('Name', 'wp-piwik'); ?></th><th><?php _e('Value', 'wp-piwik'); ?></th></tr>
323
- <?php for($i = 1; $i <= 5; $i++) { ?>
324
- <tr>
325
- <th><label for="wp-piwik_customvar1"><?php echo $i; ?>: </label></th>
326
- <td><input class="widefat" type="text" name="wp-piwik_custom_cat<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_cat'.$i, true ) ); ?>" size="200" /></td>
327
- <td><input class="widefat" type="text" name="wp-piwik_custom_val<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_val'.$i, true ) ); ?>" size="200" /></td>
328
- </tr>
329
- <?php } ?>
330
- </table>
331
- <p><?php _e('Set custom variables for a page view', 'wp-piwik'); ?>. (<a href="http://piwik.org/docs/custom-variables/"><?php _e('More information', 'wp-piwik'); ?></a>.)</p>
332
- <?php
333
- }
334
-
335
- /**
336
- * Save post custom variables
337
- */
338
- function postCustomvarsSave($intID, $objPost) {
339
- // Verify the nonce before proceeding.
340
- if (!isset( $_POST['wp-piwik_post_customvars_nonce'] ) || !wp_verify_nonce( $_POST['wp-piwik_post_customvars_nonce'], basename( __FILE__ ) ) )
341
- return $intID;
342
- // Get post type object
343
- $objPostType = get_post_type_object($objPost->post_type);
344
- // Check if the current user has permission to edit the post.
345
- if (!current_user_can($objPostType->cap->edit_post, $intID))
346
- return $intID;
347
- $aryNames = array('cat', 'val');
348
- for ($i = 1; $i <= 5; $i++)
349
- for ($j = 0; $j <= 1; $j++) {
350
- // Get data
351
- $strMetaVal = (isset($_POST['wp-piwik_custom_'.$aryNames[$j].$i])?htmlentities($_POST['wp-piwik_custom_'.$aryNames[$j].$i]):'');
352
- // Create key
353
- $strMetaKey = 'wp-piwik_custom_'.$aryNames[$j].$i;
354
- // Get the meta value of the custom field key
355
- $strCurVal = get_post_meta($intID, $strMetaKey, true);
356
- // Add meta val:
357
- if ($strMetaVal && '' == $strCurVal)
358
- add_post_meta($intID, $strMetaKey, $strMetaVal, true);
359
- // Update meta val:
360
- elseif ($strMetaVal && $strMetaVal != $strCurVal)
361
- update_post_meta($intID, $strMetaKey, $strMetaVal);
362
- // Delete meta val:
363
- elseif (''==$strMetaVal && $strCurVal)
364
- delete_post_meta($intID, $strMetaKey, $strCurVal);
365
- }
366
- }
367
-
368
- /**
369
- * Add pages to admin menu
370
- */
371
- function buildAdminMenu() {
372
- // Show stats dashboard page if WP-Piwik is configured
373
- if (self::isConfigured()) {
374
- // Add dashboard page
375
- $this->intStatsPage = add_dashboard_page(
376
- __('Piwik Statistics', 'wp-piwik'),
377
- self::$settings->getGlobalOption('plugin_display_name'),
378
- 'wp-piwik_read_stats',
379
- 'wp-piwik_stats',
380
- array($this, 'showStats')
381
- );
382
- // Add required scripts
383
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadStatsScripts'));
384
- // Add required styles
385
- add_action('admin_print_styles-'.$this->intStatsPage, array($this, 'addAdminStyle'));
386
- // Add required header tags
387
- add_action('admin_head-'.$this->intStatsPage, array($this, 'addAdminHeaderStats'));
388
- // Stats page onload callback
389
- add_action('load-'.$this->intStatsPage, array(&$this, 'onloadStatsPage'));
390
- }
391
- if (!self::$settings->checkNetworkActivation()) {
392
- // Add options page
393
- $intOptionsPage = add_options_page(
394
- self::$settings->getGlobalOption('plugin_display_name'),
395
- self::$settings->getGlobalOption('plugin_display_name'),
396
- 'activate_plugins',
397
- __FILE__,
398
- array($this, 'showSettings')
399
- );
400
- // Add required scripts
401
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadSettingsScripts'));
402
- // Add required header tags
403
- add_action('admin_head-'.$intOptionsPage, array($this, 'addAdminHeaderSettings'));
404
- // Add styles required by options page
405
- add_action('admin_print_styles-'.$intOptionsPage, array($this, 'addAdminStyle'));
406
- }
407
- }
408
-
409
- /**
410
- * Add pages to network admin menu
411
- */
412
- function buildNetworkAdminMenu() {
413
- // Show stats dashboard page if WP-Piwik is configured
414
- if (self::isConfigured()) {
415
- // Add dashboard page
416
- $this->intStatsPage = add_dashboard_page(
417
- __('Piwik Statistics', 'wp-piwik'),
418
- self::$settings->getGlobalOption('plugin_display_name'),
419
- 'manage_sites',
420
- 'wp-piwik_stats',
421
- array($this, 'showStatsNetwork')
422
- );
423
- // Add required scripts
424
- add_action('admin_print_scripts-'.$this->intStatsPage, array($this, 'loadStatsScripts'));
425
- // Add required styles
426
- add_action('admin_print_styles-'.$this->intStatsPage, array($this, 'addAdminStyle'));
427
- // Add required header tags
428
- add_action('admin_head-'.$this->intStatsPage, array($this, 'addAdminHeaderStats'));
429
- // Stats page onload callback
430
- add_action('load-'.$this->intStatsPage, array(&$this, 'onloadStatsPage'));
431
- }
432
- $intOptionsPage = add_submenu_page(
433
- 'settings.php',
434
- self::$settings->getGlobalOption('plugin_display_name'),
435
- self::$settings->getGlobalOption('plugin_display_name'),
436
- 'manage_sites',
437
- __FILE__,
438
- array($this, 'showSettings')
439
- );
440
-
441
- // Add styles required by options page
442
- add_action('admin_print_styles-'.$intOptionsPage, array($this, 'addAdminStyle'));
443
- add_action('admin_head-'.$intOptionsPage, array($this, 'addAdminHeaderSettings'));
444
- }
445
-
446
- /**
447
- * Support two columns
448
- * seen in Heiko Rabe's metabox demo plugin
449
- *
450
- * @see http://tinyurl.com/5r5vnzs
451
- */
452
- function onScreenLayoutColumns($aryColumns, $strScreen) {
453
- if ($strScreen == $this->intStatsPage)
454
- $aryColumns[$this->intStatsPage] = 3;
455
- return $aryColumns;
456
- }
457
-
458
- /**
459
- * Add widgets to WordPress dashboard
460
- */
461
- function extendWordPressDashboard() {
462
- // Is user allowed to see stats?
463
- if (current_user_can('wp-piwik_read_stats')) {
464
- // TODO: Use bitmask here
465
- // Add data widget if enabled
466
- if (self::$settings->getGlobalOption('dashboard_widget'))
467
- $this->addWordPressDashboardWidget();
468
- // Add chart widget if enabled
469
- if (self::$settings->getGlobalOption('dashboard_chart')) {
470
- // Add required scripts
471
- add_action('admin_print_scripts-index.php', array($this, 'loadStatsScripts'));
472
- // Add required styles
473
- add_action('admin_print_styles-index.php', array($this, 'addAdminStyle'));
474
- // Add required header tags
475
- add_action('admin_head-index.php', array($this, 'addAdminHeaderStats'));
476
- $this->addWordPressDashboardChart();
477
- }
478
- // Add SEO widget if enabled
479
- if (self::$settings->getGlobalOption('dashboard_seo'))
480
- $this->addWordPressDashboardSEO();
481
- }
482
- }
483
-
484
- /**
485
- * Add widgets to WordPress Toolbar
486
- */
487
- public function extendWordPressToolbar(&$objToolbar) {
488
- // Is user allowed to see stats?
489
- if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
490
- $aryUnique = $this->callPiwikAPI('VisitsSummary.getUniqueVisitors','day','last30',null);
491
- if (!is_array($aryUnique)) $aryUnique = array();
492
- $strGraph = '<script type="text/javascript">';
493
- $strGraph .= "var \$jSpark = jQuery.noConflict();\$jSpark(function() {var piwikSparkVals=[".implode(',',$aryUnique)."];\$jSpark('.wp-piwik_dynbar').sparkline(piwikSparkVals, {type: 'bar', barColor: '#ccc', barWidth:2});});";
494
- $strGraph .= '</script>';
495
- $strGraph .= '<span class="wp-piwik_dynbar">Loading...</span>';
496
- $objToolbar->add_menu(array(
497
- 'id' => 'wp-piwik_stats',
498
- 'title' => $strGraph,
499
- 'href' => admin_url().'?page=wp-piwik_stats'
500
- ));
501
- }
502
- }
503
-
504
- /**
505
- * Add a data widget to the WordPress dashboard
506
- */
507
- function addWordPressDashboardWidget() {
508
- $aryConfig = array(
509
- 'params' => array('period' => 'day','date' => self::$settings->getGlobalOption('dashboard_widget'),'limit' => null),
510
- 'inline' => true,
511
- );
512
- $strFile = 'overview';
513
- add_meta_box(
514
- 'wp-piwik_stats-dashboard-overview',
515
- self::$settings->getGlobalOption('plugin_display_name').' - '.__(self::$settings->getGlobalOption('dashboard_widget'), 'wp-piwik'),
516
- array(&$this, 'createDashboardWidget'),
517
- 'dashboard',
518
- 'side',
519
- 'high',
520
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
521
- );
522
- }
523
-
524
- /**
525
- * Add a visitor chart to the WordPress dashboard
526
- */
527
- function addWordPressDashboardChart() {
528
- $aryConfig = array(
529
- 'params' => array('period' => 'day','date' => 'last30','limit' => null),
530
- 'inline' => true,
531
- );
532
- $strFile = 'visitors';
533
- add_meta_box(
534
- 'wp-piwik_stats-dashboard-chart',
535
- self::$settings->getGlobalOption('plugin_display_name').' - '.__('Visitors', 'wp-piwik'),
536
- array(&$this, 'createDashboardWidget'),
537
- 'dashboard',
538
- 'side',
539
- 'high',
540
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
541
- );
542
- }
543
-
544
- /**
545
- * Add a SEO widget to the WordPress dashboard
546
- */
547
- function addWordPressDashboardSEO() {
548
- $aryConfig = array(
549
- 'params' => array('period' => 'day','date' => 'today','limit' => null),
550
- 'inline' => true,
551
- );
552
- $strFile = 'seo';
553
- add_meta_box(
554
- 'wp-piwik_stats-dashboard-seo',
555
- self::$settings->getGlobalOption('plugin_display_name').' - '.__('SEO', 'wp-piwik'),
556
- array(&$this, 'createDashboardWidget'),
557
- 'dashboard',
558
- 'side',
559
- 'high',
560
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
561
- );
562
- }
563
-
564
- /**
565
- * Add plugin meta links to plugin details
566
- *
567
- * @see http://wpengineer.com/1295/meta-links-for-wordpress-plugins/
568
- */
569
- function setPluginMeta($strLinks, $strFile) {
570
- // Get plugin basename
571
- $strPlugin = plugin_basename(__FILE__);
572
- // Add link just to this plugin's details
573
- if ($strFile == self::$strPluginBasename)
574
- return array_merge(
575
- $strLinks,
576
- array(
577
- sprintf('<a href="'.(self::$settings->checkNetworkActivation()?'settings':'options-general').'.php?page=%s">%s</a>', self::$strPluginBasename, __('Settings', 'wp-piwik'))
578
- )
579
- );
580
- // Don't affect other plugins details
581
- return $strLinks;
582
- }
583
-
584
- /**
585
- * Load required scripts to stats page
586
- */
587
- function loadStatsScripts() {
588
- // Load WP-Piwik script
589
- wp_enqueue_script('wp-piwik', $this->getPluginURL().'js/wp-piwik.js', array(), self::$strVersion, true);
590
- // Load jqPlot
591
- wp_enqueue_script('wp-piwik-jqplot',$this->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'));
592
- }
593
-
594
- /**
595
- * Load scripts required by Toolbar graphs
596
- */
597
- function loadToolbarRequirements() {
598
- // Only load if user is allowed to see stats
599
- if (current_user_can('wp-piwik_read_stats') && is_admin_bar_showing()) {
600
- // Load Sparklines
601
- wp_enqueue_script('wp-piwik-sparkline',$this->getPluginURL().'js/sparkline/jquery.sparkline.min.js',array('jquery'),'2.1.1');
602
- // Load CSS
603
- wp_enqueue_style('wp-piwik', $this->getPluginURL().'css/wp-piwik-spark.css');
604
- }
605
- }
606
-
607
- /**
608
- * Load required scripts to settings page
609
- */
610
- function loadSettingsScripts() {
611
- wp_enqueue_script('jquery');
612
- }
613
-
614
- /**
615
- * Load required styles to admin pages
616
- */
617
- function addAdminStyle() {
618
- // Load WP-Piwik styles
619
- wp_enqueue_style('wp-piwik', $this->getPluginURL().'css/wp-piwik.css',array(),self::$strVersion);
620
- }
621
-
622
- /**
623
- * Add tracking code to admin header
624
- */
625
- function addAdminHeaderTracking() {
626
- $this->site_header();
627
- }
628
-
629
- /**
630
- * Add tracking image to feeds
631
- **/
632
- function addFeedTracking($content) {
633
- global $post;
634
- if(is_feed()) {
635
- self::$logger->log('Add tracking image to feed entry.');
636
- if (!self::$settings->getOption('site_id'))
637
- self::addPiwikSite();
638
- $title = the_title(null,null,false);
639
- $posturl = get_permalink($post->ID);
640
- $urlref = get_bloginfo('rss2_url');
641
- $url = self::$settings->getGlobalOption('piwik_url');
642
- if (substr($url, -10, 10) == '/index.php')
643
- $url = str_replace('/index.php', '/piwik.php', $url);
644
- else $url .= 'piwik.php';
645
- $trackingImage = $url.'?idsite='.self::$settings->getOption('site_id').'&amp;rec=1'.
646
- '&amp;url='.urlencode($posturl).
647
- '&amp;action_name='.urlencode($title).
648
- '&amp;urlref='.urlencode($urlref);
649
- $content .= '<img src="'.$trackingImage.'" style="border:0;width:0;height:0" width="0" height="0" alt="" />';
650
- }
651
- return $content;
652
- }
653
-
654
- /**
655
- * Add tracking image to feeds
656
- **/
657
- function addFeedCampaign($permalink) {
658
- global $post;
659
- if(is_feed()) {
660
- self::$logger->log('Add campaign to feed permalink.');
661
- $sep = (strpos($permalink, '?') === false?'?':'&');
662
- $permalink .= $sep.'pk_campaign='.urlencode(self::$settings->getGlobalOption('track_feed_campaign')).'&pk_kwd='.urlencode($post->post_name);
663
- }
664
- return $permalink;
665
- }
666
-
667
- function addPiwikAnnotation($postID) {
668
- $this->callPiwikAPI('Annotations.add', '', date('Y-m-d'), '', false, false, 'PHP', '', false, 'Published: '.get_post($postID)->post_title.' - URL: '.get_permalink($postID));
669
- }
670
-
671
- /**
672
- * Add required header tags to stats page
673
- */
674
- function addAdminHeaderStats() {
675
- // Load jqPlot IE compatibility script
676
- echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.$this->getPluginURL().'js/jqplot/excanvas.min.js"></script><![endif]-->';
677
- // Load jqPlot styles
678
- echo '<link rel="stylesheet" href="'.$this->getPluginURL().'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
679
- echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
680
- }
681
-
682
- /**
683
- * Add required header tags to settings page
684
- */
685
- function addAdminHeaderSettings() {
686
- echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
687
- echo '<script type="text/javascript">/* <![CDATA[ */(function() {var s = document.createElement(\'script\');var t = document.getElementsByTagName(\'script\')[0];s.type = \'text/javascript\';s.async = true;s.src = \'//api.flattr.com/js/0.6/load.js?mode=auto\';t.parentNode.insertBefore(s, t);})();/* ]]> */</script>';
688
  }
689
-
690
- /**
691
- * Get this plugin's URL
692
- */
693
- function getPluginURL() {
694
- // Return plugins URL + /wp-piwik/
695
- return trailingslashit(plugins_url().'/wp-piwik/');
696
- }
697
-
698
- /**
699
- * Call REST API
700
- *
701
- * @param $strURL Remote file URL
702
- */
703
- function callREST($strURL) {
704
- $strPiwikURL = self::$settings->getGlobalOption('piwik_url');
705
- if (substr($strPiwikURL, -1, 1) != '/') $strPiwikURL .= '/';
706
- $strURL = $strPiwikURL.'?module=API'.$strURL;
707
- // Use cURL if available
708
- if (function_exists('curl_init')) {
709
- // Init cURL
710
- $c = curl_init($strURL);
711
- // Disable SSL peer verification if asked to
712
- curl_setopt($c, CURLOPT_SSL_VERIFYPEER, !self::$settings->getGlobalOption('disable_ssl_verify'));
713
- // Set user agent
714
- curl_setopt($c, CURLOPT_USERAGENT, self::$settings->getGlobalOption('piwik_useragent')=='php'?ini_get('user_agent'):self::$settings->getGlobalOption('piwik_useragent_string'));
715
- // Configure cURL CURLOPT_RETURNTRANSFER = 1
716
- curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
717
- // Configure cURL CURLOPT_HEADER = 0
718
- curl_setopt($c, CURLOPT_HEADER, 0);
719
- // Set cURL timeout
720
- curl_setopt($c, CURLOPT_TIMEOUT, self::$settings->getGlobalOption('connection_timeout'));
721
- $httpProxyClass = new WP_HTTP_Proxy();
722
- if ($httpProxyClass->is_enabled() && $httpProxyClass->send_through_proxy($strURL)) {
723
- curl_setopt($c, CURLOPT_PROXY, $httpProxyClass->host());
724
- curl_setopt($c, CURLOPT_PROXYPORT, $httpProxyClass->port());
725
- if ($httpProxyClass->use_authentication())
726
- curl_setopt($c, CURLOPT_PROXYUSERPWD, $httpProxyClass->username().':'.$httpProxyClass->password());
727
- }
728
- // Get result
729
- $strResult = curl_exec($c);
730
- // Close connection
731
- curl_close($c);
732
- // cURL not available but url fopen allowed
733
- } elseif (ini_get('allow_url_fopen')) {
734
- // Set timeout
735
- $resContext = stream_context_create(array('http'=>array('timeout' => self::$settings->getGlobalOption('connection_timeout'))));
736
- // Get file using file_get_contents
737
- $strResult = @file_get_contents($strURL, false, $strContext);
738
- // Error: Not possible to get remote file
739
- } else $strResult = serialize(array(
740
- 'result' => 'error',
741
- 'message' => 'Remote access to Piwik not possible. Enable allow_url_fopen or CURL.'
742
- ));
743
- // Return result
744
- return $strResult;
745
- }
746
-
747
- /**
748
- * Call PHP API
749
- *
750
- * @param $strParams API call params
751
- */
752
- function callPHP($strParams) {
753
- if (!defined('PIWIK_INCLUDE_PATH'))
754
- return;
755
- if (PIWIK_INCLUDE_PATH === FALSE)
756
- return serialize(array('result' => 'error', 'message' => __('Could not resolve','wp-piwik').' &quot;'.htmlentities(self::$settings->getGlobalOption('piwik_path')).'&quot;: '.__('realpath() returns false','wp-piwik').'.'));
757
- if (!headers_sent()) {
758
- $current = ob_get_contents();
759
- ob_end_clean();
760
- ob_start();
761
- }
762
- if (file_exists(PIWIK_INCLUDE_PATH . "/index.php"))
763
- require_once PIWIK_INCLUDE_PATH . "/index.php";
764
- if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php"))
765
- require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
766
- if (class_exists('Piwik\FrontController'))
767
- Piwik\FrontController::getInstance()->init();
768
- else serialize(array('result' => 'error', 'message' => __('Class Piwik\FrontController does not exists.','wp-piwik')));
769
- if (class_exists('Piwik\API\Request'))
770
- $objRequest = new Piwik\API\Request($strParams);
771
- else serialize(array('result' => 'error', 'message' => __('Class Piwik\API\Request does not exists.','wp-piwik')));
772
- if (!headers_sent()) {
773
- ob_end_clean();
774
- ob_start;
775
- echo $current;
776
- }
777
- return $objRequest->process();
778
- }
779
-
780
- /**
781
- * Get remote file
782
- *
783
- * @param String $strURL Remote file URL
784
- */
785
- function getRemoteFile($strURL, $blogURL = '') {
786
- if (self::$settings->getGlobalOption('piwik_mode') == 'php')
787
- return $this->callPHP($strURL.($blogURL?'&url='.$blogURL:''));
788
- else
789
- return $this->callREST($strURL.($blogURL?'&url='.urlencode($blogURL):''));
790
- }
791
-
792
- /**
793
- * Add a new site to Piwik if a new blog was requested,
794
- * or get its ID by URL
795
- */
796
- function addPiwikSite() {
797
- if (isset($_GET['wpmu_show_stats']) && self::$settings->checkNetworkActivation()) {
798
- self::$logger->log('Switch blog ID: '.(int) $_GET['wpmu_show_stats']);
799
- switch_to_blog((int) $_GET['wpmu_show_stats']);
800
- }
801
- self::$logger->log('Get the blog\'s site ID by URL: '.get_bloginfo('url'));
802
- // Check if blog URL already known
803
- $strURL = '&method=SitesManager.getSitesIdFromSiteUrl';
804
- $strURL .= '&format=PHP';
805
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
806
- $aryResult = unserialize($this->getRemoteFile($strURL, get_bloginfo('url')));
807
- if (!empty($aryResult) && isset($aryResult[0]['idsite'])) {
808
- self::$settings->setOption('site_id', (int) $aryResult[0]['idsite']);
809
- // Otherwise create new site
810
- } elseif (self::isConfigured() && !empty($strURL)) {
811
- self::$logger->log('Blog not known yet - create new site');
812
- $strName = get_bloginfo('name');
813
- if (empty($strName)) $strName = get_bloginfo('url');
814
- self::$settings->setOption('name', $strName);
815
- $strURL .= '&method=SitesManager.addSite';
816
- $strURL .= '&siteName='.urlencode($strName).'&urls='.urlencode(get_bloginfo('url'));
817
- $strURL .= '&format=PHP';
818
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
819
- $strResult = unserialize($this->getRemoteFile($strURL, get_bloginfo('url')));
820
- if (!empty($strResult)) self::$settings->setOption('site_id', (int) $strResult);
821
- }
822
- // Store new data if site created
823
- if (self::$settings->getOption('site_id')) {
824
- self::$logger->log('Get the site\'s tracking code');
825
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
826
- } else self::$settings->getOption('tracking_code', '');
827
- self::$settings->save();
828
- if (isset($_GET['wpmu_show_stats']) && self::$settings->checkNetworkActivation()) {
829
- self::$logger->log('Back to current blog');
830
- restore_current_blog();
831
- }
832
- return array('js' => self::$settings->getOption('tracking_code'), 'id' => self::$settings->getOption('site_id'));
833
- }
834
-
835
- /**
836
- * Update a site
837
- */
838
- function updatePiwikSite() {
839
- $strBlogURL = get_bloginfo('url');
840
- // Check if blog URL already known
841
- $strName = get_bloginfo('name');
842
- if (empty($strName)) $strName = $strBlogURL;
843
- self::$settings->setOption('name', $strName);
844
- $strURL = '&method=SitesManager.updateSite';
845
- $strURL .= '&idSite='.self::$settings->getOption('site_id');
846
- $strURL .= '&siteName='.urlencode($strName).'&urls='.urlencode($strBlogURL);
847
- $strURL .= '&format=PHP';
848
- $strURL .= '&token_auth='.self::$settings->getGlobalOption('piwik_token');
849
- $strResult = unserialize($this->getRemoteFile($strURL));
850
- // Store new data
851
- self::$settings->getOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
852
- self::$settings->save();
853
- }
854
-
855
- /**
856
- * Apply configured Tracking Code changes
857
- */
858
- function applyJSCodeChanges($strCode) {
859
- self::$logger->log('Apply tracking code changes.');
860
- self::$settings->setOption('last_tracking_code_update', time());
861
- $strCode = html_entity_decode($strCode);
862
- // Change code if js/index.php should be used
863
- if (self::$settings->getGlobalOption('track_mode') == 1) {
864
- $strCode = str_replace('piwik.js', 'js/index.php', $strCode);
865
- $strCode = str_replace('piwik.php', 'js/index.php', $strCode);
866
- } elseif (self::$settings->getGlobalOption('track_mode') == 2) {
867
- $strCode = str_replace('piwik.js', 'piwik.php', $strCode);
868
- $strURL = str_replace('https://', '//', self::$settings->getGlobalOption('piwik_url'));
869
- $strURL = str_replace('http://', '//', $strURL);
870
- $strProxy = str_replace('https://', '//', plugins_url('wp-piwik'));
871
- $strProxy = str_replace('http://', '//', $strProxy);
872
- $strProxy .= '/';
873
- $strCode = str_replace($strURL, $strProxy, $strCode);
874
- }
875
- $strCode = str_replace('//";','/"',$strCode);
876
- if (self::$settings->getGlobalOption('track_cdnurl')||self::$settings->getGlobalOption('track_cdnurlssl')) {
877
- $strCode = str_replace("var d=doc", "var ucdn=(('https:' == document.location.protocol) ? 'https://".(self::$settings->getGlobalOption('track_cdnurlssl')?self::$settings->getGlobalOption('track_cdnurlssl'):self::$settings->getGlobalOption('track_cdnurl'))."/' : 'http://".(self::$settings->getGlobalOption('track_cdnurl')?self::$settings->getGlobalOption('track_cdnurl'):self::$settings->getGlobalOption('track_cdnurlssl'))."/');\nvar d=doc", $strCode);
878
- $strCode = str_replace("g.src=u+", "g.src=ucdn+", $strCode);
879
- }
880
- // Change code if POST is forced to be used
881
- if (self::$settings->getGlobalOption('track_post') && self::$settings->getGlobalOption('track_mode') != 2) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setRequestMethod', 'POST']);\n_paq.push(['trackPageView']);", $strCode);
882
- // Change code if cookies are disabled
883
- if (self::$settings->getGlobalOption('disable_cookies')) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['disableCookies']);\n_paq.push(['trackPageView']);", $strCode);
884
- if (self::$settings->getGlobalOption('limit_cookies')) $strCode = str_replace("_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '".self::$settings->getGlobalOption('limit_cookies_visitor')."']);\n_paq.push(['setSessionCookieTimeout', '".self::$settings->getGlobalOption('limit_cookies_session')."']);\n_paq.push(['trackPageView']);", $strCode);
885
- // Store <noscript> code
886
- $aryNoscript = array();
887
- preg_match('/<noscript>(.*)<\/noscript>/', $strCode, $aryNoscript);
888
- if (isset($aryNoscript[0])) {
889
- if (self::$settings->getGlobalOption('track_nojavascript'))
890
- $aryNoscript[0] = str_replace('?idsite', '?rec=1&idsite', $aryNoscript[0]);
891
- self::$settings->setOption('noscript_code', $aryNoscript[0]);
892
- }
893
- if (self::$settings->getGlobalOption('track_datacfasync'))
894
- $strCode = str_replace('<script type', '<script data-cfasync="false" type', $strCode);
895
- // Remove <noscript> code
896
- $strCode = preg_replace('/<noscript>(.*)<\/noscript>/', '', $strCode);
897
- // Return code without empty lines
898
- return preg_replace('/\s+(\r\n|\r|\n)/', '$1', $strCode);
899
- }
900
-
901
- /**
902
- * Create a WordPress dashboard widget
903
- */
904
- function createDashboardWidget($objPost, $aryMetabox) {
905
- // Create description and ID
906
- $strDesc = $strID = '';
907
- $aryConfig = $aryMetabox['args']['aryConfig'];
908
- foreach ($aryConfig['params'] as $strParam)
909
- if (!empty($strParam)) {
910
- $strDesc .= $strParam.', ';
911
- $strID .= '_'.$strParam;
912
- }
913
- // Remove dots from filename
914
- $strFile = str_replace('.', '', $aryMetabox['args']['strFile']);
915
- // Finalize configuration
916
- $aryConf = array_merge($aryConfig, array(
917
- 'id' => $strFile.$strID,
918
- 'desc' => substr($strDesc, 0, -2)));
919
- // Include widget file
920
- if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'dashboard/'.$strFile.'.php'))
921
- include(dirname(__FILE__).DIRECTORY_SEPARATOR.'dashboard/'.$strFile.'.php');
922
- }
923
-
924
- /**
925
- * Call Piwik's API
926
- */
927
- function callPiwikAPI($strMethod, $strPeriod='', $strDate='', $intLimit='',$bolExpanded=false, $intId = false, $strFormat = 'PHP', $strPageURL = '', $useCache = true, $strNote = '') {
928
- // Create unique cache key
929
- $strKey = 'wp-piwik_'.md5($strMethod.'_'.$strPeriod.'_'.$strDate.'_'.$intLimit.'_'.self::$settings->getGlobalOption('piwik_token').'_'.self::$settings->getGlobalOption('piwik_url').'_'.$intId.'_'.$strPageURL);
930
- // Call API if data not cached
931
- if (self::$settings->getGlobalOption('cache') && $useCache) {
932
- $result = get_transient($strKey);
933
- self::$logger->log('API method: '.$strMethod.' Fetch call from cache: '.$strKey);
934
- } else $result = false;
935
- if ($strMethod == "SitesManager.getSitesWithAtLeastViewAccess" || false === $result) {
936
- $strToken = self::$settings->getGlobalOption('piwik_token');
937
- // If multisite stats are shown, maybe the super admin wants to show other blog's stats.
938
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && function_exists('wp_get_current_user') && is_super_admin() && isset($_GET['wpmu_show_stats'])) {
939
- $aryOptions = get_blog_option((int) $_GET['wpmu_show_stats'], 'wp-piwik_settings' , array());
940
- if (!empty($aryOptions) && isset($aryOptions['site_id']))
941
- $intSite = $aryOptions['site_id'];
942
- else $intSite = self::$settings->getOption('site_id');
943
- // Otherwise use the current site's id.
944
- } else {
945
- if (!self::$settings->getOption('site_id'))
946
- self::addPiwikSite();
947
- $intSite = self::$settings->getOption('site_id');
948
- }
949
- //die($intSite);
950
- // Create error message if WP-Piwik isn't configured
951
- if (!self::isConfigured()) {
952
- $result = array(
953
- 'result' => 'error',
954
- 'message' => 'Piwik URL/path or auth token not set.'
955
- );
956
- return $result;
957
- }
958
- // Build URL
959
- $strURL = '&method='.$strMethod;
960
- $strURL .= '&idSite='.(int)$intSite.'&period='.$strPeriod.'&date='.$strDate;
961
- $strURL .= '&filter_limit='.$intLimit;
962
- $strURL .= '&token_auth='.$strToken;
963
- $strURL .= '&expanded='.$bolExpanded;
964
- $strURL .= '&format='.$strFormat;
965
- $strURL .= ($strPageURL?'&pageUrl='.urlencode($strPageURL):'');
966
- $strURL .= ($strNote?'&note='.urlencode($strNote):'');
967
- if (self::$settings->getGlobalOption('track_across') && $strMethod == 'SitesManager.getJavascriptTag') {
968
- $strURL .= '&mergeSubdomains=1';
969
- }
970
- if (self::$settings->getGlobalOption('track_across_alias') && $strMethod == 'SitesManager.getJavascriptTag') {
971
- $strURL .= '&mergeAliasUrls=1';
972
- }
973
- // Fetch data if site exists
974
- if (!empty($intSite) || $strMethod=='SitesManager.getSitesWithAtLeastViewAccess') {
975
- self::$logger->log('API method: '.$strMethod.' API call: '.$strURL);
976
- $strResult = (string) $this->getRemoteFile($strURL, get_bloginfo('url'));
977
- $result = ($strFormat == 'PHP'?unserialize($strResult):$strResult);
978
- // Apply tracking code changes if configured
979
- if ($strMethod == 'SitesManager.getJavascriptTag' && !empty($result)) {
980
- $result = is_string($result)?$this->applyJSCodeChanges($result):'<!-- WP-Piwik ERROR: Tracking code not availbale -->'."\n";
981
- }
982
- // Otherwise return error message
983
- } else $result = array('result' => 'error', 'message' => 'Unknown site/blog.');
984
- if (
985
- $strMethod != 'SitesManager.getJavascriptTag' &&
986
- $strDate != 'today' && $strDate != date('Ymd') && substr($strDate, 0, 4) != 'last' &&
987
- self::$settings->getGlobalOption('cache') &&
988
- !(isset($result['result']) && $result['result'] == 'error')&&
989
- !empty($result)
990
- ) set_transient($strKey, $result, WEEK_IN_SECONDS);
991
- }
992
- return $result;
993
- }
994
-
995
- /* TODO: Add post stats
996
- * function display_post_unique_column($aryCols) {
997
- * $aryCols['wp-piwik_unique'] = __('Unique');
998
- * return $aryCols;
999
- * }
1000
- *
1001
- * function display_post_unique_content($strCol, $intID) {
1002
- * if( $strCol == 'wp-piwik_unique' ) {
1003
- * }
1004
- * }
1005
- */
1006
-
1007
- function onloadStatsPage() {
1008
- wp_enqueue_script('common');
1009
- wp_enqueue_script('wp-lists');
1010
- wp_enqueue_script('postbox');
1011
- $strToken = self::$settings->getGlobalOption('piwik_token');
1012
- $strPiwikURL = self::$settings->getGlobalOption('piwik_url');
1013
- $aryDashboard = array();
1014
- // Set default configuration
1015
- $arySortOrder = array(
1016
- 'side' => array(
1017
- 'overview' => array(__('Overview', 'wp-piwik'), 'day', 'yesterday'),
1018
- 'seo' => array(__('SEO', 'wp-piwik'), 'day', 'yesterday'),
1019
- 'pages' => array(__('Pages', 'wp-piwik'), 'day', 'yesterday'),
1020
- 'keywords' => array(__('Keywords', 'wp-piwik'), 'day', 'yesterday', 10),
1021
- 'websites' => array(__('Websites', 'wp-piwik'), 'day', 'yesterday', 10),
1022
- 'plugins' => array(__('Plugins', 'wp-piwik'), 'day', 'yesterday'),
1023
- 'search' => array(__('Site Search Keywords', 'wp-piwik'), 'day', 'yesterday', 10),
1024
- 'noresult' => array(__('Site Search without Results', 'wp-piwik'), 'day', 'yesterday', 10),
1025
- ),
1026
- 'normal' => array(
1027
- 'visitors' => array(__('Visitors', 'wp-piwik'), 'day', 'last30'),
1028
- 'browsers' => array(__('Browser', 'wp-piwik'), 'day', 'yesterday'),
1029
- 'browserdetails' => array(__('Browser Details', 'wp-piwik'), 'day', 'yesterday'),
1030
- 'screens' => array(__('Resolution', 'wp-piwik'), 'day', 'yesterday'),
1031
- 'systems' => array(__('Operating System', 'wp-piwik'), 'day', 'yesterday')
1032
- )
1033
- );
1034
- // Don't show SEO stats if disabled
1035
- if (!self::$settings->getGlobalOption('stats_seo'))
1036
- unset($arySortOrder['side']['seo']);
1037
-
1038
- foreach ($arySortOrder as $strCol => $aryWidgets) {
1039
- if (is_array($aryWidgets)) foreach ($aryWidgets as $strFile => $aryParams) {
1040
- $aryDashboard[$strCol][$strFile] = array(
1041
- 'params' => array(
1042
- 'title' => (isset($aryParams[0])?$aryParams[0]:$strFile),
1043
- 'period' => (isset($aryParams[1])?$aryParams[1]:''),
1044
- 'date' => (isset($aryParams[2])?$aryParams[2]:''),
1045
- 'limit' => (isset($aryParams[3])?$aryParams[3]:'')
1046
- )
1047
- );
1048
- if (isset($_GET['date']) && preg_match('/^[0-9]{8}$/', $_GET['date']) && $strFile != 'visitors')
1049
- $aryDashboard[$strCol][$strFile]['params']['date'] = $_GET['date'];
1050
- elseif ($strFile != 'visitors')
1051
- $aryDashboard[$strCol][$strFile]['params']['date'] = self::$settings->getGlobalOption('default_date');
1052
- }
1053
- }
1054
- $intSideBoxCnt = $intContentBox = 0;
1055
- foreach ($aryDashboard['side'] as $strFile => $aryConfig) {
1056
- $intSideBoxCnt++;
1057
- if (preg_match('/(\d{4})(\d{2})(\d{2})/', $aryConfig['params']['date'], $aryResult))
1058
- $strDate = $aryResult[1]."-".$aryResult[2]."-".$aryResult[3];
1059
- else $strDate = $aryConfig['params']['date'];
1060
- add_meta_box(
1061
- 'wp-piwik_stats-sidebox-'.$intSideBoxCnt,
1062
- $aryConfig['params']['title'].' '.($aryConfig['params']['title']!='SEO'?__($strDate, 'wp-piwik'):''),
1063
- array(&$this, 'createDashboardWidget'),
1064
- $this->intStatsPage,
1065
- 'side',
1066
- 'core',
1067
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
1068
- );
1069
- }
1070
- foreach ($aryDashboard['normal'] as $strFile => $aryConfig) {
1071
- if (preg_match('/(\d{4})(\d{2})(\d{2})/', $aryConfig['params']['date'], $aryResult))
1072
- $strDate = $aryResult[1]."-".$aryResult[2]."-".$aryResult[3];
1073
- else $strDate = $aryConfig['params']['date'];
1074
- $intContentBox++;
1075
- add_meta_box(
1076
- 'wp-piwik_stats-contentbox-'.$intContentBox,
1077
- $aryConfig['params']['title'].' '.($aryConfig['params']['title']!='SEO'?__($strDate, 'wp-piwik'):''),
1078
- array(&$this, 'createDashboardWidget'),
1079
- $this->intStatsPage,
1080
- 'normal',
1081
- 'core',
1082
- array('strFile' => $strFile, 'aryConfig' => $aryConfig)
1083
- );
1084
- }
1085
- }
1086
-
1087
- // Open stats page as network admin
1088
- function showStatsNetwork() {
1089
- $this->bolNetwork = true;
1090
- $this->showStats();
1091
- }
1092
-
1093
- function showStats() {
1094
- // Disabled time limit if required
1095
- if (self::$settings->getGlobalOption('disable_timelimit') && self::$settings->getGlobalOption('disable_timelimit'))
1096
- set_time_limit(0);
1097
- //we need the global screen column value to be able to have a sidebar in WordPress 2.8
1098
- global $screen_layout_columns;
1099
- if (empty($screen_layout_columns)) $screen_layout_columns = 2;
1100
- /***************************************************************************/ ?>
1101
- <div id="wp-piwik-stats-general" class="wrap">
1102
- <?php screen_icon('options-general'); ?>
1103
- <h2><?php echo (self::$settings->getGlobalOption('plugin_display_name') == 'WP-Piwik'?'Piwik '.__('Statistics', 'wp-piwik'):self::$settings->getGlobalOption('plugin_display_name')); ?></h2>
1104
- <?php /************************************************************************/
1105
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin() && $this->bolNetwork) {
1106
- if (isset($_GET['wpmu_show_stats'])) {
1107
- switch_to_blog((int) $_GET['wpmu_show_stats']);
1108
- // TODO OPTIMIZE
1109
- } else {
1110
- $this->includeFile('settings/sitebrowser');
1111
- return;
1112
- }
1113
- echo '<p>'.__('Currently shown stats:').' <a href="'.get_bloginfo('url').'">'.(int) $_GET['wpmu_show_stats'].' - '.get_bloginfo('name').'</a>.'.' <a href="?page=wp-piwik_stats">Show site overview</a>.</p>'."\n";
1114
- echo '</form>'."\n";
1115
- }
1116
- /***************************************************************************/ ?>
1117
- <form action="admin-post.php" method="post">
1118
- <?php wp_nonce_field('wp-piwik_stats-general'); ?>
1119
- <?php wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false ); ?>
1120
- <?php wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?>
1121
- <input type="hidden" name="action" value="save_wp-piwik_stats_general" />
1122
- <div id="dashboard-widgets" class="metabox-holder columns-<?php echo $screen_layout_columns; ?><?php echo 2 <= $screen_layout_columns?' has-right-sidebar':''; ?>">
1123
- <div id='postbox-container-1' class='postbox-container'>
1124
- <?php $meta_boxes = do_meta_boxes($this->intStatsPage, 'normal', null); ?>
1125
- </div>
1126
-
1127
- <div id='postbox-container-2' class='postbox-container'>
1128
- <?php do_meta_boxes($this->intStatsPage, 'side', null); ?>
1129
- </div>
1130
-
1131
- <div id='postbox-container-3' class='postbox-container'>
1132
- <?php do_meta_boxes($this->intStatsPage, 'column3', null); ?>
1133
- </div>
1134
-
1135
- </div>
1136
- </form>
1137
- </div>
1138
- <script type="text/javascript">
1139
- //<![CDATA[
1140
- jQuery(document).ready( function($) {
1141
- // close postboxes that should be closed
1142
- $('.if-js-closed').removeClass('if-js-closed').addClass('closed');
1143
- // postboxes setup
1144
- postboxes.add_postbox_toggles('<?php echo $this->intStatsPage; ?>');
1145
- });
1146
- //]]>
1147
- </script>
1148
- <?php /************************************************************************/
1149
- if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
1150
- restore_current_blog();
1151
- }
1152
- }
1153
-
1154
- /* Stats page changes by POST submit
1155
- seen in Heiko Rabe's metabox demo plugin
1156
- http://tinyurl.com/5r5vnzs */
1157
- function onStatsPageSaveChanges() {
1158
- //user permission check
1159
- if ( !current_user_can('manage_options') )
1160
- wp_die( __('Cheatin&#8217; uh?') );
1161
- //cross check the given referer
1162
- check_admin_referer('wp-piwik_stats');
1163
- //process here your on $_POST validation and / or option saving
1164
- //lets redirect the post request into get request (you may add additional params at the url, if you need to show save results
1165
- wp_redirect($_POST['_wp_http_referer']);
1166
- }
1167
-
1168
- /**
1169
- * Add tabs to settings page
1170
- * See http://wp.smashingmagazine.com/2011/10/20/create-tabs-wordpress-settings-pages/
1171
- */
1172
- function showSettingsTabs($bolFull = true, $strCurr = 'homepage') {
1173
- $aryTabs = ($bolFull?array(
1174
- 'homepage' => __('Home','wp-piwik'),
1175
- 'piwik' => __('Piwik Settings','wp-piwik'),
1176
- 'tracking' => __('Tracking','wp-piwik'),
1177
- 'views' => __('Statistics','wp-piwik'),
1178
- 'support' => __('Support','wp-piwik'),
1179
- 'credits' => __('Credits','wp-piwik')
1180
- ):array(
1181
- 'piwik' => __('Piwik Settings','wp-piwik'),
1182
- 'support' => __('Support','wp-piwik'),
1183
- 'credits' => __('Credits','wp-piwik')
1184
- ));
1185
- if (empty($strCurr)) $strCurr = 'homepage';
1186
- elseif (!isset($aryTabs[$strCurr]) && $strCurr != 'sitebrowser') $strCurr = 'piwik';
1187
- echo '<div id="icon-themes" class="icon32"><br></div>';
1188
- echo '<h2 class="nav-tab-wrapper">';
1189
- foreach($aryTabs as $strTab => $strName) {
1190
- $strClass = ($strTab == $strCurr?' nav-tab-active':'');
1191
- echo '<a class="nav-tab'.$strClass.'" href="?page=wp-piwik/wp-piwik.php&tab='.$strTab.'">'.$strName.'</a>';
1192
- }
1193
- echo '</h2>';
1194
- return $strCurr;
1195
- }
1196
-
1197
- /**
1198
- * Apply & store new settings
1199
- */
1200
- function applySettings() {
1201
- $strTab = (isset($_GET['tab'])?$_GET['tab']:'homepage');
1202
- self::$logger->log('Apply changes: '.$strTab);
1203
- switch ($strTab) {
1204
- case 'views':
1205
- self::$settings->setGlobalOption('plugin_display_name', (!empty($_POST['wp-piwik_displayname'])?htmlentities($_POST['wp-piwik_displayname']):'WP-Piwk'));
1206
- self::$settings->setGlobalOption('dashboard_widget',(isset($_POST['wp-piwik_dbwidget'])?$_POST['wp-piwik_dbwidget']:0));
1207
- self::$settings->setGlobalOption('dashboard_chart',(isset($_POST['wp-piwik_dbchart'])?$_POST['wp-piwik_dbchart']:false));
1208
- self::$settings->setGlobalOption('dashboard_seo',(isset($_POST['wp-piwik_dbseo'])?$_POST['wp-piwik_dbseo']:false));
1209
- self::$settings->setGlobalOption('stats_seo',(isset($_POST['wp-piwik_statsseo'])?$_POST['wp-piwik_statsseo']:false));
1210
- self::$settings->setGlobalOption('piwik_shortcut', (isset($_POST['wp-piwik_piwiklink'])?$_POST['wp-piwik_piwiklink']:false));
1211
- self::$settings->setGlobalOption('default_date', (isset($_POST['wp-piwik_default_date'])?$_POST['wp-piwik_default_date']:'yesterday'));
1212
- self::$settings->setGlobalOption('capability_read_stats', (isset($_POST['wp-piwik_displayto'])?$_POST['wp-piwik_displayto']:array()));
1213
- self::$settings->setGlobalOption('disable_timelimit', (isset($_POST['wp-piwik_disabletimelimit'])?$_POST['wp-piwik_disabletimelimit']:false));
1214
- self::$settings->setGlobalOption('toolbar', (isset($_POST['wp-piwik_toolbar'])?$_POST['wp-piwik_toolbar']:false));
1215
- self::$settings->setGlobalOption('shortcodes', (isset($_POST['wp-piwik_shortcodes'])?$_POST['wp-piwik_shortcodes']:false));
1216
- self::$settings->setGlobalOption('perpost_stats', (isset($_POST['wp-piwik_perpost'])?$_POST['wp-piwik_perpost']:false));
1217
- break;
1218
- case 'tracking':
1219
- self::$settings->setGlobalOption('add_tracking_code', (isset($_POST['wp-piwik_addjs'])?$_POST['wp-piwik_addjs']:false));
1220
- self::$settings->setGlobalOption('track_404', (isset($_POST['wp-piwik_404'])?$_POST['wp-piwik_404']:false));
1221
- self::$settings->setGlobalOption('track_search', (isset($_POST['wp-piwik_search'])?$_POST['wp-piwik_search']:false));
1222
- self::$settings->setGlobalOption('track_mode', (isset($_POST['wp-piwik_trackingmode'])?(int)$_POST['wp-piwik_trackingmode']:0));
1223
- self::$settings->setGlobalOption('track_post', (isset($_POST['wp-piwik_reqpost'])?$_POST['wp-piwik_reqpost']:false));
1224
- self::$settings->setGlobalOption('track_proxy', (isset($_POST['wp-piwik_proxy'])?$_POST['wp-piwik_proxy']:false));
1225
- self::$settings->setGlobalOption('track_cdnurl', trim(isset($_POST['wp-piwik_cdnurl'])?$_POST['wp-piwik_cdnurl']:''));
1226
- self::$settings->setGlobalOption('track_cdnurlssl', trim(isset($_POST['wp-piwik_cdnurlssl'])?$_POST['wp-piwik_cdnurlssl']:self::$settings->getGlobalOption('track_cdnurl')));
1227
- self::$settings->setGlobalOption('track_noscript', (isset($_POST['wp-piwik_noscript'])?$_POST['wp-piwik_noscript']:false));
1228
- self::$settings->setGlobalOption('track_codeposition', (isset($_POST['wp-piwik_codeposition'])?$_POST['wp-piwik_codeposition']:'footer'));
1229
- self::$settings->setGlobalOption('track_nojavascript', (isset($_POST['wp-piwik_nojavascript'])?$_POST['wp-piwik_nojavascript']:false));
1230
- self::$settings->setGlobalOption('track_admin', (isset($_POST['wp-piwik_trackadmin'])?$_POST['wp-piwik_trackadmin']:false));
1231
- self::$settings->setGlobalOption('track_feed', (isset($_POST['wp-piwik_trackfeed'])?$_POST['wp-piwik_trackfeed']:false));
1232
- self::$settings->setGlobalOption('track_feed_goal', (isset($_POST['wp-piwik_trackfeed_goal'])&&!empty($_POST['wp-piwik_trackfeed_goal'])?(int)$_POST['wp-piwik_trackfeed_goal']:''));
1233
- self::$settings->setGlobalOption('track_feed_revenue', (isset($_POST['wp-piwik_trackfeed_revenue'])&&!empty($_POST['wp-piwik_trackfeed_revenue'])?(int)$_POST['wp-piwik_trackfeed_revenue']:''));
1234
- self::$settings->setGlobalOption('track_feed_campaign', (isset($_POST['wp-piwik_trackfeed_campaign'])?$_POST['wp-piwik_trackfeed_campaign']:'feed'));
1235
- self::$settings->setGlobalOption('track_feed_addcampaign', (isset($_POST['wp-piwik_trackfeed_addcampaign'])?$_POST['wp-piwik_trackfeed_addcampaign']:false));
1236
- self::$settings->setGlobalOption('track_datacfasync', (isset($_POST['wp-piwik_datacfasync'])?$_POST['wp-piwik_datacfasync']:false));
1237
- self::$settings->setGlobalOption('track_across', (isset($_POST['wp-piwik_track_across'])?$_POST['wp-piwik_track_across']:false));
1238
- self::$settings->setGlobalOption('track_across_alias', (isset($_POST['wp-piwik_track_across_alias'])?$_POST['wp-piwik_track_across_alias']:false));
1239
- self::$settings->setGlobalOption('add_post_annotations', (isset($_POST['wp-piwik_annotations'])?$_POST['wp-piwik_annotations']:false));
1240
- self::$settings->setGlobalOption('add_customvars_box', (isset($_POST['wp-piwik_customvars'])?$_POST['wp-piwik_customvars']:false));
1241
- self::$settings->setGlobalOption('capability_stealth', (isset($_POST['wp-piwik_filter'])?$_POST['wp-piwik_filter']:array()));
1242
- self::$settings->setGlobalOption('disable_cookies', (isset($_POST['wp-piwik_disable_cookies'])?$_POST['wp-piwik_disable_cookies']:false));
1243
- self::$settings->setGlobalOption('limit_cookies', (isset($_POST['wp-piwik_limit_cookies'])?$_POST['wp-piwik_limit_cookies']:false));
1244
- self::$settings->setGlobalOption('limit_cookies_visitor', (isset($_POST['wp-piwik_limit_cookies_visitor'])?(int)$_POST['wp-piwik_limit_cookies_visitor']:1209600));
1245
- self::$settings->setGlobalOption('limit_cookies_session', (isset($_POST['wp-piwik_limit_cookies_session'])?(int)$_POST['wp-piwik_limit_cookies_session']:0));
1246
- self::$settings->setOption('tracking_code', $this->callPiwikAPI('SitesManager.getJavascriptTag'));
1247
- break;
1248
- case 'piwik':
1249
- self::$settings->setGlobalOption('piwik_token', (isset($_POST['wp-piwik_token'])?$_POST['wp-piwik_token']:''));
1250
- self::$settings->setGlobalOption('piwik_url', self::checkURL((isset($_POST['wp-piwik_url'])?$_POST['wp-piwik_url']:'')));
1251
- self::$settings->setGlobalOption('piwik_path', (isset($_POST['wp-piwik_path']) && !empty($_POST['wp-piwik_path'])?realpath($_POST['wp-piwik_path']):''));
1252
- self::$settings->setGlobalOption('cache', (isset($_POST['wp-piwik_cache'])?$_POST['wp-piwik_cache']:false));
1253
- self::$settings->setGlobalOption('piwik_mode', (isset($_POST['wp-piwik_mode'])?$_POST['wp-piwik_mode']:'http'));
1254
- self::$settings->setGlobalOption('piwik_useragent', (isset($_POST['wp-piwik_useragent'])?$_POST['wp-piwik_useragent']:'php'));
1255
- self::$settings->setGlobalOption('connection_timeout', (isset($_POST['wp-piwik_timeout'])?(int)$_POST['wp-piwik_timeout']:5));
1256
- self::$settings->setGlobalOption('piwik_useragent_string', (isset($_POST['wp-piwik_useragent_string'])?$_POST['wp-piwik_useragent_string']:'WP-Piwik'));
1257
- self::$settings->setGlobalOption('disable_ssl_verify', (isset($_POST['wp-piwik_disable_ssl_verify'])?$_POST['wp-piwik_disable_ssl_verify']:false));
1258
- if (!self::$settings->checkNetworkActivation()) {
1259
- self::$settings->setGlobalOption('auto_site_config', (isset($_POST['wp-piwik_auto_site_config'])?$_POST['wp-piwik_auto_site_config']:false));
1260
- if (!self::$settings->getGlobalOption('auto_site_config'))
1261
- self::$settings->setOption('site_id', (isset($_POST['wp-piwik_siteid'])?$_POST['wp-piwik_siteid']:self::$settings->getOption('site_id')));
1262
- } else self::$settings->setGlobalOption('auto_site_config', true);
1263
- break;
1264
- }
1265
- if (self::$settings->getGlobalOption('auto_site_config') && self::isConfigured()) {
1266
- if (self::$settings->getGlobalOption('piwik_mode') == 'php' && !defined('PIWIK_INCLUDE_PATH'))
1267
- self::definePiwikConstants();
1268
- $aryReturn = $this->addPiwikSite();
1269
- self::$settings->getOption('tracking_code', $aryReturn['js']);
1270
- self::$settings->getOption('site_id', $aryReturn['id']);
1271
- }
1272
- self::$settings->setGlobalOption('last_settings_update', time());
1273
- }
1274
-
1275
- /**
1276
- * Check & prepare URL
1277
- */
1278
- static function checkURL($strURL) {
1279
- if (empty($strURL)) return '';
1280
- if (substr($strURL, -1, 1) != '/' && substr($strURL, -10, 10) != '/index.php')
1281
- $strURL .= '/';
1282
- return $strURL;
1283
- }
1284
-
1285
- /**
1286
- * Show settings page
1287
- */
1288
- function showSettings() {
1289
- // Define globals and get request vars
1290
- global $pagenow;
1291
- $strTab = (isset($_GET['tab'])?$_GET['tab']:'homepage');
1292
- // Show update message if stats saved
1293
- if (isset($_POST['wp-piwik_settings_submit']) && $_POST['wp-piwik_settings_submit'] == 'Y')
1294
- echo '<div id="message" class="updated fade"><p>'.__('Changes saved','wp-piwik').'</p></div>';
1295
- // Show settings page title
1296
- echo '<div class="wrap"><h2>'.self::$settings->getGlobalOption('plugin_display_name').' '.__('Settings', 'wp-piwik').'</h2>';
1297
- // Show tabs
1298
- $strTab = $this->showSettingsTabs(self::isConfigured(), $strTab);
1299
- if ($strTab != 'sitebrowser') {
1300
- /***************************************************************************/ ?>
1301
- <div class="wp-piwik-donate">
1302
- <p><strong><?php _e('Donate','wp-piwik'); ?></strong></p>
1303
- <p><?php _e('If you like WP-Piwik, you can support its development by a donation:', 'wp-piwik'); ?></p>
1304
- <script type="text/javascript">
1305
- /* <![CDATA[ */
1306
- window.onload = function() {
1307
- FlattrLoader.render({
1308
- 'uid': 'flattr',
1309
- 'url': 'http://wp.local',
1310
- 'title': 'Title of the thing',
1311
- 'description': 'Description of the thing'
1312
- }, 'element_id', 'replace');
1313
- }
1314
- /* ]]> */
1315
- </script>
1316
- <div>
1317
- <a class="FlattrButton" style="display:none;" title="WordPress Plugin WP-Piwik" rel="flattr;uid:braekling;category:software;tags:wordpress,piwik,plugin,statistics;" href="https://www.braekling.de/wp-piwik-wpmu-piwik-wordpress">This WordPress plugin adds a Piwik stats site to your WordPress dashboard. It's also able to add the Piwik tracking code to your blog using wp_footer. You need a running Piwik installation and at least view access to your stats.</a>
1318
- </div>
1319
- <div>Paypal
1320
- <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
1321
- <input type="hidden" name="cmd" value="_s-xclick" />
1322
- <input type="hidden" name="hosted_button_id" value="6046779" />
1323
- <input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donateCC_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." />
1324
- <img alt="" border="0" src="https://www.paypal.com/de_DE/i/scr/pixel.gif" width="1" height="1" />
1325
- </form>
1326
- </div>
1327
- <div>
1328
- <a href="http://www.amazon.de/gp/registry/wishlist/111VUJT4HP1RA?reveal=unpurchased&amp;filter=all&amp;sort=priority&amp;layout=standard&amp;x=12&amp;y=14"><?php _e('My Amazon.de wishlist', 'wp-piwik'); ?></a>
1329
- </div>
1330
- <div>
1331
- <?php _e('Please don\'t forget to vote the compatibility at the','wp-piwik'); ?> <a href="http://wordpress.org/extend/plugins/wp-piwik/">WordPress.org Plugin Directory</a>.
1332
- </div>
1333
- </div>
1334
- <?php /***************************************************************************/
1335
- }
1336
- echo '<form class="'.($strTab != 'sitebrowser'?'wp-piwik-settings':'').'" method="post" action="'.admin_url(($pagenow == 'settings.php'?'network/':'').$pagenow.'?page=wp-piwik/wp-piwik.php&tab='.$strTab).'">';
1337
- echo '<input type="hidden" name="action" value="save_wp-piwik_settings" />';
1338
- wp_nonce_field('wp-piwik_settings');
1339
- // Show settings
1340
- if (($pagenow == 'options-general.php' || $pagenow == 'settings.php') && $_GET['page'] == 'wp-piwik/wp-piwik.php') {
1341
- echo '<table class="wp-piwik-form-table form-table">';
1342
- // Get tab contents
1343
- require_once('settings/'.$strTab.'.php');
1344
- // Show submit button
1345
- if (!in_array($strTab, array('homepage','credits','support','sitebrowser')))
1346
- echo '<tr><td><p class="submit" style="clear: both;padding:0;margin:0"><input type="submit" name="Submit" class="button-primary" value="'.__('Save settings', 'wp-piwik').'" /><input type="hidden" name="wp-piwik_settings_submit" value="Y" /></p></td></tr>';
1347
- echo '</table>';
1348
- }
1349
- // Close form
1350
- echo '</form></div>';
1351
- }
1352
-
1353
- /**
1354
- * Check if SSL is used
1355
- */
1356
- private static function isSSL() {
1357
- return (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off');
1358
- }
1359
-
1360
- /**
1361
- * Show an error message extended by a support site link
1362
- */
1363
- private static function showErrorMessage($strMessage) {
1364
- echo '<strong class="wp-piwik-error">'.__('An error occured', 'wp-piwik').':</strong> '.$strMessage.' [<a href="'.(self::$settings->checkNetworkActivation()?'network/settings':'options-general').'.php?page=wp-piwik/wp-piwik.php&tab=support">'.__('Support','wp-piwik').'</a>]';
1365
- }
1366
-
1367
- /**
1368
- * Read a RSS feed
1369
- */
1370
- private static function readRSSFeed($strFeedURL, $intCount = 5) {
1371
- $aryResult = array();
1372
- if (function_exists('simplexml_load_file') && !empty($strFeedURL)) {
1373
- $objXML = @simplexml_load_file($strFeedURL);
1374
- if (empty($strFeedURL) || !$objXML || !isset($objXML->channel[0]->item))
1375
- return array(array('title' => 'Can\'t read RSS feed.','url' => $strFeedURL));
1376
- foreach($objXML->channel[0]->item as $objItem) {
1377
- if( $intCount-- == 0 ) break;
1378
- $aryResult[] = array('title' => $objItem->title[0], 'url' => $objItem->link[0]);
1379
- }
1380
- }
1381
- return $aryResult;
1382
- }
1383
-
1384
- /**
1385
- * Execute test script
1386
- */
1387
- private static function loadTestscript() {
1388
- require_once('debug/testscript.php');
1389
- }
1390
-
1391
- /**
1392
- * Get a blog's piwik ID
1393
- */
1394
- public static function getSiteID($intBlogID = null) {
1395
- $intResult = self::$settings->getOption('site_id');
1396
- if (self::$settings->checkNetworkActivation() && !empty($intBlogID)) {
1397
- $aryResult = get_blog_option($intBlogID, 'wp-piwik_settings');
1398
- $intResult = $aryResult['site_id'];
1399
- }
1400
- return (is_int($intResult)?$intResult:'n/a');
1401
- }
1402
-
1403
- public static function isConfigured() {
1404
- return (
1405
- self::$settings->getGlobalOption('piwik_token')
1406
- && (
1407
- (
1408
- (self::$settings->getGlobalOption('piwik_mode') == 'http') && (self::$settings->getGlobalOption('piwik_url'))
1409
- ) || (
1410
- (self::$settings->getGlobalOption('piwik_mode') == 'php') && (self::$settings->getGlobalOption('piwik_path'))
1411
- )
1412
- )
1413
- );
1414
- }
1415
-
1416
- private function isUpdated() {
1417
- return self::$settings->getGlobalOption('revision') && self::$settings->getGlobalOption('revision') < self::$intRevisionId;
1418
- }
1419
-
1420
- private function isConfigSubmitted() {
1421
- return isset($_POST['action']) && $_POST['action'] == 'save_wp-piwik_settings';
1422
- }
1423
-
1424
- private function isPHPMode() {
1425
- return self::$settings->getGlobalOption('piwik_mode') && self::$settings->getGlobalOption('piwik_mode') == 'php';
1426
- }
1427
-
1428
- private function isNetworkMode() {
1429
- return self::$settings->checkNetworkActivation();
1430
- }
1431
-
1432
- private function isDashboardActive() {
1433
- return self::$settings->getGlobalOption('dashboard_widget') || self::$settings->getGlobalOption('dashboard_chart') || self::$settings->getGlobalOption('dashboard_seo');
1434
- }
1435
-
1436
- private function isToolbarActive() {
1437
- return self::$settings->getGlobalOption('toolbar');
1438
- }
1439
-
1440
- private function isTrackingActive() {
1441
- return self::$settings->getGlobalOption('add_tracking_code');
1442
- }
1443
-
1444
- private function isAdminTrackingActive() {
1445
- return self::$settings->getGlobalOption('track_admin');
1446
- }
1447
-
1448
- private function isAddNoScriptCode() {
1449
- return self::$settings->getGlobalOption('track_noscript');
1450
- }
1451
-
1452
- private function isTrackFeed() {
1453
- return self::$settings->getGlobalOption('track_feed');
1454
- }
1455
-
1456
- private function isAddFeedCampaign() {
1457
- return self::$settings->getGlobalOption('track_feed_addcampaign');
1458
- }
1459
-
1460
- private function isAddShortcode() {
1461
- return self::$settings->getGlobalOption('shortcodes');
1462
- }
1463
-
1464
- private static function definePiwikConstants() {
1465
- if (!defined('PIWIK_INCLUDE_PATH')) {
1466
- @header('Content-type: text/xml');
1467
- define('PIWIK_INCLUDE_PATH', self::$settings->getGlobalOption('piwik_path'));
1468
- define('PIWIK_USER_PATH', self::$settings->getGlobalOption('piwik_path'));
1469
- define('PIWIK_ENABLE_DISPATCH', false);
1470
- define('PIWIK_ENABLE_ERROR_HANDLER', false);
1471
- define('PIWIK_ENABLE_SESSION_START', false);
1472
- }
1473
- }
1474
-
1475
- private function openLogger() {
1476
- switch (WP_PIWIK_ACTIVATE_LOGGER) {
1477
- case 2:
1478
- require_once('classes/WP_Piwik_Logger_File.php');
1479
- self::$logger = new WP_Piwik_Logger_File(__CLASS__);
1480
- break;
1481
- default:
1482
- require_once('classes/WP_Piwik_Logger_Dummy.php');
1483
- self::$logger = new WP_Piwik_Logger_Dummy(__CLASS__);
1484
- }
1485
- }
1486
-
1487
- private function closeLogger() {
1488
- self::$logger = null;
1489
- }
1490
-
1491
- private function openSettings() {
1492
- $this->includeFile('classes/WP_Piwik_Settings');
1493
- self::$settings = new WP_Piwik_Settings(self::$logger);
1494
- }
1495
-
1496
- private function subClassConfig() {
1497
- return array(
1498
- 'wp_piwik' => $this,
1499
- 'logger' => self::$logger,
1500
- 'settings' => self::$settings
1501
- );
1502
- }
1503
-
1504
- private function includeFile($strFile) {
1505
- self::$logger->log('Include '.$strFile.'.php');
1506
- if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.$strFile.'.php'))
1507
- include(dirname(__FILE__).DIRECTORY_SEPARATOR.$strFile.'.php');
1508
- }
1509
-
1510
- private function isHiddenUser() {
1511
- if (is_multisite())
1512
- foreach (self::$settings->getGlobalOption('capability_stealth') as $key => $val)
1513
- if ($val && current_user_can($key)) return true;
1514
- return current_user_can('wp-piwik_stealth');
1515
- }
1516
-
1517
- private function isCurrentTrackingCode() {
1518
- return (self::$settings->getOption('last_tracking_code_update') < self::$settings->getGlobalOption('last_settings_update'));
1519
- }
1520
-
1521
- function site_header() {
1522
- self::$logger->log('Using deprecated function site_header');
1523
- $this->addJavascriptCode();
1524
- }
1525
-
1526
- function site_footer() {
1527
- self::$logger->log('Using deprecated function site_footer');
1528
- $this->addNoscriptCode();
1529
- }
1530
-
1531
- public function onPostStatusTransition($newStatus, $oldStatus, $post) {
1532
- if ($newStatus == 'publish' && $oldStatus != 'publish' ) {
1533
- add_action('publish_post', array($this, 'addPiwikAnnotation'));
1534
- }
1535
- }
1536
-
1537
- }
1538
  }
1539
 
1540
- require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'config.php');
1541
-
1542
- if (class_exists('wp_piwik'))
1543
- $GLOBALS['wp_piwik'] = new wp_piwik();
 
1544
 
1545
- /* EOF */
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  Description: Adds Piwik stats to your dashboard menu and Piwik code to your wordpress header.
8
 
9
+ Version: 0.10.0.0
10
  Author: Andr&eacute; Br&auml;kling
11
  Author URI: http://www.braekling.de
12
+ Text Domain: wp-piwik
13
+ Domain Path: /languages/
14
+ License: GPL3
15
 
16
  ******************************************************************************************
17
  Copyright (C) 2009-2015 Andre Braekling (email: webmaster@braekling.de)
36
  exit();
37
  }
38
 
39
+ if (!defined('NAMESPACE_SEPARATOR'))
40
+ define('NAMESPACE_SEPARATOR', '\\');
41
 
42
+ function wp_piwik_autoloader($class) {
43
+ if (substr($class, 0, 9) == 'WP_Piwik'.NAMESPACE_SEPARATOR) {
44
+ $class = str_replace('.', '', str_replace(NAMESPACE_SEPARATOR, DIRECTORY_SEPARATOR, substr($class, 9)));
45
+ require_once('classes'.DIRECTORY_SEPARATOR.'WP_Piwik'.DIRECTORY_SEPARATOR.$class.'.php');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  }
48
 
49
+ function wp_piwik_phperror($class) {
50
+ echo '<div class="error"><p>';
51
+ printf(__('WP-Piwik requires at least PHP 5.3. You are using the deprecated version %s. Please update PHP to use WP-Piwik.', 'wp-piwik'), PHP_VERSION);
52
+ echo '</p></div>';
53
+ }
54
 
55
+ load_plugin_textdomain('wp-piwik', false, 'wp-piwik'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR);
56
+
57
+ if (version_compare(PHP_VERSION, '5.3.0', '<'))
58
+ add_action('admin_notices', 'wp_piwik_phperror');
59
+ else {
60
+ define('WP_PIWIK_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
61
+ require_once(WP_PIWIK_PATH.'config.php');
62
+ require_once(WP_PIWIK_PATH.'classes'.DIRECTORY_SEPARATOR.'WP_Piwik.php');
63
+ spl_autoload_register('wp_piwik_autoloader');
64
+ if (class_exists('WP_Piwik'))
65
+ $GLOBALS['wp-piwik'] = new WP_Piwik();
66
+ }