pbot/PBot/Utils/ValidateString.pm

39 lines
946 B
Perl
Raw Normal View History

2017-09-05 09:18:03 +02:00
package PBot::Utils::ValidateString;
2018-04-09 04:34:24 +02:00
use warnings;
use strict;
2017-09-05 09:18:03 +02:00
2019-07-11 03:40:53 +02:00
use feature 'unicode_strings';
2017-09-05 09:18:03 +02:00
require Exporter;
2020-02-15 23:38:32 +01:00
our @ISA = qw/Exporter/;
2017-09-05 09:18:03 +02:00
our @EXPORT = qw/validate_string/;
2018-04-09 04:34:24 +02:00
use JSON;
2017-09-05 09:18:03 +02:00
sub validate_string {
2020-02-15 23:38:32 +01:00
my ($string, $max_length) = @_;
2018-04-09 04:34:24 +02:00
2020-02-15 23:38:32 +01:00
return $string if not defined $string or not length $string;
$max_length = 1024 * 8 if not defined $max_length;
2018-04-09 04:34:24 +02:00
2020-02-17 00:55:48 +01:00
local $@;
2020-02-15 23:38:32 +01:00
eval {
my $h = decode_json($string);
foreach my $k (keys %$h) { $h->{$k} = substr $h->{$k}, 0, $max_length unless $max_length <= 0; }
$string = encode_json($h);
};
2018-04-09 04:34:24 +02:00
2020-02-15 23:38:32 +01:00
if ($@) {
# not a json string
$string = substr $string, 0, $max_length unless $max_length <= 0;
}
2018-04-09 04:34:24 +02:00
2020-02-15 23:38:32 +01:00
# $string =~ s/(\P{PosixGraph})/my $ch = $1; if ($ch =~ m{[\s\x03\x02\x1d\x1f\x16\x0f]}) { $ch } else { sprintf "\\x%02X", ord $ch }/ge;
# $string = substr $string, 0, $max_length unless $max_length <= 0;
2018-04-09 04:34:24 +02:00
2020-02-15 23:38:32 +01:00
return $string;
2017-09-05 09:18:03 +02:00
}
1;