Completed
Pull Request — master (#95)
by Stéphane
08:28
created

wpmautic.php ➔ wpmautic_base_script()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 8
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Plugin Name: WP Mautic
4
 * Plugin URI: https://github.com/mautic/mautic-wordpress
5
 * Contributors: mautic,hideokamoto,shulard,escopecz,dbhurley,macbookandrew
6
 * Description: This plugin will allow you to add Mautic (Free Open Source Marketing Automation) tracking to your site
7
 * Version: 2.2.2
8
 * Requires at least: 4.6
9
 * Tested up to: 5.1
10
 * Author: Mautic community
11
 * Author URI: http://mautic.org
12
 * Text Domain: wp-mautic
13
 * License: GPLv2 or later
14
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
15
 *
16
 * @package wp-mautic
17
 */
18
19
// Prevent direct access to this file.
20
if ( ! defined( 'ABSPATH' ) ) {
21
	header( 'HTTP/1.0 403 Forbidden' );
22
	echo 'This file should not be accessed directly!';
23
	exit; // Exit if accessed directly.
24
}
25
26
// Store plugin directory.
27
define( 'VPMAUTIC_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
28
// Store plugin main file path.
29
define( 'VPMAUTIC_PLUGIN_FILE', __FILE__ );
30
31
add_action( 'admin_menu', 'wpmautic_settings' );
32
add_action( 'plugins_loaded', 'wpmautic_injector' );
33
34
require_once VPMAUTIC_PLUGIN_DIR . '/shortcodes.php';
35
36
/**
37
 * Declare option page
38
 */
39
function wpmautic_settings() {
40 1
	include_once VPMAUTIC_PLUGIN_DIR . '/options.php';
41
42 1
	add_options_page(
43 1
		__( 'WP Mautic Settings', 'wp-mautic' ),
44 1
		__( 'WPMautic', 'wp-mautic' ),
45 1
		'manage_options',
46 1
		'wpmautic',
47 1
		'wpmautic_options_page'
48
	);
49 1
}
50
51
/**
52
 * Settings Link in the ``Installed Plugins`` page
53
 *
54
 * @param array $links array of plugin action links.
55
 *
56
 * @return array
57
 */
58
function wpmautic_plugin_actions( $links ) {
59 1
	if ( function_exists( 'admin_url' ) ) {
60 1
		$settings_link = sprintf(
61 1
			'<a href="%s">%s</a>',
62 1
			admin_url( 'options-general.php?page=wpmautic' ),
63 1
			__( 'Settings' )
64
		);
65
		// Add the settings link before other links.
66 1
		array_unshift( $links, $settings_link );
67
	}
68 1
	return $links;
69
}
70
add_filter( 'plugin_action_links', 'wpmautic_plugin_actions', 10, 2 );
71
72
/**
73
 * Retrieve one of the wpmautic options but sanitized
74
 *
75
 * @param  string $option  Option name to be retrieved (base_url, script_location).
76
 * @param  mixed  $default Default option value return if not exists.
77
 *
78
 * @return string
79
 *
80
 * @throws InvalidArgumentException Thrown when the option name is not given.
81
 */
82
function wpmautic_option( $option, $default = null ) {
83 50
	$options = get_option( 'wpmautic_options' );
84
85 50
	switch ( $option ) {
86 50
		case 'script_location':
87 12
			return ! isset( $options[ $option ] ) ? 'header' : $options[ $option ];
88 46
		case 'fallback_activated':
89 13
			return isset( $options[ $option ] ) ? (bool) $options[ $option ] : true;
90 41
		case 'track_logged_user':
91 15
			return isset( $options[ $option ] ) ? (bool) $options[ $option ] : false;
92
		default:
93 34
			if ( ! isset( $options[ $option ] ) ) {
94 9
				if ( isset( $default ) ) {
95 8
					return $default;
96
				}
97
98 1
				throw new InvalidArgumentException( 'You must give a valid option name !' );
99
			}
100
101 25
			return $options[ $option ];
102
	}
103
}
104
105
/**
106
 * Apply JS tracking to the right place depending script_location.
107
 *
108
 * @return void
109
 */
110
function wpmautic_injector() {
111 7
	$script_location = wpmautic_option( 'script_location' );
112 7
	if ( 'header' === $script_location ) {
113 5
		add_action( 'wp_head', 'wpmautic_inject_script' );
114
	} elseif ( 'footer' === $script_location ) {
115 2
		add_action( 'wp_footer', 'wpmautic_inject_script' );
116
	}
117
118 7
	if ( 'disabled' !== $script_location && true === wpmautic_option( 'fallback_activated', false ) ) {
119 6
		add_action( 'wp_footer', 'wpmautic_inject_noscript' );
120
	}
121 7
}
122
123
/**
124
 * Generate the mautic script URL to be used outside of the plugin when
125
 * necessary
126
 *
127
 * @return string
128
 */
129 6
function wpmautic_base_script() {
130 6
	$base_url = wpmautic_option( 'base_url', '' );
131
	if ( empty( $base_url ) ) {
132
		return;
133
	}
134 6
135
	return $base_url . '/mtc.js';
136
}
137
138
/**
139
 * Writes Tracking JS to the HTML source
140
 *
141
 * @return void
142
 */
143
function wpmautic_inject_script() {
144
	$base_url = wpmautic_base_script();
145 6
	if ( empty( $base_url ) ) {
146
		return;
147
	}
148
149
	$attrs = wpmautic_get_tracking_attributes();
150
151
	?><script type="text/javascript">
152
	(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
153
		w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
154 6
		m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
155 6
	})(window,document,'script','<?php echo esc_url( $base_url ); ?>','mt');
156
157
	mt('send', 'pageview'<?php echo count( $attrs ) > 0 ? ', ' . wp_json_encode( $attrs ) : ''; ?>);
158
</script>
159 6
	<?php
160 6
}
161
162 6
/**
163
 * Writes Tracking image fallback to the HTML source
164
 * This is a separated function because <noscript> tags are not allowed in header !
165
 *
166 6
 * @return void
167
 */
168
function wpmautic_inject_noscript() {
169
	$base_url = wpmautic_option( 'base_url', '' );
170
	if ( empty( $base_url ) ) {
171
		return;
172
	}
173
174 10
	$url_query = wpmautic_get_url_query();
175 10
	$payload   = rawurlencode( base64_encode( serialize( $url_query ) ) );
176
	?>
177 10
	<noscript>
178
		<img src="<?php echo esc_url( $base_url ); ?>/mtracking.gif?d=<?php echo esc_attr( $payload ); ?>"  style="display:none;" alt="" />
179 10
	</noscript>
180 10
	<?php
181 10
}
182 10
183
/**
184 10
 * Builds and returns additional data for URL query
185 10
 *
186
 * @return array
187 10
 */
188 8
function wpmautic_get_url_query() {
189
	global $wp;
190
	$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
191 10
192
	$attrs = wpmautic_get_tracking_attributes();
193
194
	$attrs['language']   = get_locale();
195
	$attrs['page_url']   = $current_url;
196
	$attrs['page_title'] = function_exists( 'wp_get_document_title' )
197
		? wp_get_document_title()
198
		: wp_title( '&raquo;', false );
199
	$attrs['referrer']   = function_exists( 'wp_get_raw_referer' )
200 14
		? wp_get_raw_referer()
201
		: null;
202
	if ( false === $attrs['referrer'] ) {
203
		$attrs['referrer'] = $current_url;
204
	}
205
206
	return $attrs;
207
}
208
209
/**
210
 * Create custom query parameters to be injected inside tracking
211
 *
212 14
 * @return array
213
 */
214
function wpmautic_get_tracking_attributes() {
215
	$attrs = wpmautic_get_user_query();
216
217
	/**
218
	 * Update / add data to be send withing Mautic tracker
219
	 *
220
	 * Default data only contains the 'language' key but every added key to the
221 14
	 * array will be sent to Mautic.
222
	 *
223
	 * @since 2.1.0
224 14
	 *
225 14
	 * @param array $attrs Attributes to be filters, default ['language' => get_locale()]
226
	 */
227
	return apply_filters( 'wpmautic_tracking_attributes', $attrs );
228
}
229
230
/**
231
 * Extract logged user informations to be send within Mautic tracker
232
 *
233
 * @return array
234
 */
235
function wpmautic_get_user_query() {
236
	$attrs = array();
237
238
	if (
239
		true === wpmautic_option( 'track_logged_user', false ) &&
240
		is_user_logged_in()
241 14
	) {
242
		$current_user       = wp_get_current_user();
243
		$attrs['email']     = $current_user->user_email;
244
		$attrs['firstname'] = $current_user->user_firstname;
245
		$attrs['lastname']  = $current_user->user_lastname;
246
247
		// Following Mautic fields has to be created manually and the fields must match these names.
248
		$attrs['wp_user']              = $current_user->user_login;
249
		$attrs['wp_alias']             = $current_user->display_name;
250
		$attrs['wp_registration_date'] = date(
251
			'Y-m-d',
252
			strtotime( $current_user->user_registered )
253
		);
254
	}
255
256
	return $attrs;
257
}
258