Skip to content

Instantly share code, notes, and snippets.

@ssddanbrown
Last active July 13, 2023 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssddanbrown/821b7ef05bf7b24b46614c522460ce06 to your computer and use it in GitHub Desktop.
Save ssddanbrown/821b7ef05bf7b24b46614c522460ce06 to your computer and use it in GitHub Desktop.
bookstack-hack-http-call-on-tagged-page
<?php
use BookStack\Entities\Models\Page;
use BookStack\Activity\Models\View;
use BookStack\Users\Models\User;
use Illuminate\Support\Facades\Http;
// Enter the URL of your webhook endpoint between the two quote marks below.
$webhookUrl = '';
// If you want to change the name of the tag used, alter this.
// This is not case-sensitive.
$tagName = 'restricted';
// Function to send a notification for the given page and user.
function notifyIfPageTagged(int $pageId, int $userId, string $tagName, string $webhookUrl)
{
// Get the details of the page
/** @var Page $page */
$page = Page::query()->findOrFail($pageId, ['id', 'name', 'slug', 'book_id', 'book_slug']);
// Check if the page is tagged as we expect, otherwise exit
$tagged = $page->tags()->where('name', '=', $tagName)->exists();
if (!$tagged) {
return;
}
// Get the user that viewed the page
$user = User::query()->findOrFail($userId);
// Perform webhook call with below data, with a 3-second timeout limit
$webhookData = [
'text' => "User \"{$user->name}\" viewed restricted page \"{$page->name}\""
];
Http::timeout(3)->post($webhookUrl, $webhookData);
}
// Listen to the save event for stored views
View::saved(function (View $view) use ($tagName, $webhookUrl) {
// Skip the function if it's not a view for a page
if ($view->viewable_type !== 'page') {
return;
}
// Otherwise try to notify about the event, but catch and log errors in case things fails,
// so that we don't break main BookStack instance usage.
try {
notifyIfPageTagged($view->viewable_id, $view->user_id, $tagName, $webhookUrl);
} catch (Exception $exception) {
\Illuminate\Support\Facades\Log::info("Failed to notify on tagged page view, error: " . $exception->getMessage());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment