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

wpmautic.php ➔ wpmautic_get_user_query()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 7.3652

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 2
nop 0
dl 0
loc 22
ccs 3
cts 14
cp 0.2143
crap 7.3652
rs 9.2
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 43
	$options = get_option( 'wpmautic_options' );
81
82
	switch ( $option ) {
83 43
		case 'script_location':
84 12
			return ! isset( $options[ $option ] ) ? 'header' : $options[ $option ];
85 39
		case 'fallback_activated':
86 13
			return isset( $options[ $option ] ) ? (bool) $options[ $option ] : true;
87
		default:
88 34
			if ( ! isset( $options[ $option ] ) ) {
89 15
				if ( isset( $default ) ) {
90 14
					return $default;
91
				}
92
93 1
				throw new InvalidArgumentException( 'You must give a valid option name !' );
94
			}
95
96 25
			return $options[ $option ];
97
	}
98
}
99
100
/**
101
 * Apply JS tracking to the right place depending script_location.
102
 *
103
 * @return void
104
 */
105
function wpmautic_injector() {
106 7
	$script_location = wpmautic_option( 'script_location' );
107 7
	if ( 'header' === $script_location ) {
108 5
		add_action( 'wp_head', 'wpmautic_inject_script' );
109
	} else {
110 2
		add_action( 'wp_footer', 'wpmautic_inject_script' );
111
	}
112
113 7
	if ( true === wpmautic_option( 'fallback_activated', false ) ) {
114 6
		add_action( 'wp_footer', 'wpmautic_inject_noscript' );
115
	}
116 7
}
117
118
/**
119
 * Writes Tracking JS to the HTML source
120
 *
121
 * @return void
122
 */
123
function wpmautic_inject_script() {
124 6
	$base_url = wpmautic_option( 'base_url', '' );
125 6
	if ( empty( $base_url ) ) {
126
		return;
127
	}
128
129 6
	$attrs = wpmautic_get_tracking_attributes();
130 6
	$atts = $atts + wpmautic_get_user_query();
0 ignored issues
show
Bug introduced by
The variable $atts seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Unused Code introduced by
$atts is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
131
132
	?><script type="text/javascript">
133
	(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
134
		w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
135
		m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
136
	})(window,document,'script','<?php echo esc_url( $base_url ); ?>/mtc.js','mt');
137
138
	mt('send', 'pageview'<?php echo count( $attrs ) > 0?', ' . wp_json_encode( $attrs ):'' ?>);
139
</script>
140
	<?php
141
}
142
143
/**
144
 * Writes Tracking image fallback to the HTML source
145
 * This is a separated function because <noscript> tags are not allowed in header !
146
 *
147
 * @return void
148
 */
149
function wpmautic_inject_noscript() {
150 1
	$base_url = wpmautic_option( 'base_url', '' );
151 1
	if ( empty( $base_url ) ) {
152
		return;
153
	}
154
155 1
	$url_query = wpmautic_get_url_query();
156 1
	$payload = rawurlencode( base64_encode( serialize( $url_query ) ) );
157
	?>
158 1
	<noscript>
159
		<img src="<?php echo esc_url( $base_url ); ?>/mtracking.gif?d=<?php echo esc_attr( $payload ); ?>"  style="display:none;" alt="" />
160
	</noscript>
161
	<?php
162 1
}
163
164
/**
165
 * Builds and returns additional data for URL query
166
 *
167
 * @return array
168
 */
169
function wpmautic_get_url_query() {
170 5
	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...
171 5
	$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
172
173 5
	$attrs = wpmautic_get_tracking_attributes();
174
175 5
	$attrs['language']   = get_locale();
176 5
	$attrs['page_url']   = $current_url;
177 5
	$attrs['page_title'] = function_exists( 'wp_get_document_title' )
178 5
		? wp_get_document_title()
179
		: wp_title( '&raquo;', false );
180 5
	$attrs['referrer']   = function_exists( 'wp_get_raw_referer' )
181 5
		? wp_get_raw_referer()
182
		: null;
183 5
	if ( false === $attrs['referrer'] ) {
184 3
		$attrs['referrer'] = $current_url;
185
	}
186
187 5
	return $attrs;
188
}
189
190
/**
191
 * Create custom query parameters to be injected inside tracking
192
 *
193
 * @return array
194
 */
195
function wpmautic_get_tracking_attributes() {
196 14
	$attrs = array();
197
198
	/**
199
	 * Update / add data to be send withing Mautic tracker
200
	 *
201
	 * Default data only contains the 'language' key but every added key to the
202
	 * array will be sent to Mautic.
203
	 *
204
	 * @since 2.1.0
205
	 *
206
	 * @param array $attrs Attributes to be filters, default ['language' => get_locale()]
207
	 */
208 14
	return apply_filters( 'wpmautic_tracking_attributes', $attrs );
209
}
210
211
/**
212
 * Adds the user email, and other known elements about the user.
213
 *
214
 * @return array
215
 */
216
function wpmautic_get_user_query() {
217 6
	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...
218
219 6
	if ( true === wpmautic_option( 'track_logged_user', false ) && is_user_logged_in() ) {
220
		$attrs = array();
221
		$current_user = wp_get_current_user();
222
		$attrs['email']	 = $current_user->user_email;
223
		$attrs['firstname']  = $current_user->user_firstname;
224
		$attrs['lastname']  = $current_user->user_lastname;
225
226
		// Following Mautic fields has to be created manually and the fields must match these names.
227
		$attrs['wp_user']  = $current_user->user_login;
228
		$attrs['wp_alias']  = $current_user->display_name;
229
		$attrs['registration_date'] = date(
230
			'Y-m-d',
231
			strtotime( $current_user->user_registered )
232
		);
233
		return $attrs;
234
	} else {
235 6
		return array();
236
	}
237
}
238