WP_Piwik.php 43.7 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

/**
 * The main WP-Piwik class configures, registers and manages the plugin
 *
 * @author Andr&eacute; Br&auml;kling <webmaster@braekling.de>
 * @package WP_Piwik
 */
class WP_Piwik {

	/**
	 *
	 * @var Runtime environment variables
	 */
lucha's avatar
lucha committed
15
	private static $revisionId = 2017101501, $version = '1.0.19', $blog_id, $pluginBasename = NULL, $logger, $settings, $request, $optionsPageId;
ale's avatar
ale committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

	/**
	 * Constructor class to configure and register all WP-Piwik components
	 */
	public function __construct() {
		global $blog_id;
		self::$blog_id = (isset ( $blog_id ) ? $blog_id : 'n/a');
		$this->openLogger ();
		$this->openSettings ();
		$this->setup ();
		$this->addFilters ();
		$this->addActions ();
		$this->addShortcodes ();
	}

	/**
	 * Destructor class to finish logging
	 */
	public function __destruct() {
		$this->closeLogger ();
	}

	/**
	 * Setup class to prepare settings and check for installation and update
	 */
	private function setup() {
		self::$pluginBasename = plugin_basename ( __FILE__ );
		if (! $this->isInstalled ())
			$this->installPlugin ();
		elseif ($this->isUpdated ())
			$this->updatePlugin ();
		if ($this->isConfigSubmitted ())
			$this->applySettings ();
		self::$settings->save ();
	}

	/**
	 * Register WordPress actions
	 */
	private function addActions() {
		if ( is_admin () ) {
			add_action ( 'admin_menu', array (
					$this,
					'buildAdminMenu'
			) );
			add_action ( 'admin_post_save_wp-piwik_stats', array (
					$this,
					'onStatsPageSaveChanges'
			) );
			add_action ( 'load-post.php', array (
					$this,
					'addPostMetaboxes'
			) );
			add_action ( 'load-post-new.php', array (
					$this,
					'addPostMetaboxes'
			) );
			if ($this->isNetworkMode ()) {
				add_action ( 'network_admin_notices', array (
						$this,
						'showNotices'
				) );
				add_action ( 'network_admin_menu', array (
						$this,
						'buildNetworkAdminMenu'
				) );
				add_action ( 'update_site_option_blogname', array (
						$this,
						'onBlogNameChange'
				) );
				add_action ( 'update_site_option_siteurl', array (
						$this,
						'onSiteUrlChange'
				) );
			} else {
				add_action ( 'admin_notices', array (
						$this,
						'showNotices'
				) );
				add_action ( 'update_option_blogname', array (
						$this,
						'onBlogNameChange'
				) );
				add_action ( 'update_option_siteurl', array (
						$this,
						'onSiteUrlChange'
				) );
			}
			if ($this->isDashboardActive ())
				add_action ( 'wp_dashboard_setup', array (
						$this,
						'extendWordPressDashboard'
				) );
		}
		if ($this->isToolbarActive ()) {
			add_action ( is_admin () ? 'admin_head' : 'wp_head', array (
					$this,
					'loadToolbarRequirements'
			) );
			add_action ( 'admin_bar_menu', array (
					$this,
					'extendWordPressToolbar'
			), 1000 );
		}
		if ($this->isTrackingActive ()) {
lucha's avatar
lucha committed
121
122
123
			if ( !is_admin () || $this->isAdminTrackingActive ()) {
			    $prefix = is_admin ()?'admin':'wp';
				add_action ( self::$settings->getGlobalOption ( 'track_codeposition' ) == 'footer' ? $prefix.'_footer' : $prefix.'_head', array (
ale's avatar
ale committed
124
125
126
						$this,
						'addJavascriptCode'
					) );
lucha's avatar
lucha committed
127
128
129
130
131
                if (self::$settings->getGlobalOption ( 'dnsprefetch' ))
                    add_action ( $prefix.'_head', array (
                        $this,
                        'addDNSPrefetchTag'
                    ) );
ale's avatar
ale committed
132
				if ($this->isAddNoScriptCode ())
lucha's avatar
lucha committed
133
					add_action ( $prefix.'_footer', array (
ale's avatar
ale committed
134
135
136
							$this,
							'addNoscriptCode'
					) );
lucha's avatar
lucha committed
137
			}
lucha's avatar
lucha committed
138
139
140
141
142
			if (self::$settings->getGlobalOption ( 'add_post_annotations' ))
				add_action ( 'transition_post_status', array (
						$this,
						'addPiwikAnnotation'
				), 10, 3 );
ale's avatar
ale committed
143
		}
lucha's avatar
lucha committed
144
		
ale's avatar
ale committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
	}

	/**
	 * Register WordPress filters
	 */
	private function addFilters() {
		if (is_admin()) {
			add_filter ( 'plugin_row_meta', array (
					$this,
					'setPluginMeta'
			), 10, 2 );
			add_filter ( 'screen_layout_columns', array (
					$this,
					'onScreenLayoutColumns'
			), 10, 2 );
		} elseif ($this->isTrackingActive ()) {
			if ($this->isTrackFeed ()) {
				add_filter ( 'the_excerpt_rss', array (
						$this,
						'addFeedTracking'
				) );
				add_filter ( 'the_content', array (
						$this,
						'addFeedTracking'
				) );
			}
lucha's avatar
lucha committed
171
			if ($this->isAddFeedCampaign ()) {
ale's avatar
ale committed
172
173
174
175
				add_filter ( 'post_link', array (
						$this,
						'addFeedCampaign'
				) );
lucha's avatar
lucha committed
176
177
178
179
180
181
182
			}
			if ($this->isCrossDomainLinkingEnabled ()) {
				add_filter ( 'wp_redirect', array (
					$this,
					'forwardCrossDomainVisitorId'
				) );
			}
ale's avatar
ale committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
		}
	}

	/**
	 * Register WordPress shortcodes
	 */
	private function addShortcodes() {
		if ($this->isAddShortcode ())
			add_shortcode ( 'wp-piwik', array (
					$this,
					'shortcode'
			) );
	}

	/**
	 * Install WP-Piwik for the first time
	 */
	private function installPlugin($isUpdate = false) {
		self::$logger->log ( 'Running WP-Piwik installation' );
		if (! $isUpdate)
			$this->addNotice ( 'install', sprintf ( __ ( '%s %s installed.', 'wp-piwik' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), self::$version ), __ ( 'Next you should connect to Piwik', 'wp-piwik' ) );
		self::$settings->setGlobalOption ( 'revision', self::$revisionId );
		self::$settings->setGlobalOption ( 'last_settings_update', time () );
	}

	/**
	 * Uninstall WP-Piwik
	 */
	public static function uninstallPlugin() {
		self::$logger->log ( 'Running WP-Piwik uninstallation' );
		if (! defined ( 'WP_UNINSTALL_PLUGIN' ))
			exit ();
		$this->deleteWordPressOption ( 'wp-piwik-notices' );
		self::$settings->resetSettings ( true );
	}

	/**
	 * Update WP-Piwik
	 */
	private function updatePlugin() {
		self::$logger->log ( 'Upgrade WP-Piwik to ' . self::$version );
		$patches = glob ( dirname ( __FILE__ ) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'update' . DIRECTORY_SEPARATOR . '*.php' );
		$isPatched = false;
		if (is_array ( $patches )) {
			sort ( $patches );
			foreach ( $patches as $patch ) {
				$patchVersion = ( int ) pathinfo ( $patch, PATHINFO_FILENAME );
				if ($patchVersion && self::$settings->getGlobalOption ( 'revision' ) < $patchVersion) {
					self::includeFile ( 'update' . DIRECTORY_SEPARATOR . $patchVersion );
					$isPatched = true;
				}
			}
		}
		if ((self::$settings->getGlobalOption('update_notice') == 'enabled') || ((self::$settings->getGlobalOption('update_notice') == 'script') && $isPatched))
			$this->addNotice ( 'update', sprintf ( __ ( '%s updated to %s.', 'wp-piwik' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), self::$version ), __ ( 'Please validate your configuration', 'wp-piwik' ) );
		$this->installPlugin ( true );
	}

	/**
	 * Define a notice
	 *
	 * @param string $type
	 *        	identifier
	 * @param string $subject
	 *        	notice headline
	 * @param string $text
	 *        	notice content
	 * @param boolean $stay
	 *        	set to true if the message should persist (default: false)
	 */
	private function addNotice($type, $subject, $text, $stay = false) {
		$notices = $this->getWordPressOption ( 'wp-piwik-notices', array () );
		$notices [$type] = array (
				'subject' => $subject,
				'text' => $text,
				'stay' => $stay
		);
		$this->updateWordPressOption ( 'wp-piwik-notices', $notices );
	}

