Gambling/GamblingPlugin.php

107 lines
3.1 KiB
PHP
Raw Normal View History

2017-02-24 04:25:59 +00:00
<?php
if (!defined('GNUSOCIAL')) {
exit(1);
}
class GamblingPlugin extends Plugin
{
const VERSION = '0.0.1';
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 or $rolls > $obj->settings('max_rolls');
$bad_faces = $faces < 2 or $faces > $obj->settings('max_faces');
if ( $bad_rolls or $bad_faces ) {
$obj->roll_str = "Rolled: bad roll";
}
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;
}
}