A (unofficial) WordPress plugin to report PHP errors to PAB.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Type:wordpress-plugin

0.1.1 2022-02-16 07:29 UTC

This package is auto-updated.

Last update: 2024-04-16 11:49:55 UTC


README

This plugin requires PHP 7.2+ but urges users to use a PHP version that is not end of life (EOL) and no longer supported. For an up-to-date list of PHP versions that are still supported see: http://php.net/supported-versions.php.

  • Version 0.1.* of this plugin will be the last to support PHP 7.2.

Install

  1. Clone git repository git clone git@bitbucket.org:studiocreativateam/pab-wp.git or install by composer composer require studiocreativateam/pab-wp.
  2. If you cloned the repository then you need to go to the pab-wp project folder and run composer install command to get the dependencies.
  3. Now you can zip the folder into a .zip file and upload it to WordPress plugins.
  4. Configure your keys as explained below
  5. Activate the plugin through the WordPress admin interface

Note: this plugin does not do anything by default and has no admin interface. A keys must be configured first.

Configuration

(Optionally) track PHP errors by adding this snippet to your wp-config.php and replace PAB_TOKEN with your actual project token:

define( 'WP_PAB_TOKEN', 'PAB_TOKEN' );

Add this snippet to your wp-config.php and replace PAB_PRIVATE_KEY with your actual private key:

define( 'WP_PAB_PRIVATE_KEY', 'PAB_PRIVATE_KEY' );

Note: Do not set the constants to disable the PHP tracker.

(Optionally) set the error types the PHP tracker will track:

define( 'WP_PAB_ERROR_TYPES', E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_USER_DEPRECATED );

(Optionally) If this flag is enabled, certain personally identifiable information is added by active integrations. Without this flag they are never added to the event, to begin with.

If possible, it’s recommended to turn on this feature and use the server side PII stripping to remove the values instead.

When enabled the current logged in user and IP address will be added to the event.

define( 'WP_PAB_SEND_DEFAULT_PII', true );

(Optionally) define a version of your site; by default the theme version will be used. This is used for tracking at which version of your site the error occurred. When combined with release tracking this is a very powerful feature.

define( 'WP_PAB_VERSION', 'v0.1.1' );

(Optionally) define an environment of your site. Defaults to unspecified.

define( 'WP_PAB_ENV', 'production' );

Filters

This plugin provides the following filters to plugin/theme developers.

Please note that some filters are fired when the PAB trackers are initialized so they won't fire if you define them in your theme or in a plugin that loads after WP PAB does.

Common to trackers

wp_pab_user_context (array)

You can use this filter to extend the PAB user context for both PHP and JS trackers.

WARNING: These values are exposed to the public in the JS tracker, so make sure you do not expose anything private!

Example usage:

add_filter( 'wp_pab_user_context', function ( array $user ) {
	return array_merge( $user, array(
		'a-custom-user-meta-key' => 'custom value',
	));
} );

Note: _This filter fires on the WordPress set_current_user action and only if the WP_PAB_SEND_DEFAULT_PII constant is set to true._

Specific to PHP tracker:

wp_pab_token (string)

You can use this filter to override the PAB token used for the PHP tracker.

WARNING: This is not recommended, please set the token using the WP_PAB_TOKEN constant in your wp-config.php!

Example usage:

add_filter( 'wp_pab_token', function ( $token ) {
	return 'xxxxxxxxxxxxxxxxxxxxxx';
} );

Note: _This filter fires on the WordPress after_setup_theme action. It is discouraged to use this and instead define the token in the wp-config.php using the WP_PAB_TOKEN constant_

wp_pab_scope (void)

You can use this filter to customize the PAB.

Example usage:

add_filter( 'wp_pab_scope', function ( \PAB\State\Scope $scope ) {
	$scope->setTag('my-custom-tag', 'tag-value');

	return $scope;
} );

Note: _This filter fires on the WordPress after_setup_theme action._

wp_pab_options

You can use this filter to customize the PAB.

Example usage:

add_filter( 'wp_pab_options', function ( \PAB\Options $options ) {
	// Only sample 90% of the events
	$options->setSampleRate(0.9);

	return $options;
} );

Note: Items prefixed with regex: in blacklistUrls and whitelistUrls option arrays will be translated into pure RegExp.

Advanced usages

High volume of notices

Many plugin in the WordPress ecosystem generate notices that are captured by the PAB plugin.

This can cause a high volume of events and even slower page loads because of those events being transmitted to PAB.

The prevent this you can set the following in your wp-config.php to filter out errors of the notice type.

define( 'WP_PAB_ERROR_TYPES', E_ALL & ~E_NOTICE );

Capturing handled exceptions

The best thing to do with an exception is to capture it yourself, however you might still want to know about it.

The PAB plugin only captures unhandled exceptions and fatal errors, to capture handled exception you can do the following:

try {
	myMethodThatCanThrowAnException();
} catch ( \Exception $e ) {
	// We are using wp_pab_safe to make sure this code runs even if the PAB plugin is disabled
	if ( function_exists( 'wp_pab_safe' ) ) {
		wp_pab_safe( function ( \PAB\State\HubInterface $client ) use ( $e ) {
			$client->captureException( $e );
		} );
	}

	wp_die( 'There was an error doing this thing you were doing, we have been notified!' );
}