	/**
	 * Show all notices defined previously
	 *
	 * @see addNotice()
	 */
	public function showNotices() {
		$link = sprintf ( '<a href="' . $this->getSettingsURL () . '">%s</a>', __ ( 'Settings', 'wp-piwik' ) );
		if ($notices = $this->getWordPressOption ( 'wp-piwik-notices' )) {
			foreach ( $notices as $type => $notice ) {
				printf ( '<div class="updated fade"><p>%s <strong>%s:</strong> %s: %s</p></div>', $notice ['subject'], __ ( 'Important', 'wp-piwik' ), $notice ['text'], $link );
				if (! $notice ['stay'])
					unset ( $notices [$type] );
			}
		}
		$this->updateWordPressOption ( 'wp-piwik-notices', $notices );
	}

	/**
	 * Get the settings page URL
	 *
	 * @return string settings page URL
	 */
	private function getSettingsURL() {
		return (self::$settings->checkNetworkActivation () ? 'settings' : 'options-general') . '.php?page=' . self::$pluginBasename;
	}

	/**
	 * Echo javascript tracking code
	 */
	public function addJavascriptCode() {
		if ($this->isHiddenUser ()) {
			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' ) );
			return;
		}
		$trackingCode = new WP_Piwik\TrackingCode ( $this );
		$trackingCode->is404 = (is_404 () && self::$settings->getGlobalOption ( 'track_404' ));
lechuck's avatar
lechuck committed
299
		$trackingCode->isUsertracking = self::$settings->getGlobalOption ( 'track_user_id' ) != 'disabled';
ale's avatar
ale committed
300
301
302
303
304
305
306
307
308
309
310
311
		$trackingCode->isSearch = (is_search () && self::$settings->getGlobalOption ( 'track_search' ));
		self::$logger->log ( 'Add tracking code. Blog ID: ' . self::$blog_id . ' Site ID: ' . self::$settings->getOption ( 'site_id' ) );
		if ($this->isNetworkMode () && self::$settings->getGlobalOption ( 'track_mode' ) == 'manually') {
			$siteId = $this->getPiwikSiteId ();
			if ($siteId != 'n/a')
				echo str_replace ( '{ID}', $siteId, $trackingCode->getTrackingCode () );
			else
				echo '<!-- Site will be created and tracking code added on next request -->';
		} else
			echo $trackingCode->getTrackingCode ();
	}

lucha's avatar
lucha committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    /**
     * Echo DNS prefetch tag
     */
    public function addDNSPrefetchTag() {
        echo '<link rel="dns-prefetch" href="'.$this->getPiwikDomain().'" />';
    }

    /**
     * Get Piwik Domain
     */
    public function getPiwikDomain() {
        switch (self::$settings->getGlobalOption ( 'piwik_mode' )) {
            case 'php' :
                return '//' . parse_url(self::$settings->getGlobalOption ( 'proxy_url' ), PHP_URL_HOST);
            case 'cloud' :
                return '//' . self::$settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud';
            default :
                return '//' . parse_url(self::$settings->getGlobalOption ( 'piwik_url' ), PHP_URL_HOST);
        }
    }

ale's avatar
ale committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
	/**
	 * Echo noscript tracking code
	 */
	public function addNoscriptCode() {
		if (self::$settings->getGlobalOption ( 'track_mode' ) == 'proxy')
			return;
		if ($this->isHiddenUser ()) {
			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' ) );
			return;
		}
		self::$logger->log ( 'Add noscript code. Blog ID: ' . self::$blog_id . ' Site ID: ' . self::$settings->getOption ( 'site_id' ) );
		echo self::$settings->getOption ( 'noscript_code' ) . "\n";
	}

	/**
	 * Register post view meta boxes
	 */
	public function addPostMetaboxes() {
		if (self::$settings->getGlobalOption ( 'add_customvars_box' )) {
			add_action ( 'add_meta_boxes', array (
					new WP_Piwik\Template\MetaBoxCustomVars ( $this, self::$settings ),
					'addMetabox'
			) );
			add_action ( 'save_post', array (
					new WP_Piwik\Template\MetaBoxCustomVars ( $this, self::$settings ),
					'saveCustomVars'
			), 10, 2 );
		}
		if (self::$settings->getGlobalOption ( 'perpost_stats' )) {
			add_action ( 'add_meta_boxes', array (
					$this,
					'onloadPostPage'
			) );
		}
	}

