diff --git a/inc/functions.php b/inc/functions.php index 644cefbe..bca8d1d1 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -2786,6 +2786,51 @@ function diceRoller($post) { } } +/** + * Rolls a dice and generates the appropiate html from the markup. + * @param array $matches The array of the matches according to the default configuration. + * 1 -> The number of dices to roll. + * 3 -> The number faces of the dices. + * 4 -> The offset to apply to the dice. + * @param string $img_path Path to the image to use. Null if none. + * @return string The html to replace the original markup with. + */ +function handle_dice_roll_markup(array $matches, ?string $img_path): string { + function get_or_default(array $arr, int $index, int $default) { + return (isset($arr[$index]) && is_numeric($arr[$index])) ? (int)$arr[$index] : $default; + } + global $config; + + $dice_count = get_or_default($matches, 1, 1); + $dice_faces = get_or_default($matches, 3, 6); + $dice_offset = get_or_default($matches, 4, 0); + + // Clamp between 1 and max_roll_count. + $dice_count = max(min($dice_count, $config['max_roll_count']), 1); + // Must be at least 2. + if ($dice_faces < 2) { + $dice_faces = 6; + } + + $acc = ''; + $text = "$dice_count d $dice_faces + $dice_offset"; + for ($i = 0; $i < $dice_count; $i++) { + $res = $dice_offset + mt_rand(0, $dice_faces); + if ($img_path === null) { + $fmt = "$text $res"; + } else { + $fmt = "$text $res"; + } + if (empty($acc)) { + $acc = $fmt; + } else { + $acc .= " $fmt"; + } + } + + return $acc; +} + function slugify($post) { global $config;