If you need to attach extra data only for the handled exception, you could add:

$e = new Exception('Some exception I want to capture with extra data.');

if (function_exists('wp_pab_safe')) {
	wp_pab_safe(function (\PAB\State\HubInterface $client) use ($e) {
		$client->withScope(function (\PAB\State\Scope $scope) use ($client, $e) {
			$scope->setExtra('user_data', $e->getData());
			$client->captureException($e);
		});
	});
}

If you need to add data to the scope in every case use configureScope in wp_pab_scope filter.

Loading PAB before WordPress

Since WP PAB is a WordPress plugin it loads after WordPress and unless you are using a must-use plugin even after some other plugins loaded throwing errors which are not captured by PAB.

To remedy this you can opt to load the plugin from your wp-config.php file before WordPress is started.

It's really simple to do this by adding the following snippet to your wp-config.php before the /* That's all, stop editing! Happy blogging. */ comment:

require_once ABSPATH . 'wp-content/plugins/pab-wp/pab-wp.php';

Also make sure that any configuration options like WP_PAB_TOKEN are set before the snippet above otherwise they have no effect.

Capturing plugin errors

Since this plugin is called pab-wp it loads a bit late which could miss errors or notices occurring in plugins that load before it.

You can remedy this by loading WordPress PAB as a must-use plugin by creating the file wp-content/my-plugins/pab-wp.php (if the my-plugins directory does not exist you must create that too).

<?php

/**
 * Plugin Name: WordPress PAB
 * Plugin URI: https://studio-creativa.pl
 * Description: A (unofficial) WordPress plugin to report PHP errors to PAB.
 * Version: must-use-proxy
 * Author: Jacek Labudda
 * Author URI: https://studio-creativa.pl
 * License: MIT
 */

$wp_pab = ABSPATH . 'plugins/pab-wp/pab-wp.php';

// Do not crash in case the plugin is not installed
if ( ! file_exists( $wp_pab ) ) {
	return;
}

require $wp_pab;

Now pab-wp will load always and before all other plugins.

Note: We advise you leave the original pab-wp in the /wp-content/plugins folder to still have updates come in through the WordPress updater. However enabling or disabling does nothing if the above script is active (since it will always be enabled).

Capturing errors only from certain theme and/or plugin

This is an example on how to use the before_send callback of the PAB SDK to only capture errors occurring in a certain theme or plugin.

add_filter( 'wp_pab_options', function ( \PAB\Options $options ) {
	$options->setBeforeSendCallback( function ( \PAB\Event $event ) {
		$exceptions = $event->getExceptions();

		// No exceptions in the event? Send the event to PAB, it's most likely a log message
		if ( empty( $exceptions ) ) {
			return $event;
		}

		$stacktrace = $exceptions[0]->getStacktrace();

		// No stacktrace in the first exception? Send it to PAB just to be safe then
		if ( $stacktrace === null ) {
			return $event;
		}

		// Little helper and fallback for PHP versions without the str_contains function
		$strContainsHelper = function ( $haystack, $needle ) {
			if ( function_exists( 'str_contains' ) ) {
				return str_contains( $haystack, $needle );
			}

			return $needle !== '' && mb_strpos( $haystack, $needle ) !== false;
		};

		foreach ( $stacktrace->getFrames() as $frame ) {
			// Check the the frame happened inside our theme or plugin
			// Change THEME_NAME and PLUGIN_NAME to whatever is required
			// And / or modify this `if` statement to detect other variables
			if ( $strContainsHelper( $frame->getFile(), 'themes/THEME_NAME' )
				 || $strContainsHelper( $frame->getFile(), 'plugins/PLUGIN_NAME' )
			) {
				// Send the event to PAB
				return $event;
			}
		}

		// Stacktrace contained no frames in our theme and/or plugin? We send nothing to PAB
		return null;
	} );

	return $options;
} );

Modifying the PHP SDK ClientBuilder or options before initialization

Because the PHP SDK is initialized as quick as possible to capture early errors, it's impossible to modify the options or the ClientBuilder before the initialization with WordPress hooks.

There exists a way to modify the options and the ClientBuilder before the initialization of the PHP SDK by setting a callback using a constant called WP_PAB_CLIENTBUILDER_CALLBACK.

The callback will be executed whenever the plugin creates a new ClientBuilder instance to create a new PHP SDK client.

You would place the example below in your wp-config.php file to make sure it's available before the PHP SDK is initialized:

function wp_pab_clientbuilder_callback( \PAB\ClientBuilder $builder ): void {
    // For example, disabling the default integrations 
	$builder->getOptions()->setDefaultIntegrations( false );
}

define( 'WP_PAB_CLIENTBUILDER_CALLBACK', 'wp_pab_clientbuilder_callback' );

Security Vulnerabilities

If you discover a security vulnerability within WordPress PAB (pab-wp), please send an e-mail to Jacek Labudda at j.labudda@studio-creativa.pl. All security vulnerabilities will be swiftly addressed.

License

The WordPress PAB (pab-wp) plugin is open-sourced software licensed under the MIT license.