Completed
Pull Request — master (#56)
by Stéphane
03:20
created

wpmautic.php ➔ wpmautic_get_user_query()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.9862

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 2
nop 0
dl 0
loc 23
ccs 4
cts 13
cp 0.3076
crap 5.9862
rs 9.0856
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 23 and the first side effect is on line 17.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Plugin Name: WP Mautic
4
 * Plugin URI: https://github.com/mautic/mautic-wordpress
5
 * Description: This plugin will allow you to add Mautic (Free Open Source Marketing Automation) tracking to your site
6
 * Version: 2.1.0
7
 * Author: Mautic community
8
 * Author URI: http://mautic.org
9
 * Text Domain: wp-mautic
10
 * License: GPL2
11
 *
12
 * @package wp-mautic
13
 */
14
15
// Prevent direct access to this file.
16
if ( ! defined( 'ABSPATH' ) ) {
17
	header( 'HTTP/1.0 403 Forbidden' );
18
	echo 'This file should not be accessed directly!';
19
	exit; // Exit if accessed directly.
20
}
21
22
// Store plugin directory.
23
define( 'VPMAUTIC_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
24
// Store plugin main file path.
25
define( 'VPMAUTIC_PLUGIN_FILE', __FILE__ );
26
27
add_action( 'admin_menu', 'wpmautic_settings' );
28
add_action( 'plugins_loaded', 'wpmautic_injector' );
29
30
include_once( VPMAUTIC_PLUGIN_DIR . '/shortcodes.php' );
31
32
/**
33
 * Declare option page
34
 */
35
function wpmautic_settings() {
36 1
	include_once( VPMAUTIC_PLUGIN_DIR . '/options.php' );
37
38 1
	add_options_page(
39 1
		__( 'WP Mautic Settings', 'wp-mautic' ),
40 1
		__( 'WPMautic', 'wp-mautic' ),
41 1
		'manage_options',
42 1
		'wpmautic',
43 1
		'wpmautic_options_page'
44
	);
45 1
}
46
47
/**
48
 * Settings Link in the ``Installed Plugins`` page
49
 *
50
 * @param  array  $links array of plugin action links.
51
 * @param  string $file  Path to the plugin file relative to the plugins directory.
52
 *
53
 * @return array
54
 */
55
function wpmautic_plugin_actions( $links, $file ) {
56 1
	if ( plugin_basename( VPMAUTIC_PLUGIN_FILE ) === $file && function_exists( 'admin_url' ) ) {
57 1
		$settings_link = sprintf(
58 1
			'<a href="%s">%s</a>',
59 1
			admin_url( 'options-general.php?page=wpmautic' ),
60 1
			__( 'Settings' )
61
		);
62
		// Add the settings link before other links.
63 1
		array_unshift( $links, $settings_link );
64
	}
65 1
	return $links;
66
}
67
add_filter( 'plugin_action_links', 'wpmautic_plugin_actions', 10, 2 );
68
69
/**
70
 * Retrieve one of the wpmautic options but sanitized
71
 *
72
 * @param  string $option  Option name to be retrieved (base_url, script_location).
73
 * @param  mixed  $default Default option value return if not exists.
74
 *
75
 * @return string
76
 *
77
 * @throws InvalidArgumentException Thrown when the option name is not given.
78
 */
79
function wpmautic_option( $option, $default = null ) {
80 47
	$options = get_option( 'wpmautic_options' );
81
82
	switch ( $option ) {
83 47
		case 'script_location':
84 12
			return ! isset( $options[ $option ] ) ? 'header' : $options[ $option ];
85 43
		case 'fallback_activated':
86 13
			return isset( $options[ $option ] ) ? (bool) $options[ $option ] : true;
87 38
		case 'track_logged_user':
88 12
			return isset( $options[ $option ] ) ? (bool) $options[ $option ] : false;
89
		default:
90 34
			if ( ! isset( $options[ $option ] ) ) {
91 9
				if ( isset( $default ) ) {
92 8
					return $default;
93
				}
94
95 1
				throw new InvalidArgumentException( 'You must give a valid option name !' );
96
			}
97
98 25
			return $options[ $option ];
99
	}
100
}
101
102
/**
103
 * Apply JS tracking to the right place depending script_location.
104
 *
105
 * @return void
106
 */
107
function wpmautic_injector() {
108 7
	$script_location = wpmautic_option( 'script_location' );
109 7
	if ( 'header' === $script_location ) {
110 5
		add_action( 'wp_head', 'wpmautic_inject_script' );
111
	} else {
112 2
		add_action( 'wp_footer', 'wpmautic_inject_script' );
113
	}
114
115 7
	if ( true === wpmautic_option( 'fallback_activated', false ) ) {
116 6
		add_action( 'wp_footer', 'wpmautic_inject_noscript' );
117
	}
118 7
}
119
120
/**
121
 * Writes Tracking JS to the HTML source
122
 *
123
 * @return void
124
 */
125
function wpmautic_inject_script() {
126 6
	$base_url = wpmautic_option( 'base_url', '' );
127 6
	if ( empty( $base_url ) ) {
128
		return;
129
	}
130
131 6
	$attrs = array_merge(
132 6
		wpmautic_get_user_query(),
133 6
		wpmautic_get_tracking_attributes()
134
	);
135
136
	?><script type="text/javascript">
137
	(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
138
		w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
139
		m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
140
	})(window,document,'script','<?php echo esc_url( $base_url ); ?>/mtc.js','mt');
141
142
	mt('send', 'pageview'<?php echo count( $attrs ) > 0?', ' . wp_json_encode( $attrs ):'' ?>);
143
</script>
144
	<?php
145 6
}
146
147
/**
148
 * Writes Tracking image fallback to the HTML source
149
 * This is a separated function because <noscript> tags are not allowed in header !
150
 *
151
 * @return void
152
 */
153
function wpmautic_inject_noscript() {
154 6
	$base_url = wpmautic_option( 'base_url', '' );
155 6
	if ( empty( $base_url ) ) {
156
		return;
157
	}
158
159 6
	$url_query = wpmautic_get_url_query();
160 6
	$payload = rawurlencode( base64_encode( serialize( $url_query ) ) );
161
	?>
162 6
	<noscript>
163
		<img src="<?php echo esc_url( $base_url ); ?>/mtracking.gif?d=<?php echo esc_attr( $payload ); ?>"  style="display:none;" alt="" />
164
	</noscript>
165
	<?php
166 6
}
167
168
/**
169
 * Builds and returns additional data for URL query
170
 *
171
 * @return array
172
 */
173
function wpmautic_get_url_query() {
174 10
	global $wp;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
175 10
	$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
176
177 10
	$attrs = array_merge(
178 10
		wpmautic_get_user_query(),
179 10
		wpmautic_get_tracking_attributes()
180
	);
181
182 10
	$attrs['language']   = get_locale();
183 10
	$attrs['page_url']   = $current_url;
184 10
	$attrs['page_title'] = function_exists( 'wp_get_document_title' )
185 10
		? wp_get_document_title()
186
		: wp_title( '&raquo;', false );
187 10
	$attrs['referrer']   = function_exists( 'wp_get_raw_referer' )
188 10
		? wp_get_raw_referer()
189
		: null;
190 10
	if ( false === $attrs['referrer'] ) {
191 8
		$attrs['referrer'] = $current_url;
192
	}
193
194 10
	return $attrs;
195
}
196
197
/**
198
 * Create custom query parameters to be injected inside tracking
199
 *
200
 * @return array
201
 */
202
function wpmautic_get_tracking_attributes() {
203 14
	$attrs = array();
204
205
	/**
206
	 * Update / add data to be send withing Mautic tracker
207
	 *
208
	 * Default data only contains the 'language' key but every added key to the
209
	 * array will be sent to Mautic.
210
	 *
211
	 * @since 2.1.0
212
	 *
213
	 * @param array $attrs Attributes to be filters, default ['language' => get_locale()]
214
	 */
215 14
	return apply_filters( 'wpmautic_tracking_attributes', $attrs );
216
}
217
218
/**
219
 * Extract logged user informations to be send within Mautic tracker
220
 *
221
 * @return array
222
 */
223
function wpmautic_get_user_query() {
224 11
	$attrs = array();
225
226
	if (
227 11
		true === wpmautic_option( 'track_logged_user', false ) &&
228 11
		is_user_logged_in()
229
	) {
230
		$current_user = wp_get_current_user();
231
		$attrs['email']	 = $current_user->user_email;
232
		$attrs['firstname']  = $current_user->user_firstname;
233
		$attrs['lastname']  = $current_user->user_lastname;
234
235
		// Following Mautic fields has to be created manually and the fields must match these names.
236
		$attrs['wp_user']  = $current_user->user_login;
237
		$attrs['wp_alias']  = $current_user->display_name;
238
		$attrs['wp_registration_date'] = date(
239
			'Y-m-d',
240
			strtotime( $current_user->user_registered )
241
		);
242
	}
243
244 11
	return $attrs;
245
}
246