Text.pm 22.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
10
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
IKEDA Soji's avatar
IKEDA Soji committed
11
12
# Copyright 2018, 2020 The Sympa Community. See the AUTHORS.md
# file at the top-level directory of this distribution and at
13
# <https://github.com/sympa-community/sympa.git>.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package Sympa::Tools::Text;

use strict;
use warnings;
32
use feature qw(fc);
33
use Encode qw();
sikeda's avatar
sikeda committed
34
use English qw(-no_match_vars);
35
use Encode::MIME::Header;    # 'MIME-Q' encoding.
36
use HTML::Entities qw();
37
use MIME::EncWords;
38
use Text::LineFold;
39
use Unicode::GCString;
40
use URI::Escape qw();
41
BEGIN { eval 'use Unicode::Normalize qw()'; }
42
BEGIN { eval 'use Unicode::UTF8 qw()'; }
43

IKEDA Soji's avatar
IKEDA Soji committed
44
use Sympa::Language;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use Sympa::Regexps;

# Old name: tools::addrencode().
sub addrencode {
    my $addr    = shift;
    my $phrase  = (shift || '');
    my $charset = (shift || 'utf8');
    my $comment = (shift || '');

    return undef unless $addr =~ /\S/;

    if ($phrase =~ /[^\s\x21-\x7E]/) {
        $phrase = MIME::EncWords::encode_mimewords(
            Encode::decode('utf8', $phrase),
            'Encoding'    => 'A',
            'Charset'     => $charset,
            'Replacement' => 'FALLBACK',
            'Field'       => 'Resent-Sender', # almost longest
            'Minimal'     => 'DISPNAME',      # needs MIME::EncWords >= 1.012.
        );
    } elsif ($phrase =~ /\S/) {
        $phrase =~ s/([\\\"])/\\$1/g;
        $phrase = '"' . $phrase . '"';
    }
    if ($comment =~ /[^\s\x21-\x27\x2A-\x5B\x5D-\x7E]/) {
        $comment = MIME::EncWords::encode_mimewords(
            Encode::decode('utf8', $comment),
            'Encoding'    => 'A',
            'Charset'     => $charset,
            'Replacement' => 'FALLBACK',
            'Minimal'     => 'DISPNAME',
        );
    } elsif ($comment =~ /\S/) {
        $comment =~ s/([\\\"])/\\$1/g;
    }

    return
82
          ($phrase =~ /\S/  ? "$phrase "    : '')
83
84
85
86
        . ($comment =~ /\S/ ? "($comment) " : '')
        . "<$addr>";
}

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Old names: tools::clean_email(), tools::get_canonical_email().
sub canonic_email {
    my $email = shift;

    return undef unless defined $email;

    # Remove leading and trailing white spaces.
    $email =~ s/\A\s+//;
    $email =~ s/\s+\z//;

    # Lower-case.
    $email =~ tr/A-Z/a-z/;

    return (length $email) ? $email : undef;
}

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# Old name: tools::clean_msg_id().
sub canonic_message_id {
    my $msg_id = shift;

    return $msg_id unless defined $msg_id;

    chomp $msg_id;

    if ($msg_id =~ /\<(.+)\>/) {
        $msg_id = $1;
    }

    return $msg_id;
}

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
sub canonic_text {
    my $text = shift;

    return undef unless defined $text;

    # Normalize text. See also discussion on
    # https://listes.renater.fr/sympa/arc/sympa-developpers/2018-03/thrd1.html
    #
    # N.B.: Corresponding modules are optional by now, and should be
    # mandatory in the future.
    my $utext;
    if (Encode::is_utf8($text)) {
        $utext = $text;
    } elsif ($Unicode::UTF8::VERSION) {
        no warnings 'utf8';
        $utext = Unicode::UTF8::decode_utf8($text);
    } else {
        $utext = Encode::decode_utf8($text);
    }
    if ($Unicode::Normalize::VERSION) {
        $utext = Unicode::Normalize::normalize('NFC', $utext);
    }

    # Remove DOS linefeeds (^M) that cause problems with Outlook 98, AOL,
    # and EIMS:
    $utext =~ s/\r\n|\r/\n/g;

    if (Encode::is_utf8($text)) {
        return $utext;
    } else {
        return Encode::encode_utf8($utext);
    }
}

sub slurp {
    my $path = shift;

    my $ifh;
    return undef unless open $ifh, '<', $path;
    my $text = do { local $RS; <$ifh> };
    close $ifh;

    return canonic_text($text);
}

163
164
165
166
167
sub wrap_text {
    my $text = shift;
    my $init = shift;
    my $subs = shift;
    my $cols = shift;
168

169
170
    $init //= '';
    $subs //= '';
171
    $cols //= 78;
172
173
    return $text unless $cols;

174
    my $email_re = Sympa::Regexps::email();
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    my $linefold = Text::LineFold->new(
        Language   => Sympa::Language->instance->get_lang,
        Prep       => 'NONBREAKURI',
        prep       => [$email_re, sub { shift; @_ }],
        ColumnsMax => $cols,
        Format     => sub {
            shift;
            my $event = shift;
            my $str   = shift;
            if ($event =~ /^eo/)     { return "\n"; }
            if ($event =~ /^so[tp]/) { return $init . $str; }
            if ($event eq 'sol')     { return $subs . $str; }
            undef;
        },
    );

    my $t = Encode::is_utf8($text) ? $text : Encode::decode_utf8($text);

    my $ret = '';
    while (1000 < length $t) {
        my $s = substr $t, 0, 1000;
        $ret .= $linefold->break_partial($s);
        $t = substr $t, 1000;
    }
    $ret .= $linefold->break_partial($t) if length $t;
    $ret .= $linefold->break_partial(undef);

    return Encode::is_utf8($text) ? $ret : Encode::encode_utf8($ret);
203
204
}

205
206
207
208
209
210
211
212
213
214
sub decode_filesystem_safe {
    my $str = shift;
    return '' unless defined $str and length $str;

    $str = Encode::encode_utf8($str) if Encode::is_utf8($str);
    # On case-insensitive filesystem "_XX" along with "_xx" should be decoded.
    $str =~ s/_([0-9A-Fa-f]{2})/chr hex "0x$1"/eg;
    return $str;
}

215
216
217
218
219
220
221
sub decode_html {
    my $str = shift;

    Encode::encode_utf8(
        HTML::Entities::decode_entities(Encode::decode_utf8($str)));
}

222
223
224
225
226
227
228
229
230
sub encode_filesystem_safe {
    my $str = shift;
    return '' unless defined $str and length $str;

    $str = Encode::encode_utf8($str) if Encode::is_utf8($str);
    $str =~ s/([^-+.0-9\@A-Za-z])/sprintf '_%02x', ord $1/eg;
    return $str;
}

231
sub encode_html {
Luc Didry's avatar
Luc Didry committed
232
    my $str = shift;
233
    my $additional_unsafe = shift || '';
234

235
    HTML::Entities::encode_entities($str, '<>&"' . $additional_unsafe);
236
237
}

238
239
240
241
242
243
244
245
246
247
248
249
250
sub encode_uri {
    my $str     = shift;
    my %options = @_;

    # Note: URI-1.35 (URI::Escape 3.28) or later is required.
    return Encode::encode_utf8(
        URI::Escape::uri_escape_utf8(
            Encode::decode_utf8($str),
            '^-A-Za-z0-9._~' . (exists $options{omit} ? $options{omit} : '')
        )
    );
}

251
# Old name: tools::escape_chars().
252
253
# Moved to: Sympa::Upgrade::_escape_chars()
#sub escape_chars;
254
255

# Old name: tt2::escape_url().
sikeda's avatar
sikeda committed
256
# DEPRECATED.  Use Sympa::Tools::Text::escape_uri() or
257
# Sympa::Tools::Text::mailtourl().
sikeda's avatar
sikeda committed
258
#sub escape_url;
259

260
261
262
sub foldcase {
    my $str = shift;

263
264
    return '' unless defined $str and length $str;
    return Encode::encode_utf8(fc(Encode::decode_utf8($str)));
265
266
}

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
my %legacy_charsets = (
    'ar'    => [qw(iso-8859-6)],
    'bs'    => [qw(iso-8859-2)],
    'cs'    => [qw(iso-8859-2)],
    'eo'    => [qw(iso-8859-3)],
    'et'    => [qw(iso-8859-4)],
    'he'    => [qw(iso-8859-8)],
    'hr'    => [qw(iso-8859-2)],
    'hu'    => [qw(iso-8859-2)],
    'ja'    => [qw(euc-jp cp932 MacJapanese)],
    'kl'    => [qw(iso-8859-4)],
    'ko'    => [qw(cp949)],
    'lt'    => [qw(iso-8859-4)],
    'lv'    => [qw(iso-8859-4)],
    'mt'    => [qw(iso-8859-3)],
    'pl'    => [qw(iso-8859-2)],
    'ro'    => [qw(iso-8859-2)],
284
    'ru'    => [qw(koi8-r cp1251)],               # cp866? MacCyrillic?
285
286
    'sk'    => [qw(iso-8859-2)],
    'sl'    => [qw(iso-8859-2)],
287
    'th'    => [qw(iso-8859-11 cp874 MacThai)],
288
    'tr'    => [qw(iso-8859-9)],
289
    'uk'    => [qw(koi8-u)],                      # MacUkrainian?
290
291
292
293
294
295
296
297
298
299
300
    'zh-CN' => [qw(euc-cn)],
    'zh-TW' => [qw(big5-eten)],
);

sub guessed_to_utf8 {
    my $text  = shift;
    my @langs = @_;

    return Encode::encode_utf8($text) if Encode::is_utf8($text);
    return $text
        unless defined $text
301
302
        and length $text
        and $text =~ /[^\x00-\x7F]/;
303
304

    my $utf8;
305
306
307
308
309
310
311
312
313
314
315
316
317
    if ($Unicode::UTF8::VERSION) {
        $utf8 =
            eval { Unicode::UTF8::decode_utf8($text, Encode::FB_CROAK()) };
    }
    unless (defined $utf8) {
        foreach my $charset (map { $_ ? @$_ : () } @legacy_charsets{@langs}) {
            $utf8 =
                eval { Encode::decode($charset, $text, Encode::FB_CROAK()) };
            last if defined $utf8;
        }
    }
    unless (defined $utf8) {
        $utf8 = Encode::decode('iso-8859-1', $text);
318
    }
319
320
321
322

    # Apply NFC: e.g. for modified-NFD by Mac OS X.
    $utf8 = Unicode::Normalize::normalize('NFC', $utf8)
        if $Unicode::Normalize::VERSION;
323

324
325
326
    return Encode::encode_utf8($utf8);
}

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
sub mailtourl {
    my $text    = shift;
    my %options = @_;

    my $dtext =
          (not defined $text)   ? ''
        : $options{decode_html} ? Sympa::Tools::Text::decode_html($text)
        :                         $text;
    $dtext =~ s/\A\s+//;
    $dtext =~ s/\s+\z//;
    $dtext =~ s/(?:\r\n|\r|\n)(?=[ \t])//g;
    $dtext =~ s/\r\n|\r|\n/ /g;

    # The ``@'' in email address should not be encoded because some MUAs
    # aren't able to decode ``%40'' in e-mail address of mailto: URL.
    # Contrary, ``@'' in query component should be encoded because some
    # MUAs take it for a delimiter to separate URL from the rest.
    my ($format, $utext, $qsep);
    if ($dtext =~ /[()<>\[\]:;,\"\s]/) {
        # Use "to" header if source text includes any of RFC 5322
        # "specials", minus ``@'' and ``\'', plus whitespaces.
        $format = 'mailto:?to=%s%s';
        $utext  = Sympa::Tools::Text::encode_uri($dtext);
        $qsep   = '&';
    } else {
        $format = 'mailto:%s%s';
        $utext  = Sympa::Tools::Text::encode_uri($dtext, omit => '@');
        $qsep   = '?';
    }
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    my $qstring = _url_query_string(
        $options{query},
        decode_html => $options{decode_html},
        leadchar    => $qsep,
        sepchar     => '&',
        trim_values => 1,
    );

    return sprintf $format, $utext, $qstring;
}

sub _url_query_string {
    my $query   = shift;
    my %options = @_;
370
371

    unless (ref $query eq 'HASH' and %$query) {
372
        return '';
373
    } else {
374
375
376
377
        my $decode_html = $options{decode_html};
        my $trim_values = $options{trim_values};
        return ($options{leadchar} || '?') . join(
            ($options{sepchar} || ';'),
378
379
            map {
                my ($dkey, $dval) = map {
380
381
382
                          (not defined $_) ? ''
                        : $decode_html ? Sympa::Tools::Text::decode_html($_)
                        :                $_;
383
                } ($_, $query->{$_});
384
                if ($trim_values and lc $dkey ne 'body') {
385
386
387
388
389
390
391
392
393
                    $dval =~ s/\A\s+//;
                    $dval =~ s/\s+\z//;
                    $dval =~ s/(?:\r\n|\r|\n)(?=[ \t])//g;
                    $dval =~ s/\r\n|\r|\n/ /g;
                }

                sprintf '%s=%s',
                    Sympa::Tools::Text::encode_uri($dkey),
                    Sympa::Tools::Text::encode_uri($dval);
394
            } sort keys %$query
395
396
397
398
        );
    }
}

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
sub pad {
    my $str   = shift;
    my $width = shift;

    return $str unless $width and defined $str;

    my $ustr = Encode::is_utf8($str) ? $str : Encode::decode_utf8($str);
    my $cols = Unicode::GCString->new($ustr)->columns;

    unless ($cols < abs $width) {
        return $str;
    } elsif ($width < 0) {
        return $str . (' ' x (-$width - $cols));
    } else {
        return (' ' x ($width - $cols)) . $str;
    }
}

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# Old name: tools::qdecode_filename().
sub qdecode_filename {
    my $filename = shift;

    ## We don't use MIME::Words here because it does not encode properly
    ## Unicode
    ## Check if string is already Q-encoded first
    #if ($filename =~ /\=\?UTF-8\?/) {
    $filename = Encode::encode_utf8(Encode::decode('MIME-Q', $filename));
    #}

    return $filename;
}

# Old name: tools::qencode_filename().
sub qencode_filename {
    my $filename = shift;

    ## We don't use MIME::Words here because it does not encode properly
    ## Unicode
    ## Check if string is already Q-encoded first
    ## Also check if the string contains 8bit chars
    unless ($filename =~ /\=\?UTF-8\?/
        || $filename =~ /^[\x00-\x7f]*$/) {

        ## Don't encode elements such as .desc. or .url or .moderate
        ## or .extension
        my $part = $filename;
        my ($leading, $trailing);
        $leading  = $1 if ($part =~ s/^(\.desc\.)//);    ## leading .desc
        $trailing = $1 if ($part =~ s/((\.\w+)+)$//);    ## trailing .xx

        my $encoded_part = MIME::EncWords::encode_mimewords(
            $part,
            Charset    => 'utf8',
            Encoding   => 'q',
            MaxLineLen => 1000,
            Minimal    => 'NO'
        );

        $filename = $leading . $encoded_part . $trailing;
    }

    return $filename;
}

IKEDA Soji's avatar
IKEDA Soji committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
sub clip {
    my $string = shift;
    return undef unless @_;
    my $length = shift;

    my ($gcstr, $blen);
    if (ref $string eq 'Unicode::GCString') {
        $gcstr = $string;
        $blen  = length Encode::encode_utf8($string->as_string);
    } elsif (Encode::is_utf8($string)) {
        $gcstr = Unicode::GCString->new($string);
        $blen  = length Encode::encode_utf8($string);
    } else {
        $gcstr = Unicode::GCString->new(Encode::decode_utf8($string));
        $blen  = length $string;
    }

    $length += $blen if $length < 0;
    return '' if $length < 0;             # out of range
    return $string if $blen <= $length;

    my $result = $gcstr->substr(0, _gc_length($gcstr, $length));

    if (ref $string eq 'Unicode::GCString') {
        return $result;
    } elsif (Encode::is_utf8($string)) {
        return $result->as_string;
    } else {
        return Encode::encode_utf8($result->as_string);
    }
}

sub _gc_length {
    my $gcstr  = shift;
    my $length = shift;

    return 0 unless $gcstr->length;
    return 0 unless $length;

    my ($shorter, $longer) = (0, $gcstr->length);
    while ($shorter < $longer) {
        my $cur = ($shorter + $longer + 1) >> 1;
        my $elen =
            length Encode::encode_utf8($gcstr->substr(0, $cur)->as_string);
        if ($elen <= $length) {
            $shorter = $cur;
        } else {
            $longer = $cur - 1;
        }
    }

    return $shorter;
}

517
# Old name: tools::unescape_chars().
518
519
# Moved to: Sympa::Upgrade::_unescape_chars().
#sub unescape_chars;
520
521
522
523
524
525
526
527
528
529
530
531
532
533

# Old name: tools::valid_email().
sub valid_email {
    my $email = shift;

    my $email_re = Sympa::Regexps::email();
    return undef unless $email =~ /^${email_re}$/;

    # Forbidden characters.
    return undef if $email =~ /[\|\$\*\?\!]/;

    return 1;
}

534
535
536
537
538
539
540
541
542
sub weburl {
    my $base    = shift;
    my $paths   = shift;
    my %options = @_;

    my @paths = map {
        Sympa::Tools::Text::encode_uri(
              (not defined $_)      ? ''
            : $options{decode_html} ? Sympa::Tools::Text::decode_html($_)
543
            :                         $_
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
        );
    } @{$paths || []};

    my $qstring = _url_query_string(
        $options{query},
        decode_html => $options{decode_html},
        sepchar     => '&',
    );

    my $fstring;
    my $fragment = $options{fragment};
    if (defined $fragment) {
        $fstring = '#'
            . Sympa::Tools::Text::encode_uri(
            $options{decode_html}
            ? Sympa::Tools::Text::decode_html($fragment)
            : $fragment
            );
    } else {
        $fstring = '';
    }

    return sprintf '%s%s%s', join('/', grep { defined $_ } ($base, @paths)),
        $qstring, $fstring;
}

570
1;
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
__END__

=encoding utf-8

=head1 NAME

Sympa::Tools::Text - Text-related functions

=head1 DESCRIPTION

This package provides some text-related functions.

=head2 Functions

=over

587
588
589
590
=item addrencode ( $addr, [ $phrase, [ $charset, [ $comment ] ] ] )

Returns formatted (and encoded) name-addr as RFC5322 3.4.

591
592
593
594
595
=item canonic_email ( $email )

I<Function>.
Returns canonical form of e-mail address.

596
Leading and trailing white spaces are removed.
597
598
599
600
Latin letters without accents are lower-cased.

For malformed inputs returns C<undef>.

601
602
603
604
605
=item canonic_message_id ( $message_id )

Returns canonical form of message ID without trailing or leading whitespaces
or C<E<lt>>, C<E<gt>>.

606
607
608
609
610
611
612
613
=item canonic_text ( $text )

Canonicalizes text.
C<$text> should be a binary string encoded by UTF-8 character set or
a Unicode string.
Forbidden sequences in binary string will be replaced by
U+FFFD REPLACEMENT CHARACTERs, and Normalization Form C (NFC) will be applied.

IKEDA Soji's avatar
IKEDA Soji committed
614
615
616
617
618
619
620
=item clip ( $string, $length )

I<Function>.
Clips $string according to $length by bytes,
considering boundary of grapheme clusters.
UTF-8 is assumed for $string as bytestring.

sikeda's avatar
sikeda committed
621
=item decode_filesystem_safe ( $str )
622
623

I<Function>.
sikeda's avatar
sikeda committed
624
Decodes a string encoded by encode_filesystem_safe().
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639

Parameter:

=over

=item $str

String to be decoded.

=back

Returns:

Decoded string, stripped C<utf8> flag if any.

sikeda's avatar
sikeda committed
640
=item decode_html ( $str )
641
642

I<Function>.
sikeda's avatar
sikeda committed
643
Decodes HTML entities in a string encoded by UTF-8 or a Unicode string.
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658

Parameter:

=over

=item $str

String to be decoded.

=back

Returns:

Decoded string, stripped C<utf8> flag if any.

sikeda's avatar
sikeda committed
659
=item encode_filesystem_safe ( $str )
660
661

I<Function>.
sikeda's avatar
sikeda committed
662
Encodes a string $str to be suitable for filesystem.
663
664
665
666
667
668
669
670
671
672
673
674
675

Parameter:

=over

=item $str

String to be encoded.

=back

Returns:

sikeda's avatar
sikeda committed
676
677
678
679
Encoded string, stripped C<utf8> flag if any.
All bytes except C<'-'>, C<'+'>, C<'.'>, C<'@'>
and alphanumeric characters are encoded to sequences C<'_'> followed by
two hexdigits.
680

sikeda's avatar
sikeda committed
681
682
Note that C<'/'> will also be encoded.

683
=item encode_html ( $str, [ $additional_unsafe ] )
684
685

I<Function>.
sikeda's avatar
sikeda committed
686
Encodes characters in a string $str to HTML entities.
687
By default
sikeda's avatar
sikeda committed
688
C<'E<lt>'>, C<'E<gt>'>, C<'E<amp>'> and C<'E<quot>'> are encoded.
689
690
691
692
693
694
695
696
697

Parameter:

=over

=item $str

String to be encoded.

698
699
700
701
702
703
=item $additional_unsafe

Character or range of characters additionally encoded as entity references.

This optional parameter was introduced on Sympa 6.2.37b.3.

704
705
706
707
=back

Returns:

sikeda's avatar
sikeda committed
708
Encoded string, I<not> stripping utf8 flag if any.
709

710
711
=item encode_uri ( $str, [ omit => $chars ] )

sikeda's avatar
sikeda committed
712
713
714
I<Function>.
Encodes potentially unsafe characters in the string using "percent" encoding
suitable for URIs.
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735

Parameters:

=over

=item $str

String to be encoded.

=item omit =E<gt> $chars

By default, all characters except those defined as "unreserved" in RFC 3986
are encoded, that is, C<[^-A-Za-z0-9._~]>.
If this parameter is given, it will prevent encoding additional characters.

=back

Returns:

Encoded string, stripped C<utf8> flag if any.

736
737
=item escape_chars ( $str )

738
739
B<Deprecated>.
Use L</encode_filesystem_safe>.
740

741
Escape weird characters.
742
743
744

=item escape_url ( $str )

sikeda's avatar
sikeda committed
745
DEPRECATED.
746
747
Would be better to use L</"encode_uri"> or L</"mailtourl">.

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
=item foldcase ( $str )

I<Function>.
Returns "fold-case" string suitable for case-insensitive match.
For example, a code below looks for a needle in haystack not regarding case,
even if they are non-ASCII UTF-8 strings.

  $haystack = Sympa::Tools::Text::foldcase($HayStack);
  $needle   = Sympa::Tools::Text::foldcase($NeedLe);
  if (index $haystack, $needle >= 0) {
      ...
  }

Parameter:

=over

=item $str

A string.

=back

771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
=item guessed_to_utf8( $text, [ lang, ... ] )

I<Function>.
Guesses text charset considering language context
and returns the text reencoded by UTF-8.

Parameters:

=over

=item $text

Text to be reencoded.

=item lang, ...

Language tag(s) which may be given by L<Sympa::Language/"implicated_langs">.

=back

Returns:

Reencoded text.
If any charsets could not be guessed, C<iso-8859-1> will be used
as the last resort, just because it covers full range of 8-bit.

sikeda's avatar
sikeda committed
797
798
799
=item mailtourl ( $email, [ decode_html =E<gt> 1 ],
[ query =E<gt> {key =E<gt> val, ...} ] )

sikeda's avatar
sikeda committed
800
I<Function>.
sikeda's avatar
sikeda committed
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
Constructs a C<mailto:> URL for given e-mail.

Parameters:

=over

=item $email

E-mail address.

=item decode_html =E<gt> 1

If set, arguments are assumed to include HTML entities.

=item query =E<gt> {key =E<gt> val, ...}

Optional query.

=back

Returns:

Constructed URL.

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
=item pad ( $str, $width )

Pads space a string so that result will not be narrower than given width.

Parameters:

=over

=item $str

A string.

=item $width

If $width is false value or width of $str is not less than $width,
does nothing.
If $width is less than C<0>, pads right.
Otherwise, pads left.

=back

Returns:

Padded string.

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
=item qdecode_filename ( $filename )

Q-Decodes web file name.

ToDo:
This should be obsoleted in the future release: Would be better to use
L</decode_filesystem_safe>.

=item qencode_filename ( $filename )

Q-Encodes web file name.

ToDo:
This should be obsoleted in the future release: Would be better to use
L</encode_filesystem_safe>.

866
867
868
869
870
871
=item slurp ( $file )

Get entire content of the file.
Normalization by canonic_text() is applied.
C<$file> is the path to text file.

872
873
=item unescape_chars ( $str )

874
875
B<Deprecated>.
Use L</decode_filesystem_safe>.
876

877
Unescape weird characters.
878
879
880
881
882

=item valid_email ( $string )

Basic check of an email address.

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
=item weburl ( $base, \@paths, [ decode_html =E<gt> 1 ],
[ fragment =E<gt> $fragment ], [ query =E<gt> \%query ] )

Constructs a C<http:> or C<https:> URL under given base URI.

Parameters:

=over

=item $base

Base URI.

=item \@paths

Additional path components.

=item decode_html =E<gt> 1

If set, arguments are assumed to include HTML entities.
Exception is $base:
It is assumed not to include entities.

=item fragment =E<gt> $fragment

Optional fragment.

=item query =E<gt> \%query

Optional query.

=back

Returns:

A URI.

sikeda's avatar
sikeda committed
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
=item wrap_text ( $text, [ $init_tab, [ $subsequent_tab, [ $cols ] ] ] )

I<Function>.
Returns line-wrapped text.

Parameters:

=over

=item $text

The text to be folded.

=item $init_tab

Indentation prepended to the first line of paragraph.
Default is C<''>, no indentation.

=item $subsequent_tab

Indentation prepended to each subsequent line of folded paragraph.
Default is C<''>, no indentation.

=item $cols

Max number of columns of folded text.
Default is C<78>.

=back

950
951
=back

952
953
954
955
956
957
958
=head1 HISTORY

L<Sympa::Tools::Text> appeared on Sympa 6.2a.41.

decode_filesystem_safe() and encode_filesystem_safe() were added
on Sympa 6.2.10.

959
decode_html(), encode_html(), encode_uri() and mailtourl()
sikeda's avatar
sikeda committed
960
were added on Sympa 6.2.14, and escape_url() was deprecated.
961

962
guessed_to_utf8() and pad() were added on Sympa 6.2.17.
963

964
965
canonic_text() and slurp() were added on Sympa 6.2.53b.

IKEDA Soji's avatar
IKEDA Soji committed
966
967
clip() was added on Sympa 6.2.61b.

968
=cut