Completed
Pull Request — master (#102)
by
unknown
10:06
created

wpmautic.php ➔ wpmautic_inject_send_script()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 0
dl 0
loc 20
ccs 7
cts 7
cp 1
crap 3
rs 9.6
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.3.2
8
 * Requires at least: 4.6
9
 * Tested up to: 5.4
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_' . plugin_basename( VPMAUTIC_PLUGIN_FILE ), '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 53
	$options = get_option( 'wpmautic_options' );
84
85 53
	switch ( $option ) {
86 53
		case 'script_location':
87 15
			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 8
	$script_location = wpmautic_option( 'script_location' );
112 8
	if ( 'header' === $script_location ) {
113 5
		add_action( 'wp_head', 'wpmautic_inject_script' );
114 3
	} elseif ( 'footer' === $script_location || 'disabled' === $script_location ) {
115 2
		add_action( 'wp_footer', 'wpmautic_inject_script' );
116
	}
117
118 8
	if ( 'disabled' !== $script_location && true === wpmautic_option( 'fallback_activated', false ) ) {
119 6
		add_action( 'wp_footer', 'wpmautic_inject_noscript' );
120
	}
121 8
}
122
123
/**
124
 * Generate the mautic script URL to be used outside of the plugin when
125
 * necessary
126
 *
127
 * @return string
128
 */
129
function wpmautic_base_script() {
130 6
	$base_url = wpmautic_option( 'base_url', '' );
131 6
	if ( empty( $base_url ) ) {
132
		return;
133
	}
134
135 6
	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 6
	?>
145 6
	<script type="text/javascript">
146
		<?php
147
		wpmautic_inject_base_script();
148
		wpmautic_inject_send_script();
149 6
		?>
150
	</script>
151
	<?php
152
}
153
154
/**
155
 * Load the Mautic tracking library mtc.js if it is not disabled.
156
 */
157
function wpmautic_inject_base_script() {
158
	$base_url        = wpmautic_base_script();
159
	$script_location = wpmautic_option( 'script_location' );
160 6
161
	if ( empty( $base_url ) || 'disabled' === $script_location ) {
162
		return;
163
	}
164
	?>
165
	(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
166
		w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
167
		m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
168
	})(window,document,'script','<?php echo esc_url( $base_url ); ?>','mt');
169 6
	<?php
170 6
}
171
172
/**
173
 * Add the mt('send', 'pageview') script with optional tracking attributes
174 6
 */
175 6
function wpmautic_inject_send_script() {
176
	$attrs           = wpmautic_get_tracking_attributes();
177 6
	$script_location = wpmautic_option( 'script_location' );
178
	?>
179
	function wpmautic_send(){
180
		if ('undefined' === typeof mt){
181 6
			console.warn('mt not defined. Did you load mtc.js?');
182
			return false;
183
		}
184
		mt('send', 'pageview'<?php echo count( $attrs ) > 0 ? ', ' . wp_json_encode( $attrs ) : ''; ?>);
185
	}
186
	<?php
187
	if ( 'disabled' !== $script_location ) {
188
		?>
189 10
			wpmautic_send();
190 10
		<?php
191
	}
192 10
	?>
193
	<?php
194 10
}
195 10
196 10
/**
197 10
 * Writes Tracking image fallback to the HTML source
198
 * This is a separated function because <noscript> tags are not allowed in header !
199 10
 *
200 10
 * @return void
201
 */
202 10
function wpmautic_inject_noscript() {
203 8
	$base_url = wpmautic_option( 'base_url', '' );
204
	if ( empty( $base_url ) ) {
205
		return;
206 10
	}
207
208
	$url_query = wpmautic_get_url_query();
209
	$payload   = rawurlencode( base64_encode( serialize( $url_query ) ) );
210
	?>
211
	<noscript>
212
		<img src="<?php echo esc_url( $base_url ); ?>/mtracking.gif?d=<?php echo esc_attr( $payload ); ?>"  style="display:none;" alt="" />
213
	</noscript>
214
	<?php
215 14
}
216
217
/**
218
 * Builds and returns additional data for URL query
219
 *
220
 * @return array
221
 */
222
function wpmautic_get_url_query() {
223
	global $wp;
224
	$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
225
226
	$attrs = wpmautic_get_tracking_attributes();
227 14
228
	$attrs['language']   = get_locale();
229
	$attrs['page_url']   = $current_url;
230
	$attrs['page_title'] = function_exists( 'wp_get_document_title' )
231
		? wp_get_document_title()
232
		: wp_title( '&raquo;', false );
233
	$attrs['referrer']   = function_exists( 'wp_get_raw_referer' )
234
		? wp_get_raw_referer()
235
		: null;
236 14
	if ( false === $attrs['referrer'] ) {
237
		$attrs['referrer'] = $current_url;
238
	}
239 14
240 14
	return $attrs;
241
}
242
243
/**
244
 * Create custom query parameters to be injected inside tracking
245
 *
246
 * @return array
247
 */
248
function wpmautic_get_tracking_attributes() {
249
	$attrs = wpmautic_get_user_query();
250
251
	/**
252
	 * Update / add data to be send withing Mautic tracker
253
	 *
254
	 * Default data only contains the 'language' key but every added key to the
255
	 * array will be sent to Mautic.
256 14
	 *
257
	 * @since 2.1.0
258
	 *
259
	 * @param array $attrs Attributes to be filters, default ['language' => get_locale()]
260
	 */
261
	return apply_filters( 'wpmautic_tracking_attributes', $attrs );
262
}
263
264
/**
265
 * Extract logged user informations to be send within Mautic tracker
266
 *
267
 * @return array
268
 */
269
function wpmautic_get_user_query() {
270
	$attrs = array();
271
272
	if (
273
		true === wpmautic_option( 'track_logged_user', false ) &&
274
		is_user_logged_in()
275
	) {
276
		$current_user       = wp_get_current_user();
277
		$attrs['email']     = $current_user->user_email;
278
		$attrs['firstname'] = $current_user->user_firstname;
279
		$attrs['lastname']  = $current_user->user_lastname;
280
281
		// Following Mautic fields has to be created manually and the fields must match these names.
282
		$attrs['wp_user']              = $current_user->user_login;
283
		$attrs['wp_alias']             = $current_user->display_name;
284
		$attrs['wp_registration_date'] = date(
285
			'Y-m-d',
286
			strtotime( $current_user->user_registered )
287
		);
288
	}
289
290
	return $attrs;
291
}
292