	/**
	 * Register admin menu components
	 */
	public function buildAdminMenu() {
		if (self::isConfigured ()) {
			$cap = 'wp-piwik_read_stats';
			if (self::$settings->checkNetworkActivation ()) {
				global $current_user;
				$userRoles = $current_user->roles;
				$allowed = self::$settings->getGlobalOption ( 'capability_read_stats' );
				if (is_array($userRoles) && is_array($allowed)) 
					foreach ($userRoles as $userRole)
						if (isset( $allowed[$userRole] ) && $allowed[$userRole]) {
							$cap = 'read';
							break;
						}
			}
			$statsPage = new WP_Piwik\Admin\Statistics ( $this, self::$settings );
			$this->statsPageId = add_dashboard_page ( __ ( 'Piwik Statistics', 'wp-piwik' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), $cap, 'wp-piwik_stats', array (
					$statsPage,
					'show'
			) );
			$this->loadAdminStatsHeader ( $this->statsPageId, $statsPage );
		}
		if (! self::$settings->checkNetworkActivation ()) {
			$optionsPage = new WP_Piwik\Admin\Settings ( $this, self::$settings );
lucha's avatar
lucha committed
395
			self::$optionsPageId = add_options_page ( self::$settings->getGlobalOption ( 'plugin_display_name' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), 'activate_plugins', __FILE__, array (
ale's avatar
ale committed
396
397
398
					$optionsPage,
					'show'
			) );
lucha's avatar
lucha committed
399
			$this->loadAdminSettingsHeader ( self::$optionsPageId, $optionsPage );
ale's avatar
ale committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
		}
	}

	/**
	 * Register network admin menu components
	 */
	public function buildNetworkAdminMenu() {		
		if (self::isConfigured ()) {
			$statsPage = new WP_Piwik\Admin\Network ( $this, self::$settings );
			$this->statsPageId = add_dashboard_page ( __ ( 'Piwik Statistics', 'wp-piwik' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), 'manage_sites', 'wp-piwik_stats', array (
					$statsPage,
					'show'
			) );
			$this->loadAdminStatsHeader ( $this->statsPageId, $statsPage );
		}
		$optionsPage = new WP_Piwik\Admin\Settings ( $this, self::$settings );
lucha's avatar
lucha committed
416
		self::$optionsPageId = add_submenu_page ( 'settings.php', self::$settings->getGlobalOption ( 'plugin_display_name' ), self::$settings->getGlobalOption ( 'plugin_display_name' ), 'manage_sites', __FILE__, array (
ale's avatar
ale committed
417
418
419
				$optionsPage,
				'show'
		) );
lucha's avatar
lucha committed
420
		$this->loadAdminSettingsHeader ( self::$optionsPageId, $optionsPage );
ale's avatar
ale committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
	}

	/**
	 * Register admin header extensions for stats page
	 *
	 * @param $optionsPageId options
	 *        	page id
	 * @param $optionsPage options
	 *        	page object
	 */
	public function loadAdminStatsHeader($statsPageId, $statsPage) {
		add_action ( 'admin_print_scripts-' . $statsPageId, array (
				$statsPage,
				'printAdminScripts'
		) );
		add_action ( 'admin_print_styles-' . $statsPageId, array (
				$statsPage,
				'printAdminStyles'
		) );
		add_action ( 'admin_head-' . $statsPageId, array (
				$statsPage,
				'extendAdminHeader'
		) );
		add_action ( 'load-' . $statsPageId, array (
				$this,
				'onloadStatsPage'
		) );
	}

	/**
	 * Register admin header extensions for settings page
	 *
	 * @param $optionsPageId options
	 *        	page id
	 * @param $optionsPage options
	 *        	page object
	 */
	public function loadAdminSettingsHeader($optionsPageId, $optionsPage) {
		add_action ( 'admin_head-' . $optionsPageId, array (
				$optionsPage,
				'extendAdminHeader'
		) );
		add_action ( 'admin_print_styles-' . $optionsPageId, array (
				$optionsPage,
				'printAdminStyles'
		) );
	}

	/**
	 * Register WordPress dashboard widgets
	 */
	public function extendWordPressDashboard() {
		if (current_user_can ( 'wp-piwik_read_stats' )) {
			if (self::$settings->getGlobalOption ( 'dashboard_widget' ) != 'disabled')
				new WP_Piwik\Widget\Overview ( $this, self::$settings, 'dashboard', 'side', 'default', array (
						'date' => self::$settings->getGlobalOption ( 'dashboard_widget' ),
						'period' => 'day'
				) );
			if (self::$settings->getGlobalOption ( 'dashboard_chart' ))
				new WP_Piwik\Widget\Chart ( $this, self::$settings );
lucha's avatar
lucha committed
481
482
            if (self::$settings->getGlobalOption ( 'dashboard_ecommerce' ))
                new WP_Piwik\Widget\Ecommerce ( $this, self::$settings );
ale's avatar
ale committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
			if (self::$settings->getGlobalOption ( 'dashboard_seo' ))
				new WP_Piwik\Widget\Seo ( $this, self::$settings );
		}
	}

