-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-wp-rollbar.php
More file actions
312 lines (273 loc) · 17.2 KB
/
simple-wp-rollbar.php
File metadata and controls
312 lines (273 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<?php
/**
* Simple WP Rollbar
*
* @package simple-wp-rollbar
* @author SystemSeed
* @license GPL-2.0-or-later
* @link https://github.com/systemseed/simple-wp-rollbar
*
* Plugin Name: Simple WP Rollbar
* Plugin URI: https://wordpress.org/plugins/simple-wp-rollbar
* Description: Implements the Rollbar PHP and BrowserJS logging services.
* Version: 1.0.0
* Requires at least: 6.8
* Requires PHP: 8.3
* Author: SystemSeed
* Author URI: https://systemseed.com
* Text Domain: simple-wp-rollbar
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License version 2, as published by the Free Software Foundation. You may NOT assume
* that you can use any other version of the GPL.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
use Rollbar\Rollbar;
use function Env\env;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Initialise Rollbar when the server access token is configured.
*
* See https://docs.rollbar.com/docs/basic-php-installation-setup
*/
function simple_wp_rollbar_bootstrap_server(): void {
if ( ! class_exists( Rollbar::class ) ) {
return;
}
$server_token = env( 'ROLLBAR_SERVER_ACCESS_TOKEN' );
if ( false === $server_token || '' === $server_token ) {
return;
}
Rollbar::init(
array(
'access_token' => $server_token,
'environment' => env( 'APPLICATION_MODE' ),
'root' => ABSPATH,
)
);
}
/**
* Output Rollbar browser snippet for front-end and admin when configured.
*
* See https://docs.rollbar.com/docs/browser-js
*/
function simple_wp_rollbar_print_browser_snippet(): void {
static $rendered = false;
if ( $rendered ) {
return;
}
$client_token = env( 'ROLLBAR_CLIENT_ACCESS_TOKEN' );
if ( false === $client_token || '' === $client_token ) {
return;
}
$rendered = true;
$environment = env( 'APPLICATION_MODE' );
$config = array(
'accessToken' => $client_token,
'captureUncaught' => true,
'captureUnhandledRejections' => true,
'payload' => array(
'environment' => $environment,
'client' => array(
'javascript' => array(
'code_version' => '1.0.0',
),
),
),
);
?>
<script>
var _rollbarConfig = <?php echo wp_json_encode( $config, JSON_UNESCAPED_SLASHES ); ?>;
// Rollbar Snippet - loads main Rollbar library and shims.
!function(r){var e={};function o(n){if(e[n])return e[n].exports;var t=e[n]={i:n,l:!1,exports:{}};return r[n].call(t.exports,t,t.exports,o),t.l=!0,t.exports}o.m=r,o.c=e,o.d=function(r,e,n){o.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},o.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},o.t=function(r,e){if(1&e&&(r=o(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var t in r)o.d(n,t,function(e){return r[e]}.bind(null,t));return n},o.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return o.d(e,"a",e),e},o.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},o.p="",o(o.s=0)}([function(r,e,o){"use strict";var n=o(1),t=o(5);_rollbarConfig=_rollbarConfig||{},_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://cdn.rollbar.com/rollbarjs/refs/tags/v2.26.4/rollbar.min.js",_rollbarConfig.async=void 0===_rollbarConfig.async||_rollbarConfig.async;var a=n.setupShim(window,_rollbarConfig),l=t(_rollbarConfig);window.rollbar=n.Rollbar,a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,l)},function(r,e,o){"use strict";var n=o(2),t=o(3);function a(r){return function(){try{return r.apply(this,arguments)}catch(r){try{console.error("[Rollbar]: Internal error",r)}catch(r){}}}}var l=0;function i(r,e){this.options=r,this._rollbarOldOnError=null;var o=l++;this.shimId=function(){return o},"undefined"!=typeof window&&window._rollbarShims&&(window._rollbarShims[o]={handler:e,messages:[]})}var s=o(4),d=function(r,e){return new i(r,e)},c=function(r){return new s(d,r)};function u(r){return a((function(){var e=this,o=Array.prototype.slice.call(arguments,0),n={shim:e,method:r,args:o,ts:new Date};window._rollbarShims[this.shimId()].messages.push(n)}))}i.prototype.loadFull=function(r,e,o,n,t){var l=!1,i=e.createElement("script"),s=e.getElementsByTagName("script")[0],d=s.parentNode;i.crossOrigin="",i.src=n.rollbarJsUrl,o||(i.async=!0),i.onload=i.onreadystatechange=a((function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){i.onload=i.onreadystatechange=null;try{d.removeChild(i)}catch(r){}l=!0,function(){var e;if(void 0===r._rollbarDidLoad){e=new Error("rollbar.js did not load");for(var o,n,a,l,i=0;o=r._rollbarShims[i++];)for(o=o.messages||[];n=o.shift();)for(a=n.args||[],i=0;i<a.length;++i)if("function"==typeof(l=a[i])){l(e);break}}"function"==typeof t&&t(e)}()}})),d.insertBefore(i,s)},i.prototype.wrap=function(r,e,o){try{var n;if(n="function"==typeof e?e:function(){return e||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._rollbar_wrapped&&(r._rollbar_wrapped=function(){o&&"function"==typeof o&&o.apply(this,arguments);try{return r.apply(this,arguments)}catch(o){var e=o;throw e&&("string"==typeof e&&(e=new String(e)),e._rollbarContext=n()||{},e._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=e),e}},r._rollbar_wrapped._isWrap=!0,r.hasOwnProperty))for(var t in r)r.hasOwnProperty(t)&&(r._rollbar_wrapped[t]=r[t]);return r._rollbar_wrapped}catch(e){return r}};for(var p="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,captureEvent,captureDomContentLoaded,captureLoad".split(","),f=0;f<p.length;++f)i.prototype[p[f]]=u(p[f]);r.exports={setupShim:function(r,e){if(r){var o=e.globalAlias||"Rollbar";if("object"==typeof r[o])return r[o];r._rollbarShims={},r._rollbarWrappedError=null;var l=new c(e);return a((function(){e.captureUncaught&&(l._rollbarOldOnError=r.onerror,n.captureUncaughtExceptions(r,l,!0),e.wrapGlobalEventHandlers&&t(r,l,!0)),e.captureUnhandledRejections&&n.captureUnhandledRejections(r,l,!0);var a=e.autoInstrument;return!1!==e.enabled&&(void 0===a||!0===a||function(r){return!("object"!=typeof r||void 0!==r.page&&!r.page)}(a))&&r.addEventListener&&(r.addEventListener("load",l.captureLoad.bind(l)),r.addEventListener("DOMContentLoaded",l.captureDomContentLoaded.bind(l))),r[o]=l,l}))()}},Rollbar:c}},function(r,e,o){"use strict";function n(r,e,o,n){r._rollbarWrappedError&&(n[4]||(n[4]=r._rollbarWrappedError),n[5]||(n[5]=r._rollbarWrappedError._rollbarContext),r._rollbarWrappedError=null);var t=e.handleUncaughtException.apply(e,n);o&&o.apply(r,n),"anonymous"===t&&(e.anonymousErrorsPending+=1)}r.exports={captureUncaughtExceptions:function(r,e,o){if(r){var t;if("function"==typeof e._rollbarOldOnError)t=e._rollbarOldOnError;else if(r.onerror){for(t=r.onerror;t._rollbarOldOnError;)t=t._rollbarOldOnError;e._rollbarOldOnError=t}e.handleAnonymousErrors();var a=function(){var o=Array.prototype.slice.call(arguments,0);n(r,e,t,o)};o&&(a._rollbarOldOnError=t),r.onerror=a}},captureUnhandledRejections:function(r,e,o){if(r){"function"==typeof r._rollbarURH&&r._rollbarURH.belongsToShim&&r.removeEventListener("unhandledrejection",r._rollbarURH);var n=function(r){var o,n,t;try{o=r.reason}catch(r){o=void 0}try{n=r.promise}catch(r){n="[unhandledrejection] error getting `promise` from event"}try{t=r.detail,!o&&t&&(o=t.reason,n=t.promise)}catch(r){}o||(o="[unhandledrejection] error getting `reason` from event"),e&&e.handleUnhandledRejection&&e.handleUnhandledRejection(o,n)};n.belongsToShim=o,r._rollbarURH=n,r.addEventListener("unhandledrejection",n)}}}},function(r,e,o){"use strict";function n(r,e,o){if(e.hasOwnProperty&&e.hasOwnProperty("addEventListener")){for(var n=e.addEventListener;n._rollbarOldAdd&&n.belongsToShim;)n=n._rollbarOldAdd;var t=function(e,o,t){n.call(this,e,r.wrap(o),t)};t._rollbarOldAdd=n,t.belongsToShim=o,e.addEventListener=t;for(var a=e.removeEventListener;a._rollbarOldRemove&&a.belongsToShim;)a=a._rollbarOldRemove;var l=function(r,e,o){a.call(this,r,e&&e._rollbar_wrapped||e,o)};l._rollbarOldRemove=a,l.belongsToShim=o,e.removeEventListener=l}}r.exports=function(r,e,o){if(r){var t,a,l="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(t=0;t<l.length;++t)r[a=l[t]]&&r[a].prototype&&n(e,r[a].prototype,o)}}},function(r,e,o){"use strict";function n(r,e){this.impl=r(e,this),this.options=e,function(r){for(var e=function(r){return function(){var e=Array.prototype.slice.call(arguments,0);if(this.impl[r])return this.impl[r].apply(this.impl,e)}},o="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,_createItem,wrap,loadFull,shimId,captureEvent,captureDomContentLoaded,captureLoad".split(","),n=0;n<o.length;n++)r[o[n]]=e(o[n])}(n.prototype)}n.prototype._swapAndProcessMessages=function(r,e){var o,n,t;for(this.impl=r(this.options);o=e.shift();)n=o.method,t=o.args,this[n]&&"function"==typeof this[n]&&("captureDomContentLoaded"===n||"captureLoad"===n?this[n].apply(this,[t[0],o.ts]):this[n].apply(this,t));return this},r.exports=n},function(r,e,o){"use strict";r.exports=function(r){return function(e){if(!e&&!window._rollbarInitialized){for(var o,n,t=(r=r||{}).globalAlias||"Rollbar",a=window.rollbar,l=function(r){return new a(r)},i=0;o=window._rollbarShims[i++];)n||(n=o.handler),o.handler._swapAndProcessMessages(l,o.messages);window[t]=n,window._rollbarInitialized=!0}}}}]);
// End Rollbar Snippet.
</script>
<?php
}
/**
* Ensure the Rollbar browser snippet renders across relevant contexts.
*/
function simple_wp_rollbar_register_browser_snippet_hooks(): void {
add_action( 'wp_head', 'simple_wp_rollbar_print_browser_snippet', 1 );
add_action( 'admin_head', 'simple_wp_rollbar_print_browser_snippet', 1 );
add_action( 'login_head', 'simple_wp_rollbar_print_browser_snippet', 1 );
}
// The plugin could be loaded either before or after muplugins_loaded fires.
// We need to cover both scenarios.
if ( did_action( 'muplugins_loaded' ) ) {
simple_wp_rollbar_bootstrap_server();
simple_wp_rollbar_register_browser_snippet_hooks();
} else {
add_action( 'muplugins_loaded', 'simple_wp_rollbar_bootstrap_server', 5 );
add_action( 'muplugins_loaded', 'simple_wp_rollbar_register_browser_snippet_hooks', 5 );
}
/**
* Register the plugin's admin page so site admins can trigger diagnostic checks.
*/
function simple_wp_rollbar_register_admin_page(): void {
add_options_page(
__( 'Rollbar Integration', 'simple-wp-rollbar' ),
__( 'Rollbar Diagnostics', 'simple-wp-rollbar' ),
'manage_options',
'simple-wp-rollbar',
'simple_wp_rollbar_render_admin_page'
);
}
add_action( 'admin_menu', 'simple_wp_rollbar_register_admin_page' );
/**
* Render the admin page with quick actions for sending Rollbar test messages.
*/
function simple_wp_rollbar_render_admin_page(): void {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'simple-wp-rollbar' ) );
}
// Flags to help with later rendering.
$trigger_browser_test = false;
// Snapshot the token presence so we can surface helpful messaging.
$server_token = env( 'ROLLBAR_SERVER_ACCESS_TOKEN' );
$client_token = env( 'ROLLBAR_CLIENT_ACCESS_TOKEN' );
$has_server = ( false !== $server_token && '' !== $server_token );
$has_client = ( false !== $client_token && '' !== $client_token );
if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] && isset( $_POST['simple_wp_rollbar_action'] ) ) {
$action = sanitize_key( wp_unslash( $_POST['simple_wp_rollbar_action'] ) );
if ( 'test_php' === $action ) {
check_admin_referer( 'simple_wp_rollbar_test_php' );
if ( ! $has_server ) {
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_php_missing',
__( 'Cannot send PHP test message because the Rollbar server access token is not configured.', 'simple-wp-rollbar' ),
'error'
);
} elseif ( ! class_exists( Rollbar::class ) ) {
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_php_missing_sdk',
__( 'Cannot send PHP test message because the Rollbar PHP SDK is unavailable.', 'simple-wp-rollbar' ),
'error'
);
} else {
try {
Rollbar::log( 'info', 'Rollbar test message from SystemSeed WordPress plugin (PHP).' );
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_php_success',
__( 'PHP test message sent to Rollbar. Check your Rollbar project for delivery.', 'simple-wp-rollbar' ),
'updated'
);
} catch ( Throwable $throwable ) {
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_php_exception',
sprintf(
'%s %s',
__( 'Failed to send PHP test message:', 'simple-wp-rollbar' ),
esc_html( $throwable->getMessage() )
),
'error'
);
}
}
}
if ( 'test_browser' === $action ) {
check_admin_referer( 'simple_wp_rollbar_test_browser' );
if ( ! $has_client ) {
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_browser_missing',
__( 'Cannot send browser test message because the Rollbar client access token is not configured.', 'simple-wp-rollbar' ),
'error'
);
} else {
$trigger_browser_test = true;
add_settings_error(
'simple_wp_rollbar',
'simple_wp_rollbar_test_browser_success',
__( 'Browser test message queued. It will fire once the page finishes loading.', 'simple-wp-rollbar' ),
'updated'
);
}
}
}
// For convenience, output the current environment type.
printf(
'<div class="notice notice-info"><p>%s</p></div>',
esc_html(
sprintf(
/* translators: %s: the current environment. */
__( 'The current environment is %s.', 'simple-wp-rollbar' ),
env( 'APPLICATION_MODE' )
)
)
);
// Highlight missing configuration before the forms so it's instantly visible.
$php_submit_attributes = array();
$browser_submit_attributes = array();
if ( ! $has_server || ! $has_client ) {
$missing_tokens = array();
if ( ! $has_server ) {
$missing_tokens[] = __( 'ROLLBAR_SERVER_ACCESS_TOKEN', 'simple-wp-rollbar' );
$php_submit_attributes = array( 'disabled' => true );
}
if ( ! $has_client ) {
$missing_tokens[] = __( 'ROLLBAR_CLIENT_ACCESS_TOKEN', 'simple-wp-rollbar' );
$browser_submit_attributes = array( 'disabled' => true );
}
printf(
'<div class="notice notice-error"><p>%s</p></div>',
esc_html(
sprintf(
/* translators: %s: comma separated list of environment variables. */
__( 'Missing environment variables: %s. Test calls will fail until they are set.', 'simple-wp-rollbar' ),
implode( ', ', $missing_tokens )
)
)
);
}
// Surface any notices generated during processing.
settings_errors( 'simple_wp_rollbar' );
?>
<div class="wrap">
<h1><?php esc_html_e( 'Rollbar Diagnostics', 'simple-wp-rollbar' ); ?></h1>
<p><?php esc_html_e( 'Use the buttons below to send quick test messages to Rollbar and confirm both the PHP SDK and browser snippet are functioning.', 'simple-wp-rollbar' ); ?></p>
<div class="systemseed-rollbar-actions">
<form method="post">
<?php wp_nonce_field( 'simple_wp_rollbar_test_php' ); ?>
<input type="hidden" name="simple_wp_rollbar_action" value="test_php" />
<?php submit_button( __( 'Test Rollbar PHP', 'simple-wp-rollbar' ), 'primary', 'submit', false, $php_submit_attributes ); ?>
</form>
<form method="post" style="margin-top: 1em;">
<?php wp_nonce_field( 'simple_wp_rollbar_test_browser' ); ?>
<input type="hidden" name="simple_wp_rollbar_action" value="test_browser" />
<?php submit_button( __( 'Test Rollbar Browser JS', 'simple-wp-rollbar' ), 'secondary', 'submit', false, $browser_submit_attributes ); ?>
</form>
</div>
</div>
<?php
// Inject a simple script to emit the browser-side test once Rollbar is ready.
if ( $trigger_browser_test ) {
?>
<script>
(function () {
function sendRollbarBrowserTest() {
if ( ! window.Rollbar || typeof window.Rollbar.info !== 'function' ) {
console.warn('Rollbar JS not ready yet; retrying shortly.');
window.setTimeout(sendRollbarBrowserTest, 500);
return;
}
window.Rollbar.info('Rollbar test message from SystemSeed WordPress plugin (Browser JS).');
console.info('Rollbar browser test message dispatched.');
}
// Delay slightly so the Rollbar snippet has time to bootstrap.
window.setTimeout(sendRollbarBrowserTest, 200);
})();
</script>
<?php
}
}