Gambling/GamblingPlugin.php

107 lines
3.2 KiB
PHP

<?php
if (!defined('GNUSOCIAL')) {
exit(1);
}
class GamblingPlugin extends Plugin
{
const VERSION = '0.0.2';
const ROLL_RE = '/\/roll\+(?<rolls>\d+)d(?<faces>\d+)/';
public $roll_str = null;
public $render_html = false;
static function settings($setting)
{
$settings['style'] = "span.dicerolls { font-weight: bold; border: 1px solid black; }";
$settings['max_rolls'] = 10;
$settings['max_faces'] = 100;
$configphpsettings = common_config('site','gambling') ?: array();
foreach($configphpsettings as $configphpsetting=>$value) {
$settings[$configphpsetting] = $value;
}
if(isset($settings[$setting])) {
return $settings[$setting];
}
else {
return false;
}
}
public function onEndShowStyles(Action $action)
{
$action->style(self::settings('style'));
}
public function onQvitterEndShowHeadElements(Action $action)
{
$this->onEndShowStyles($action);
}
function onStartNoticeSave(&$notice)
{
if (! $notice->is_local) return;
$obj = $this;
$render_dice = function($matches) use (&$obj) {
if (is_null($obj->roll_str)) {
$rolls = intval($matches[1]);
$faces = intval($matches[2]);
$bad_rolls = $rolls < 1 || $rolls > $self::settings('max_rolls');
$bad_faces = $faces < 2 || $faces > $self::settings('max_faces');
if ( $bad_rolls || $bad_faces ) {
$obj->roll_str = "Bad roll, The correct syntax is: '/roll+XdY' where X is max of " . self::settings('max_rolls'). "& Y is max of " . self::settings('max_faces') . ".";
}
else {
$total = 0;
$rolled_str = "Rolled: ";
for ($i = 1; $i <= $rolls; $i++)
{
$roll = random_int(1,$faces);
$total = $total + $roll;
$rolled_str .= $roll . ($i==$rolls ? ' ' : ', ');
}
$rolled_str = $rolled_str . ' = ' . $total . ' (' . $rolls . 'd' . $faces . ')';
$obj->roll_str = $rolled_str;
}
}
if ($obj->render_html) {
return '<span class="dicerolls">' . $obj->roll_str . '</span>';
}
else {
return $obj->roll_str;
}
};
$notice->content = preg_replace_callback(self::ROLL_RE, $render_dice, $notice->content, 1);
$this->render_html = true;
$notice->rendered = preg_replace_callback(self::ROLL_RE, $render_dice, $notice->rendered, 1);
}
function onPluginVersion(array &$versions)
{
$versions[] = array('name' => 'Gambling',
'version' => self::VERSION,
'author' => 'MoonMan',
'homepage' => 'https://gitgud.io/ShitposterClub/Gambling/',
'description' =>
_m('Dice rolling and maybe other things'));
return true;
}
}