	/**
	 * Register WordPress toolbar components
	 */
	public function extendWordPressToolbar($toolbar) {
		if (current_user_can ( 'wp-piwik_read_stats' ) && is_admin_bar_showing ()) {
			$id = WP_Piwik\Request::register ( 'VisitsSummary.getUniqueVisitors', array (
					'period' => 'day',
					'date' => 'last30'
			) );
			$unique = $this->request ( $id );
			$url = is_network_admin () ? $this->getSettingsURL () : false;
			$content = is_network_admin () ? __('Configure WP-Piwik', 'wp-piwik') : '';
			// Leave if result array does contain a message instead of valid data
			if (isset($unique['result']))
				$content .= '<!-- '.$unique['result'].': '.($unique['message']?$unique['message']:'...').' -->';
			elseif (is_array ( $unique ) ) {
				$content = "<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>";
				$url = $this->getStatsURL ();
			}
			$toolbar->add_menu ( array (
				'id' => 'wp-piwik_stats',
				'title' => $content,
				'href' => $url
			) );
		}
	}

	/**
	 * Add plugin meta data
	 *
	 * @param array $links
	 *        	list of already defined plugin meta data
	 * @param string $file
	 *        	handled file
	 * @return array complete list of plugin meta data
	 */
	public function setPluginMeta($links, $file) {
lucha's avatar
lucha committed
525
		if ($file == 'wp-piwik/wp-piwik.php' && (!$this->isNetworkMode () || is_network_admin()) )
ale's avatar
ale committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
			return array_merge ( $links, array (
					sprintf ( '<a href="%s">%s</a>', self::getSettingsURL (), __ ( 'Settings', 'wp-piwik' ) )
			) );
		return $links;
	}

	/**
	 * Prepare toolbar widget requirements
	 */
	public function loadToolbarRequirements() {
		if (is_admin_bar_showing ()) {
			wp_enqueue_script ( 'wp-piwik-sparkline', $this->getPluginURL () . 'js/sparkline/jquery.sparkline.min.js', array (
					'jquery'
			), self::$version );
			wp_enqueue_style ( 'wp-piwik', $this->getPluginURL () . 'css/wp-piwik-spark.css', array (), $this->getPluginVersion () );
		}
	}

	/**
	 * Add tracking pixels to feed content
	 *
	 * @param string $content
	 *        	post content
	 * @return string post content extended by tracking pixel
	 */
	public function addFeedTracking($content) {
		global $post;
		if (is_feed ()) {
			self::$logger->log ( 'Add tracking image to feed entry.' );
			if (! self::$settings->getOption ( 'site_id' )) {
				$siteId = $this->requestPiwikSiteId ();
				if ($siteId != 'n/a')
					self::$settings->setOption ( 'site_id', $siteId );
				else
					return false;
			}
			$title = the_title ( null, null, false );
			$posturl = get_permalink ( $post->ID );
			$urlref = get_bloginfo ( 'rss2_url' );
lucha's avatar
lucha committed
565
566
567
568
569
570
571
572
573
			if (self::$settings->getGlobalOption ( 'track_mode' ) == 'proxy')
			    $url = plugins_url ( 'wp-piwik' ) . '/proxy/piwik.php';
            else {
                $url = self::$settings->getGlobalOption ( 'piwik_url' );
                if (substr($url, -10, 10) == '/index.php')
                    $url = str_replace('/index.php', '/piwik.php', $url);
                else
                    $url .= 'piwik.php';
            }
ale's avatar
ale committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
			$trackingImage = $url . '?idsite=' . self::$settings->getOption ( 'site_id' ) . '&amp;rec=1&amp;url=' . urlencode ( $posturl ) . '&amp;action_name=' . urlencode ( $title ) . '&amp;urlref=' . urlencode ( $urlref );
			$content .= '<img src="' . $trackingImage . '" style="border:0;width:0;height:0" width="0" height="0" alt="" />';
		}
		return $content;
	}

	/**
	 * Add a campaign parameter to feed permalink
	 *
	 * @param string $permalink
	 *        	permalink
	 * @return string permalink extended by campaign parameter
	 */
	public function addFeedCampaign($permalink) {
		global $post;
		if (is_feed ()) {
			self::$logger->log ( 'Add campaign to feed permalink.' );
			$sep = (strpos ( $permalink, '?' ) === false ? '?' : '&');
			$permalink .= $sep . 'pk_campaign=' . urlencode ( self::$settings->getGlobalOption ( 'track_feed_campaign' ) ) . '&pk_kwd=' . urlencode ( $post->post_name );
		}
		return $permalink;
	}

lucha's avatar
lucha committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
	/**
	 * Forwards the cross domain parameter pk_vid if the URL parameter is set and a user is about to be redirected.
     * When another website links to WooCommerce with a pk_vid parameter, and WooCommerce redirects the user to another
     * URL, the pk_vid parameter would get lost and the visitorId would later not be applied by the tracking code
     * due to the lost pk_vid URL parameter. If the URL parameter is set, we make sure to forward this parameter.
	 *
	 * @param string $location
	 *
	 * @return string location extended by pk_vid URL parameter if the URL parameter is set
	 */
	public function forwardCrossDomainVisitorId($location) {

		if (!empty($_GET['pk_vid'])
			&& preg_match('/^[a-zA-Z0-9]{24,48}$/', $_GET['pk_vid'])) {
			// currently, the pk_vid parameter is 32 characters long, but it may vary over time.
			$location = add_query_arg( 'pk_vid', $_GET['pk_vid'], $location );
		}

		return $location;
	}

ale's avatar
ale committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
	/**
	 * Apply settings update
	 *
	 * @return boolean settings update applied
	 */
	private function applySettings() {
		self::$settings->applyChanges ( $_POST ['wp-piwik'] );
		if (self::$settings->getGlobalOption ( 'auto_site_config' ) && self::isConfigured ()) {
			if ($this->isPHPMode () && ! defined ( 'PIWIK_INCLUDE_PATH' ))
				self::definePiwikConstants ();
			$siteId = $this->getPiwikSiteId ();
			$trackingCode = $this->updateTrackingCode ( $siteId );
			self::$settings->setOption ( 'site_id', $siteId );
		}
		self::$settings->setGlobalOption ( 'revision', self::$revisionId );
		self::$settings->setGlobalOption ( 'last_settings_update', time () );
		return true;
	}

	/**
	 * Check if WP-Piwik is configured
	 *
	 * @return boolean Is WP-Piwik configured?
	 */
	public static function isConfigured() {
lucha's avatar
lucha committed
643
		return (self::$settings->getGlobalOption ( 'piwik_token' ) && (self::$settings->getGlobalOption ( 'piwik_mode' ) != 'disabled') && (((self::$settings->getGlobalOption ( 'piwik_mode' ) == 'http') && (self::$settings->getGlobalOption ( 'piwik_url' ))) || ((self::$settings->getGlobalOption ( 'piwik_mode' ) == 'php') && (self::$settings->getGlobalOption ( 'piwik_path' ))) || ((self::$settings->getGlobalOption ( 'piwik_mode' ) == 'cloud') && (self::$settings->getGlobalOption ( 'piwik_user' )))));
ale's avatar
ale committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
	}

	/**
	 * Check if WP-Piwik was updated
	 *
	 * @return boolean Was WP-Piwik updated?
	 */
	private function isUpdated() {
		return self::$settings->getGlobalOption ( 'revision' ) && self::$settings->getGlobalOption ( 'revision' ) < self::$revisionId;
	}

	/**
	 * Check if WP-Piwik is already installed
	 *
	 * @return boolean Is WP-Piwik installed?
	 */
	private function isInstalled() {
		$oldSettings = $this->getWordPressOption ( 'wp-piwik_global-settings', false );
		if ($oldSettings && isset( $oldSettings['revision'] )) {
			self::log('Save old settings');
			self::$settings->setGlobalOption ( 'revision', $oldSettings['revision'] );
		} else self::log( 'Current revision '.self::$settings->getGlobalOption ( 'revision' ) );
		return self::$settings->getGlobalOption ( 'revision' ) > 0;
	}

	/**
	 * Check if new settings were submitted
	 *
	 * @return boolean Are new settings submitted?
	 */
lucha's avatar
lucha committed
674
675
	public static function isConfigSubmitted() {
		return isset ( $_POST ) && isset ( $_POST ['wp-piwik'] ) && self::isValidOptionsPost();
ale's avatar
ale committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
	}

	/**
	 * Check if PHP mode is chosen
	 *
	 * @return Is PHP mode chosen?
	 */
	public function isPHPMode() {
		return self::$settings->getGlobalOption ( 'piwik_mode' ) && self::$settings->getGlobalOption ( 'piwik_mode' ) == 'php';
	}

	/**
	 * Check if WordPress is running in network mode
	 *
	 * @return boolean Is WordPress running in network mode?
	 */
	public function isNetworkMode() {
		return self::$settings->checkNetworkActivation ();
	}

	/**
	 * Check if a WP-Piwik dashboard widget is enabled
	 *
	 * @return boolean Is a dashboard widget enabled?
	 */
	private function isDashboardActive() {
		return self::$settings->getGlobalOption ( 'dashboard_widget' ) || self::$settings->getGlobalOption ( 'dashboard_chart' ) || self::$settings->getGlobalOption ( 'dashboard_seo' );
	}

