Completed
Push — master ( 370b29...d2e2f1 )
by Stéphane
04:42 queued 02:42
created

wpmautic.php ➔ wpmautic_option()   C

Complexity

Conditions 9
Paths 9

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 9

Importance

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