treebird/perl/string_helpers.pm
nekobit 7d0de2754f Titles, Emojis, Greentexts, and more
FossilOrigin-Name: 7166edf7fcd136ffbda39d2f36e96832690cf978a1c5df4bb6d172f8a2e905ac
2022-07-31 05:59:21 +00:00

47 lines
1.3 KiB
Perl

package string_helpers;
use strict;
use warnings;
use HTML::Escape 'escape_html';
use Exporter 'import';
our @EXPORT = qw( reltime_to_str greentextify emojify format_username );
sub reltime_to_str
{
my $since = time() - $_[0];
return $since . 's' if $since < 60;
return int($since / 60) . 'm' if $since < 60 * 60;
return int($since / (60 * 60)) . 'h' if $since < 60 * 60 * 24;
return int($since / (60 * 60 * 24)) . 'd' if $since < 60 * 60 * 24 * 31;
return int($since / (60 * 60 * 24 * 31)) . 'mon' if $since < 60 * 60 * 24 * 365;
return int($since / (60 * 60 * 24 * 365)) . 'yr';
}
sub greentextify
{
my $text = shift;
$text =~ s/((?:^|<br\/?>| )&gt;.*?)(?:<br\/?>|$)/<span class="greentext">$1<\/span><br>/gs;
$text =~ s/((?:^|<br\/?>| )&lt;.*?)(?:<br\/?>|$)/<span class="bluetext">$1<\/span><br>/gs;
$text =~ s/((?:^|<br\/?>| )\^.*?)(?:<br\/?>|$)/<span class="yellowtext">$1<\/span><br>/gs;
$text;
}
sub emojify
{
my ($text, $emojis) = @_;
foreach my $emoji (@{$emojis})
{
my $emo = $emoji->{shortcode};
my $url = $emoji->{url};
$text =~ s/:$emo:/<img class="emoji" src="$url" loading="lazy">/gsi;
}
$text;
}
sub format_username
{
my $username = shift;
emojify escape_html($username);
}