	/**
	 * Check if a WP-Piwik toolbar widget is enabled
	 *
	 * @return boolean Is a toolbar widget enabled?
	 */
	private function isToolbarActive() {
		return self::$settings->getGlobalOption ( 'toolbar' );
	}

	/**
	 * Check if WP-Piwik tracking code insertion is enabled
	 *
	 * @return boolean Insert tracking code?
	 */
	private function isTrackingActive() {
		return self::$settings->getGlobalOption ( 'track_mode' ) != 'disabled';
	}

	/**
	 * Check if admin tracking is enabled
	 *
	 * @return boolean Is admin tracking enabled?
	 */
	private function isAdminTrackingActive() {
		return self::$settings->getGlobalOption ( 'track_admin' ) && is_admin ();
	}

	/**
	 * Check if WP-Piwik noscript code insertion is enabled
	 *
	 * @return boolean Insert noscript code?
	 */
	private function isAddNoScriptCode() {
		return self::$settings->getGlobalOption ( 'track_noscript' );
	}

	/**
	 * Check if feed tracking is enabled
	 *
	 * @return boolean Is feed tracking enabled?
	 */
	private function isTrackFeed() {
		return self::$settings->getGlobalOption ( 'track_feed' );
	}

	/**
	 * Check if feed permalinks get a campaign parameter
	 *
	 * @return boolean Add campaign parameter to feed permalinks?
	 */
	private function isAddFeedCampaign() {
		return self::$settings->getGlobalOption ( 'track_feed_addcampaign' );
	}

lucha's avatar
lucha committed
759
760
761
762
763
764
765
766
767
	/**
	 * Check if feed permalinks get a campaign parameter
	 *
	 * @return boolean Add campaign parameter to feed permalinks?
	 */
	private function isCrossDomainLinkingEnabled() {
		return self::$settings->getGlobalOption ( 'track_crossdomain_linking' );
	}

ale's avatar
ale committed
768
769
770
771
772
773
774
775
776
777
778
779
780
781
	/**
	 * Check if WP-Piwik shortcodes are enabled
	 *
	 * @return boolean Are shortcodes enabled?
	 */
	private function isAddShortcode() {
		return self::$settings->getGlobalOption ( 'shortcodes' );
	}

	/**
	 * Define Piwik constants for PHP reporting API
	 */
	public static function definePiwikConstants() {
		if (! defined ( 'PIWIK_INCLUDE_PATH' )) {
lucha's avatar
lucha committed
782
            //@header('Content-type: text/html');
ale's avatar
ale committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
			define ( 'PIWIK_INCLUDE_PATH', self::$settings->getGlobalOption ( 'piwik_path' ) );
			define ( 'PIWIK_USER_PATH', self::$settings->getGlobalOption ( 'piwik_path' ) );
			define ( 'PIWIK_ENABLE_DISPATCH', false );
			define ( 'PIWIK_ENABLE_ERROR_HANDLER', false );
			define ( 'PIWIK_ENABLE_SESSION_START', false );
		}
	}

	/**
	 * Start chosen logging method
	 */
	private function openLogger() {
		switch (WP_PIWIK_ACTIVATE_LOGGER) {
			case 1 :
				self::$logger = new WP_Piwik\Logger\Screen ( __CLASS__ );
				break;
			case 2 :
				self::$logger = new WP_Piwik\Logger\File ( __CLASS__ );
				break;
			default :
				self::$logger = new WP_Piwik\Logger\Dummy ( __CLASS__ );
		}
	}

	/**
	 * Log a message
	 *
	 * @param string $message
	 *        	logger message
	 */
	public static function log($message) {
		self::$logger->log ( $message );
	}

	/**
	 * End logging
	 */
	private function closeLogger() {
		self::$logger = null;
	}

	/**
	 * Load WP-Piwik settings
	 */
	private function openSettings() {
		self::$settings = new WP_Piwik\Settings ( $this, self::$logger );
		if (! $this->isConfigSubmitted () && $this->isPHPMode () && ! defined ( 'PIWIK_INCLUDE_PATH' ))
			self::definePiwikConstants ();
	}

	/**
	 * Include a WP-Piwik file
	 */
	private function includeFile($strFile) {
		self::$logger->log ( 'Include ' . $strFile . '.php' );
		if (WP_PIWIK_PATH . $strFile . '.php')
			include (WP_PIWIK_PATH . $strFile . '.php');
	}

	/**
	 * Check if user should not be tracked
	 *
	 * @return boolean Do not track user?
	 */
	private function isHiddenUser() {
		if (is_multisite ())
			foreach ( self::$settings->getGlobalOption ( 'capability_stealth' ) as $key => $val )
				if ($val && current_user_can ( $key ))
					return true;
		return current_user_can ( 'wp-piwik_stealth' );
	}

	/**
	 * Check if tracking code is up to date
	 *
	 * @return boolean Is tracking code up to date?
	 */
	public function isCurrentTrackingCode() {
		return (self::$settings->getOption ( 'last_tracking_code_update' ) && self::$settings->getOption ( 'last_tracking_code_update' ) > self::$settings->getGlobalOption ( 'last_settings_update' ));
	}

	/**
	 * DEPRECTAED Add javascript code to site header
	 *
	 * @deprecated
	 *
	 */
	public function site_header() {
		self::$logger->log ( 'Using deprecated function site_header' );
		$this->addJavascriptCode ();
	}

	/**
	 * DEPRECTAED Add javascript code to site footer
	 *
	 * @deprecated
	 *
	 */
	public function site_footer() {
		self::$logger->log ( 'Using deprecated function site_footer' );
		$this->addNoscriptCode ();
	}

	/**
	 * Identify new posts if an annotation is required
lucha's avatar
lucha committed
888
	 * and create Piwik annotation
ale's avatar
ale committed
889
890
891
892
893
894
895
896
	 *
	 * @param string $newStatus
	 *        	new post status
	 * @param strint $oldStatus
	 *        	new post status
	 * @param object $post
	 *        	current post object
	 */
lucha's avatar
lucha committed
897
	public function addPiwikAnnotation($newStatus, $oldStatus, $post) {
lucha's avatar
lucha committed
898
899
	    $enabledPostTypes = self::$settings->getGlobalOption ( 'add_post_annotations' );
		if (isset($enabledPostTypes[$post->post_type]) && $enabledPostTypes[$post->post_type] && $newStatus == 'publish' && $oldStatus != 'publish') {
lucha's avatar
lucha committed
900
901
902
903
904
			$note = 'Published: ' . $post->post_title . ' - URL: ' . get_permalink ( $post->ID );
			$id = WP_Piwik\Request::register ( 'Annotations.add', array (
				'idSite' => $this->getPiwikSiteId (),
				'date' => date ( 'Y-m-d' ),
				'note' => $note
ale's avatar
ale committed
905
			) );
lucha's avatar
lucha committed
906
907
			$result = $this->request ( $id );
			self::$logger->log ( 'Add post annotation. ' . $note . ' - ' . serialize ( $result ) );
ale's avatar
ale committed
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
		}
	}

	/**
	 * Get WP-Piwik's URL
	 */
	public function getPluginURL() {
		return trailingslashit ( plugins_url () . '/wp-piwik/' );
	}

	/**
	 * Get WP-Piwik's version
	 */
	public function getPluginVersion() {
		return self::$version;
	}

	/**
	 * Enable three columns for WP-Piwik stats screen
	 *
	 * @param
	 *        	array full list of column settings
	 * @param
	 *        	mixed current screen id
	 * @return array updated list of column settings
	 */
	public function onScreenLayoutColumns($columns, $screen) {
		if (isset( $this->statsPageId ) && $screen == $this->statsPageId)
			$columns [$this->statsPageId] = 3;
		return $columns;
	}

	/**
	 * Add tracking code to admin header
	 */
	function addAdminHeaderTracking() {
		$this->addJavascriptCode ();
	}

	/**
	 * Get option value
	 *
	 * @param string $key
	 *        	option key
	 * @return mixed option value
	 */
	public function getOption($key) {
		return self::$settings->getOption ( $key );
	}

	/**
	 * Get global option value
	 *
	 * @param string $key
	 *        	global option key
	 * @return mixed global option value
	 */
	public function getGlobalOption($key) {
		return self::$settings->getGlobalOption ( $key );
	}

	/**
	 * Get stats page URL
	 *
	 * @return string stats page URL
	 */
	public function getStatsURL() {
		return admin_url () . '?page=wp-piwik_stats';
	}

	/**
	 * Execute WP-Piwik test script
	 */
	private function loadTestscript() {
		$this->includeFile ( 'debug' . DIRECTORY_SEPARATOR . 'testscript' );
	}

	/**
	 * Echo an error message
	 *
	 * @param string $message
	 *        	message content
	 */
	private static function showErrorMessage($message) {
		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>]';
	}

	/**
	 * Perform a Piwik request
	 *
	 * @param string $id
	 *        	request ID
	 * @return mixed request result
For faster browsing, not all history is shown. View entire blame