Util.pm 33.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Dan Mosedale <dmose@mozilla.org>
22
#                 Jacob Steenhagen <jake@bugzilla.org>
23 24
#                 Bradley Baetz <bbaetz@student.usyd.edu.au>
#                 Christopher Aillon <christopher@aillon.com>
25
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
26
#                 Frédéric Buclin <LpSolit@gmail.com>
27
#                 Marc Schumann <wurblzap@gmail.com>
28 29 30

package Bugzilla::Util;

31
use strict;
32

33
use base qw(Exporter);
34
@Bugzilla::Util::EXPORT = qw(trick_taint detaint_natural
35
                             detaint_signed
36
                             html_quote url_quote xml_quote
37
                             css_class_quote html_light_quote url_decode
38
                             i_am_cgi correct_urlbase remote_ip
39
                             do_ssl_redirect_if_required use_attachbase
40
                             diff_arrays on_main_db
41
                             trim wrap_hard wrap_comment find_wrap_point
42
                             format_time validate_date validate_time datetime_from
43
                             file_mod_time is_7bit_clean
44
                             bz_crypt generate_random_password
45
                             validate_email_syntax clean_text
46 47
                             get_text template_var disable_utf8
                             detect_encoding);
48

49
use Bugzilla::Constants;
50

51 52
use Date::Parse;
use Date::Format;
53
use DateTime;
54
use DateTime::TimeZone;
55
use Digest;
56
use Email::Address;
57
use List::Util qw(first);
58
use Math::Random::Secure qw(irand);
59
use Scalar::Util qw(tainted blessed);
60
use Template::Filters;
61
use Text::Wrap;
62 63
use Encode qw(encode decode resolve_alias);
use Encode::Guess;
64 65

sub trick_taint {
66 67
    require Carp;
    Carp::confess("Undef to trick_taint") unless defined $_[0];
68 69
    my $match = $_[0] =~ /^(.*)$/s;
    $_[0] = $match ? $1 : undef;
70 71 72 73
    return (defined($_[0]));
}

sub detaint_natural {
74
    my $match = $_[0] =~ /^(\d+)$/;
75
    $_[0] = $match ? int($1) : undef;
76 77 78
    return (defined($_[0]));
}

79
sub detaint_signed {
80
    my $match = $_[0] =~ /^([-+]?\d+)$/;
81 82
    # The "int()" call removes any leading plus sign.
    $_[0] = $match ? int($1) : undef;
83 84 85
    return (defined($_[0]));
}

86 87 88
# Bug 120030: Override html filter to obscure the '@' in user
#             visible strings.
# Bug 319331: Handle BiDi disruptions.
89
sub html_quote {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    my ($var) = Template::Filters::html_filter(@_);
    # Obscure '@'.
    $var =~ s/\@/\&#64;/g;
    if (Bugzilla->params->{'utf8'}) {
        # Remove the following characters because they're
        # influencing BiDi:
        # --------------------------------------------------------
        # |Code  |Name                      |UTF-8 representation|
        # |------|--------------------------|--------------------|
        # |U+202a|Left-To-Right Embedding   |0xe2 0x80 0xaa      |
        # |U+202b|Right-To-Left Embedding   |0xe2 0x80 0xab      |
        # |U+202c|Pop Directional Formatting|0xe2 0x80 0xac      |
        # |U+202d|Left-To-Right Override    |0xe2 0x80 0xad      |
        # |U+202e|Right-To-Left Override    |0xe2 0x80 0xae      |
        # --------------------------------------------------------
        #
        # The following are characters influencing BiDi, too, but
        # they can be spared from filtering because they don't
        # influence more than one character right or left:
        # --------------------------------------------------------
        # |Code  |Name                      |UTF-8 representation|
        # |------|--------------------------|--------------------|
        # |U+200e|Left-To-Right Mark        |0xe2 0x80 0x8e      |
        # |U+200f|Right-To-Left Mark        |0xe2 0x80 0x8f      |
        # --------------------------------------------------------
        $var =~ s/[\x{202a}-\x{202e}]//g;
    }
117 118 119
    return $var;
}

120 121 122 123 124
sub html_light_quote {
    my ($text) = @_;

    # List of allowed HTML elements having no attributes.
    my @allow = qw(b strong em i u p br abbr acronym ins del cite code var
125 126
                   dfn samp kbd big small sub sup tt dd dt dl ul li ol
                   fieldset legend);
127

128
    if (!Bugzilla->feature('html_desc')) {
129 130 131 132 133 134 135 136 137 138 139 140 141 142
        my $safe = join('|', @allow);
        my $chr = chr(1);

        # First, escape safe elements.
        $text =~ s#<($safe)>#$chr$1$chr#go;
        $text =~ s#</($safe)>#$chr/$1$chr#go;
        # Now filter < and >.
        $text =~ s#<#&lt;#g;
        $text =~ s#>#&gt;#g;
        # Restore safe elements.
        $text =~ s#$chr/($safe)$chr#</$1>#go;
        $text =~ s#$chr($safe)$chr#<$1>#go;
        return $text;
    }
143
    else {
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        # We can be less restrictive. We can accept elements with attributes.
        push(@allow, qw(a blockquote q span));

        # Allowed protocols.
        my $safe_protocols = join('|', SAFE_PROTOCOLS);
        my $protocol_regexp = qr{(^(?:$safe_protocols):|^[^:]+$)}i;

        # Deny all elements and attributes unless explicitly authorized.
        my @default = (0 => {
                             id    => 1,
                             name  => 1,
                             class => 1,
                             '*'   => 0, # Reject all other attributes.
                            }
                       );

        # Specific rules for allowed elements. If no specific rule is set
        # for a given element, then the default is used.
        my @rules = (a => {
                           href  => $protocol_regexp,
                           title => 1,
                           id    => 1,
                           name  => 1,
                           class => 1,
                           '*'   => 0, # Reject all other attributes.
                          },
                     blockquote => {
                                    cite => $protocol_regexp,
                                    id    => 1,
                                    name  => 1,
                                    class => 1,
                                    '*'  => 0, # Reject all other attributes.
                                   },
                     'q' => {
                             cite => $protocol_regexp,
                             id    => 1,
                             name  => 1,
                             class => 1,
                             '*'  => 0, # Reject all other attributes.
                          },
                    );

        my $scrubber = HTML::Scrubber->new(default => \@default,
                                           allow   => \@allow,
                                           rules   => \@rules,
                                           comment => 0,
                                           process => 0);

        return $scrubber->scrub($text);
    }
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209
sub email_filter {
    my ($toencode) = @_;
    if (!Bugzilla->user->id) {
        my @emails = Email::Address->parse($toencode);
        if (scalar @emails) {
            my @hosts = map { quotemeta($_->host) } @emails;
            my $hosts_re = join('|', @hosts);
            $toencode =~ s/\@(?:$hosts_re)//g;
            return $toencode;
        }
    }
    return $toencode;
}

210
# This originally came from CGI.pm, by Lincoln D. Stein
211 212
sub url_quote {
    my ($toencode) = (@_);
213 214
    utf8::encode($toencode) # The below regex works only on bytes
        if Bugzilla->params->{'utf8'} && utf8::is_utf8($toencode);
215 216 217 218
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

219 220
sub css_class_quote {
    my ($toencode) = (@_);
221
    $toencode =~ s#[ /]#_#g;
222 223 224 225
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("&#x%x;",ord($1))/eg;
    return $toencode;
}

226 227 228 229 230 231 232
sub xml_quote {
    my ($var) = (@_);
    $var =~ s/\&/\&amp;/g;
    $var =~ s/</\&lt;/g;
    $var =~ s/>/\&gt;/g;
    $var =~ s/\"/\&quot;/g;
    $var =~ s/\'/\&apos;/g;
233 234 235 236 237 238 239
    
    # the following nukes characters disallowed by the XML 1.0
    # spec, Production 2.2. 1.0 declares that only the following 
    # are valid:
    # (#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF])
    $var =~ s/([\x{0001}-\x{0008}]|
               [\x{000B}-\x{000C}]|
240
               [\x{000E}-\x{001F}]|
241 242
               [\x{D800}-\x{DFFF}]|
               [\x{FFFE}-\x{FFFF}])//gx;
243 244 245
    return $var;
}

246 247 248 249
# This function must not be relied upon to return a valid string to pass to
# the DB or the user in UTF-8 situations. The only thing you  can rely upon
# it for is that if you url_decode a string, it will url_encode back to the 
# exact same thing.
250 251 252 253 254 255 256
sub url_decode {
    my ($todecode) = (@_);
    $todecode =~ tr/+/ /;       # pluses become spaces
    $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
    return $todecode;
}

257
sub i_am_cgi {
258 259 260 261 262
    # I use SERVER_SOFTWARE because it's required to be
    # defined for all requests in the CGI spec.
    return exists $ENV{'SERVER_SOFTWARE'} ? 1 : 0;
}

263 264 265 266 267 268
# This exists as a separate function from Bugzilla::CGI::redirect_to_https
# because we don't want to create a CGI object during XML-RPC calls
# (doing so can mess up XML-RPC).
sub do_ssl_redirect_if_required {
    return if !i_am_cgi();
    return if !Bugzilla->params->{'ssl_redirect'};
269

270 271 272 273 274 275 276
    my $sslbase = Bugzilla->params->{'sslbase'};
    
    # If we're already running under SSL, never redirect.
    return if uc($ENV{HTTPS} || '') eq 'ON';
    # Never redirect if there isn't an sslbase.
    return if !$sslbase;
    Bugzilla->cgi->redirect_to_https();
277 278
}

279
sub correct_urlbase {
280 281
    my $ssl = Bugzilla->params->{'ssl_redirect'};
    my $urlbase = Bugzilla->params->{'urlbase'};
282 283
    my $sslbase = Bugzilla->params->{'sslbase'};

284 285 286 287 288 289 290 291 292 293
    if (!$sslbase) {
        return $urlbase;
    }
    elsif ($ssl) {
        return $sslbase;
    }
    else {
        # Return what the user currently uses.
        return (uc($ENV{HTTPS} || '') eq 'ON') ? $sslbase : $urlbase;
    }
294 295
}

296 297 298 299 300 301 302 303 304
sub remote_ip {
    my $ip = $ENV{'REMOTE_ADDR'} || '127.0.0.1';
    my @proxies = split(/[\s,]+/, Bugzilla->params->{'inbound_proxies'});
    if (first { $_ eq $ip } @proxies) {
        $ip = $ENV{'HTTP_X_FORWARDED_FOR'} if $ENV{'HTTP_X_FORWARDED_FOR'};
    }
    return $ip;
}

305 306 307 308 309 310 311
sub use_attachbase {
    my $attachbase = Bugzilla->params->{'attachment_base'};
    return ($attachbase ne ''
            && $attachbase ne Bugzilla->params->{'urlbase'}
            && $attachbase ne Bugzilla->params->{'sslbase'}) ? 1 : 0;
}

312
sub diff_arrays {
313
    my ($old_ref, $new_ref, $attrib) = @_;
314 315 316

    my @old = @$old_ref;
    my @new = @$new_ref;
317
    $attrib ||= 'name';
318 319

    # For each pair of (old, new) entries:
320
    # If object arrays were passed then an attribute should be defined;
321 322 323 324
    # If they're equal, set them to empty. When done, @old contains entries
    # that were removed; @new contains ones that got added.
    foreach my $oldv (@old) {
        foreach my $newv (@new) {
325 326 327 328 329 330 331 332 333 334
            next if ($newv eq '' or $oldv eq '');
            if (blessed($oldv) and blessed($newv)) {
                if ($oldv->$attrib eq $newv->$attrib) {
                    $newv = $oldv = '';
                }
            }
            else {
                if ($oldv eq $newv) {
                    $newv = $oldv = ''
                }
335 336 337 338
            }
        }
    }

339 340 341 342 343
    my @removed;
    my @added;
    @removed = grep { $_ ne '' } @old;
    @added   = grep { $_ ne '' } @new;

344 345 346
    return (\@removed, \@added);
}

347 348
sub trim {
    my ($str) = @_;
349 350 351 352
    if ($str) {
      $str =~ s/^\s+//g;
      $str =~ s/\s+$//g;
    }
353 354 355
    return $str;
}

356
sub wrap_comment {
357
    my ($comment, $cols) = @_;
358 359 360
    my $wrappedcomment = "";

    # Use 'local', as recommended by Text::Wrap's perldoc.
361
    local $Text::Wrap::columns = $cols || COMMENT_COLS;
362 363 364 365 366 367 368 369 370 371 372
    # Make words that are longer than COMMENT_COLS not wrap.
    local $Text::Wrap::huge    = 'overflow';
    # Don't mess with tabs.
    local $Text::Wrap::unexpand = 0;

    # If the line starts with ">", don't wrap it. Otherwise, wrap.
    foreach my $line (split(/\r\n|\r|\n/, $comment)) {
      if ($line =~ qr/^>/) {
        $wrappedcomment .= ($line . "\n");
      }
      else {
373 374 375 376 377
        # Due to a segfault in Text::Tabs::expand() when processing tabs with
        # Unicode (see http://rt.perl.org/rt3/Public/Bug/Display.html?id=52104),
        # we have to remove tabs before processing the comment. This restriction
        # can go away when we require Perl 5.8.9 or newer.
        $line =~ s/\t/    /g;
378 379 380 381
        $wrappedcomment .= (wrap('', '', $line) . "\n");
      }
    }

382
    chomp($wrappedcomment); # Text::Wrap adds an extra newline at the end.
383
    return $wrappedcomment;
384 385
}

386
sub find_wrap_point {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    my ($string, $maxpos) = @_;
    if (!$string) { return 0 }
    if (length($string) < $maxpos) { return length($string) }
    my $wrappoint = rindex($string, ",", $maxpos); # look for comma
    if ($wrappoint < 0) {  # can't find comma
        $wrappoint = rindex($string, " ", $maxpos); # look for space
        if ($wrappoint < 0) {  # can't find space
            $wrappoint = rindex($string, "-", $maxpos); # look for hyphen
            if ($wrappoint < 0) {  # can't find hyphen
                $wrappoint = $maxpos;  # just truncate it
            } else {
                $wrappoint++; # leave hyphen on the left side
            }
        }
    }
    return $wrappoint;
}

405 406 407 408 409 410 411 412 413 414 415
sub wrap_hard {
    my ($string, $columns) = @_;
    local $Text::Wrap::columns = $columns;
    local $Text::Wrap::unexpand = 0;
    local $Text::Wrap::huge = 'wrap';
    
    my $wrapped = wrap('', '', $string);
    chomp($wrapped);
    return $wrapped;
}

416
sub format_time {
417
    my ($date, $format, $timezone) = @_;
418

419 420
    # If $format is not set, try to guess the correct date format.
    if (!$format) {
421 422 423
        if (!ref $date
            && $date =~ /^(\d{4})[-\.](\d{2})[-\.](\d{2}) (\d{2}):(\d{2})(:(\d{2}))?$/) 
        {
424 425
            my $sec = $7;
            if (defined $sec) {
426
                $format = "%Y-%m-%d %T %Z";
427
            } else {
428
                $format = "%Y-%m-%d %R %Z";
429 430
            }
        } else {
431 432
            # Default date format. See DateTime for other formats available.
            $format = "%Y-%m-%d %R %Z";
433
        }
434
    }
435

436 437 438 439 440 441 442 443
    my $dt = ref $date ? $date : datetime_from($date, $timezone);
    $date = defined $dt ? $dt->strftime($format) : '';
    return trim($date);
}

sub datetime_from {
    my ($date, $timezone) = @_;

444 445 446
    # In the database, this is the "0" date.
    return undef if $date =~ /^0000/;

447 448
    # strptime($date) returns an empty array if $date has an invalid
    # date format.
449 450
    my @time = strptime($date);

451
    unless (scalar @time) {
452 453 454
        # If an unknown timezone is passed (such as MSK, for Moskow),
        # strptime() is unable to parse the date. We try again, but we first
        # remove the timezone.
455 456 457 458
        $date =~ s/\s+\S+$//;
        @time = strptime($date);
    }

459 460 461 462
    return undef if !@time;

    # strptime() counts years from 1900, and months from 0 (January).
    # We have to fix both values.
463
    my %args = (
464 465 466 467 468 469 470
        year   => $time[5] + 1900,
        month  => $time[4] + 1,
        day    => $time[3],
        hour   => $time[2],
        minute => $time[1],
        # DateTime doesn't like fractional seconds.
        # Also, sometimes seconds are undef.
471
        second => defined($time[0]) ? int($time[0]) : undef,
472 473 474 475
        # If a timezone was specified, use it. Otherwise, use the
        # local timezone.
        time_zone => Bugzilla->local_timezone->offset_as_string($time[6]) 
                     || Bugzilla->local_timezone,
476 477 478 479 480 481 482 483 484 485
    );

    # If something wasn't specified in the date, it's best to just not
    # pass it to DateTime at all. (This is important for doing datetime_from
    # on the deadline field, which is usually just a date with no time.)
    foreach my $arg (keys %args) {
        delete $args{$arg} if !defined $args{$arg};
    }

    my $dt = new DateTime(\%args);
486 487 488 489 490

    # Now display the date using the given timezone,
    # or the user's timezone if none is given.
    $dt->set_time_zone($timezone || Bugzilla->user->timezone);
    return $dt;
491 492
}

493
sub file_mod_time {
494 495 496 497 498 499 500
    my ($filename) = (@_);
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
        $atime,$mtime,$ctime,$blksize,$blocks)
        = stat($filename);
    return $mtime;
}

501
sub bz_crypt {
502 503
    my ($password, $salt) = @_;

504
    my $algorithm;
505
    if (!defined $salt) {
506 507 508 509 510 511 512 513
        # If you don't use a salt, then people can create tables of
        # hashes that map to particular passwords, and then break your
        # hashing very easily if they have a large-enough table of common
        # (or even uncommon) passwords. So we generate a unique salt for
        # each password in the database, and then just prepend it to
        # the hash.
        $salt = generate_random_password(PASSWORD_SALT_LENGTH);
        $algorithm = PASSWORD_DIGEST_ALGORITHM;
514 515
    }

516 517 518 519 520 521 522
    # We append the algorithm used to the string. This is good because then
    # we can change the algorithm being used, in the future, without 
    # disrupting the validation of existing passwords. Also, this tells
    # us if a password is using the old "crypt" method of hashing passwords,
    # because the algorithm will be missing from the string.
    if ($salt =~ /{([^}]+)}$/) {
        $algorithm = $1;
523
    }
524

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    my $crypted_password;
    if (!$algorithm) {
        # Wide characters cause crypt to die
        if (Bugzilla->params->{'utf8'}) {
            utf8::encode($password) if utf8::is_utf8($password);
        }
    
        # Crypt the password.
        $crypted_password = crypt($password, $salt);

        # HACK: Perl has bug where returned crypted password is considered
        # tainted. See http://rt.perl.org/rt3/Public/Bug/Display.html?id=59998
        unless(tainted($password) || tainted($salt)) {
            trick_taint($crypted_password);
        } 
    }
    else {
        my $hasher = Digest->new($algorithm);
        # We only want to use the first characters of the salt, no
        # matter how long of a salt we may have been passed.
        $salt = substr($salt, 0, PASSWORD_SALT_LENGTH);
        $hasher->add($password, $salt);
        $crypted_password = $salt . $hasher->b64digest . "{$algorithm}";
    }
549

550
    # Return the crypted password.
551
    return $crypted_password;
552 553
}

554 555 556 557 558 559
# If you want to understand the security of strings generated by this
# function, here's a quick formula that will help you estimate:
# We pick from 62 characters, which is close to 64, which is 2^6.
# So 8 characters is (2^6)^8 == 2^48 combinations. Just multiply 6
# by the number of characters you generate, and that gets you the equivalent
# strength of the string in bits.
560 561
sub generate_random_password {
    my $size = shift || 10; # default to 10 chars if nothing specified
562
    return join("", map{ ('0'..'9','a'..'z','A'..'Z')[irand 62] } (1..$size));
563 564
}

565 566
sub validate_email_syntax {
    my ($addr) = @_;
567
    my $match = Bugzilla->params->{'emailregexp'};
568
    my $ret = ($addr =~ /$match/ && $addr !~ /[\\\(\)<>&,;:"\[\] \t\r\n]/);
569 570 571 572
    if ($ret) {
        # We assume these checks to suffice to consider the address untainted.
        trick_taint($_[0]);
    }
573
    return $ret ? 1 : 0;
574 575
}

576 577
sub validate_date {
    my ($date) = @_;
578
    my $date2;
579

580 581 582 583
    # $ts is undefined if the parser fails.
    my $ts = str2time($date);
    if ($ts) {
        $date2 = time2str("%Y-%m-%d", $ts);
584

585 586 587
        $date =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/; 
        $date2 =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/;
    }
588 589
    my $ret = ($ts && $date eq $date2);
    return $ret ? 1 : 0;
590 591
}

592 593 594 595 596 597 598 599
sub validate_time {
    my ($time) = @_;
    my $time2;

    # $ts is undefined if the parser fails.
    my $ts = str2time($time);
    if ($ts) {
        $time2 = time2str("%H:%M:%S", $ts);
600 601
        if ($time =~ /^(\d{1,2}):(\d\d)(?::(\d\d))?$/) {
            $time = sprintf("%02d:%02d:%02d", $1, $2, $3 || 0);
602
        }
603 604 605 606 607
    }
    my $ret = ($ts && $time eq $time2);
    return $ret ? 1 : 0;
}

608 609 610 611
sub is_7bit_clean {
    return $_[0] !~ /[^\x20-\x7E\x0A\x0D]/;
}

612
sub clean_text {
613 614 615 616 617
    my $dtext = shift;
    if ($dtext) {
        # change control characters into a space
        $dtext =~ s/[\x00-\x1F\x7F]+/ /g;
    }
618
    return trim($dtext);
619 620
}

621 622 623 624 625 626 627 628
sub on_main_db (&) {
    my $code = shift;
    my $original_dbh = Bugzilla->dbh;
    Bugzilla->request_cache->{dbh} = Bugzilla->dbh_main;
    $code->();
    Bugzilla->request_cache->{dbh} = $original_dbh;
}

629 630
sub get_text {
    my ($name, $vars) = @_;
631
    my $template = Bugzilla->template_inner;
632 633 634
    $vars ||= {};
    $vars->{'message'} = $name;
    my $message;
635 636 637 638
    if (!$template->process('global/message.txt.tmpl', $vars, \$message)) {
        require Bugzilla::Error;
        Bugzilla::Error::ThrowTemplateError($template->error());
    }
639 640 641 642 643
    # Remove the indenting that exists in messages.html.tmpl.
    $message =~ s/^    //gm;
    return $message;
}

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
sub template_var {
    my $name = shift;
    my $cache = Bugzilla->request_cache->{util_template_var} ||= {};
    my $template = Bugzilla->template_inner;
    my $lang = $template->context->{bz_language};
    return $cache->{$lang}->{$name} if defined $cache->{$lang};
    my %vars;
    # Note: If we suddenly start needing a lot of template_var variables,
    # they should move into their own template, not field-descs.
    my $result = $template->process('global/field-descs.none.tmpl', 
                                    { vars => \%vars, in_template_var => 1 });
    # Bugzilla::Error can't be "use"d in Bugzilla::Util.
    if (!$result) {
        require Bugzilla::Error;
        Bugzilla::Error::ThrowTemplateError($template->error);
    }
    $cache->{$lang} = \%vars;
    return $vars{$name};
}

664 665 666 667 668 669 670 671 672
sub display_value {
    my ($field, $value) = @_;
    my $value_descs = template_var('value_descs');
    if (defined $value_descs->{$field}->{$value}) {
        return $value_descs->{$field}->{$value};
    }
    return $value;
}

673 674
sub disable_utf8 {
    if (Bugzilla->params->{'utf8'}) {
675
        binmode STDOUT, ':bytes'; # Turn off UTF8 encoding.
676 677 678
    }
}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
use constant UTF8_ACCIDENTAL => qw(shiftjis big5-eten euc-kr euc-jp);

sub detect_encoding {
    my $data = shift;

    if (!Bugzilla->feature('detect_charset')) {
        require Bugzilla::Error;
        Bugzilla::Error::ThrowCodeError('feature_disabled',
            { feature => 'detect_charset' });
    }

    require Encode::Detect::Detector;
    import Encode::Detect::Detector 'detect';

    my $encoding = detect($data);
    $encoding = resolve_alias($encoding) if $encoding;

    # Encode::Detect is bad at detecting certain charsets, but Encode::Guess
    # is better at them. Here's the details:

    # shiftjis, big5-eten, euc-kr, and euc-jp: (Encode::Detect
    # tends to accidentally mis-detect UTF-8 strings as being
    # these encodings.)
    if ($encoding && grep($_ eq $encoding, UTF8_ACCIDENTAL)) {
        $encoding = undef;
        my $decoder = guess_encoding($data, UTF8_ACCIDENTAL);
        $encoding = $decoder->name if ref $decoder;
    }

    # Encode::Detect sometimes mis-detects various ISO encodings as iso-8859-8,
    # but Encode::Guess can usually tell which one it is.
    if ($encoding && $encoding eq 'iso-8859-8') {
        my $decoded_as = _guess_iso($data, 'iso-8859-8', 
            # These are ordered this way because it gives the most 
            # accurate results.
            qw(iso-8859-7 iso-8859-2));
        $encoding = $decoded_as if $decoded_as;
    }

    return $encoding;
}

# A helper for detect_encoding.
sub _guess_iso {
    my ($data, $versus, @isos) = (shift, shift, shift);

    my $encoding;
    foreach my $iso (@isos) {
        my $decoder = guess_encoding($data, ($iso, $versus));
        if (ref $decoder) {
            $encoding = $decoder->name if ref $decoder;
            last;
        }
    }
    return $encoding;
}

736 737 738 739
1;

__END__

740 741 742 743 744 745 746 747 748 749 750
=head1 NAME

Bugzilla::Util - Generic utility functions for bugzilla

=head1 SYNOPSIS

  use Bugzilla::Util;

  # Functions for dealing with variable tainting
  trick_taint($var);
  detaint_natural($var);
751
  detaint_signed($var);
752 753 754

  # Functions for quoting
  html_quote($var);
755
  url_quote($var);
756
  xml_quote($var);
757
  email_filter($var);
758

759 760
  # Functions for decoding
  $rv = url_decode($var);
761

762
  # Functions that tell you about your environment
763 764
  my $is_cgi   = i_am_cgi();
  my $urlbase  = correct_urlbase();
765

766 767 768
  # Data manipulation
  ($removed, $added) = diff_arrays(\@old, \@new);

769
  # Functions for manipulating strings
770
  $val = trim(" abc ");
771
  $wrapped = wrap_comment($comment);
772

773 774
  # Functions for formatting time
  format_time($time);
775
  datetime_from($time, $timezone);
776

777 778 779
  # Functions for dealing with files
  $time = file_mod_time($filename);

780 781
  # Cryptographic Functions
  $crypted_password = bz_crypt($password);
782
  $new_password = generate_random_password($password_length);
783

784
  # Validation Functions
785 786
  validate_email_syntax($email);
  validate_date($date);
787

788 789 790 791 792
  # DB-related functions
  on_main_db {
     ... code here ...
  };

793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
=head1 DESCRIPTION

This package contains various utility functions which do not belong anywhere
else.

B<It is not intended as a general dumping group for something which
people feel might be useful somewhere, someday>. Do not add methods to this
package unless it is intended to be used for a significant number of files,
and it does not belong anywhere else.

=head1 FUNCTIONS

This package provides several types of routines:

=head2 Tainting

Several functions are available to deal with tainted variables. B<Use these
with care> to avoid security holes.

=over 4

=item C<trick_taint($val)>

Tricks perl into untainting a particular variable.

Use trick_taint() when you know that there is no way that the data
in a scalar can be tainted, but taint mode still bails on it.

B<WARNING!! Using this routine on data that really could be tainted defeats
822 823
the purpose of taint mode.  It should only be used on variables that have been
sanity checked in some way and have been determined to be OK.>
824 825 826 827 828 829 830

=item C<detaint_natural($num)>

This routine detaints a natural number. It returns a true value if the
value passed in was a valid natural number, else it returns false. You
B<MUST> check the result of this routine to avoid security holes.

831 832 833 834 835 836
=item C<detaint_signed($num)>

This routine detaints a signed integer. It returns a true value if the
value passed in was a valid signed integer, else it returns false. You
B<MUST> check the result of this routine to avoid security holes.

837 838 839 840 841 842 843 844 845 846 847
=back

=head2 Quoting

Some values may need to be quoted from perl. However, this should in general
be done in the template where possible.

=over 4

=item C<html_quote($val)>

848 849 850
Returns a value quoted for use in HTML, with &, E<lt>, E<gt>, E<34> and @ being
replaced with their appropriate HTML entities.  Also, Unicode BiDi controls are
deleted.
851

852 853 854 855 856 857
=item C<html_light_quote($val)>

Returns a string where only explicitly allowed HTML elements and attributes
are kept. All HTML elements and attributes not being in the whitelist are either
escaped (if HTML::Scrubber is not installed) or removed.

858 859 860 861
=item C<url_quote($val)>

Quotes characters so that they may be included as part of a url.

862 863 864
=item C<css_class_quote($val)>

Quotes characters so that they may be used as CSS class names. Spaces
865
and forward slashes are replaced by underscores.
866

867 868 869 870 871 872
=item C<xml_quote($val)>

This is similar to C<html_quote>, except that ' is escaped to &apos;. This
is kept separate from html_quote partly for compatibility with previous code
(for &apos;) and partly for future handling of non-ASCII characters.

873 874 875 876
=item C<url_decode($val)>

Converts the %xx encoding from the given URL back to its original form.

877 878 879 880 881 882
=item C<email_filter>

Removes the hostname from email addresses in the string, if the user
currently viewing Bugzilla is logged out. If the user is logged-in,
this filter just returns the input string.

883 884 885 886 887 888 889 890
=back

=head2 Environment and Location

Functions returning information about your environment or location.

=over 4

891 892 893 894 895 896
=item C<i_am_cgi()>

Tells you whether or not you are being run as a CGI script in a web
server. For example, it would return false if the caller is running
in a command-line script.

897 898 899
=item C<correct_urlbase()>

Returns either the C<sslbase> or C<urlbase> parameter, depending on the
900
current setting for the C<ssl_redirect> parameter.
901

902 903 904 905 906
=item C<use_attachbase()>

Returns true if an alternate host is used to display attachments; false
otherwise.

907 908
=back

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
=head2 Data Manipulation

=over 4

=item C<diff_arrays(\@old, \@new)>

 Description: Takes two arrayrefs, and will tell you what it takes to 
              get from @old to @new.
 Params:      @old = array that you are changing from
              @new = array that you are changing to
 Returns:     A list of two arrayrefs. The first is a reference to an 
              array containing items that were removed from @old. The
              second is a reference to an array containing items
              that were added to @old. If both returned arrays are 
              empty, @old and @new contain the same values.

=back

927
=head2 String Manipulation
928 929 930 931 932 933 934 935

=over 4

=item C<trim($str)>

Removes any leading or trailing whitespace from a string. This routine does not
modify the existing string.

936 937 938 939 940
=item C<wrap_hard($string, $size)>

Wraps a string, so that a line is I<never> longer than C<$size>.
Returns the string, wrapped.

941 942 943 944 945 946 947 948 949 950
=item C<wrap_comment($comment)>

Takes a bug comment, and wraps it to the appropriate length. The length is
currently specified in C<Bugzilla::Constants::COMMENT_COLS>. Lines beginning
with ">" are assumed to be quotes, and they will not be wrapped.

The intended use of this function is to wrap comments that are about to be
displayed or emailed. Generally, wrapped text should not be stored in the
database.

951 952 953 954 955 956
=item C<find_wrap_point($string, $maxpos)>

Search for a comma, a whitespace or a hyphen to split $string, within the first
$maxpos characters. If none of them is found, just split $string at $maxpos.
The search starts at $maxpos and goes back to the beginning of the string.

957 958 959 960 961
=item C<is_7bit_clean($str)>

Returns true is the string contains only 7-bit characters (ASCII 32 through 126,
ASCII 10 (LineFeed) and ASCII 13 (Carrage Return).

962 963 964 965
=item C<disable_utf8()>

Disable utf8 on STDOUT (and display raw data instead).

966 967 968 969 970 971
=item C<detect_encoding($str)>

Guesses what encoding a given data is encoded in, returning the canonical name
of the detected encoding (which may be different from the MIME charset 
specification).

972 973 974 975
=item C<clean_text($str)>
Returns the parameter "cleaned" by exchanging non-printable characters with spaces.
Specifically characters (ASCII 0 through 31) and (ASCII 127) will become ASCII 32 (Space).

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
=item C<get_text>

=over

=item B<Description>

This is a method of getting localized strings within Bugzilla code.
Use this when you don't want to display a whole template, you just
want a particular string.

It uses the F<global/message.txt.tmpl> template to return a string.

=item B<Params>

=over

=item C<$message> - The identifier for the message.

=item C<$vars> - A hashref. Any variables you want to pass to the template.

=back

=item B<Returns>

A string.

=back

1004 1005 1006 1007 1008 1009 1010 1011

=item C<template_var>

This is a method of getting the value of a variable from a template in
Perl code. The available variables are in the C<global/field-descs.none.tmpl>
template. Just pass in the name of the variable that you want the value of.


1012 1013
=back

1014 1015 1016 1017 1018 1019
=head2 Formatting Time

=over 4

=item C<format_time($time)>

1020 1021 1022 1023
Takes a time and converts it to the desired format and timezone.
If no format is given, the routine guesses the correct one and returns
an empty array if it cannot. If no timezone is given, the user's timezone
is used, as defined in his preferences.
1024 1025

This routine is mainly called from templates to filter dates, see
1026
"FILTER time" in L<Bugzilla::Template>.
1027

1028 1029 1030 1031 1032 1033 1034 1035 1036
=item C<datetime_from($time, $timezone)>

Returns a DateTime object given a date string. If the string is not in some
valid date format that C<strptime> understands, we return C<undef>.

You can optionally specify a timezone for the returned date. If not
specified, defaults to the currently-logged-in user's timezone, or
the Bugzilla server's local timezone if there isn't a logged-in user.

1037 1038 1039
=back


1040 1041 1042 1043 1044 1045
=head2 Files

=over 4

=item C<file_mod_time($filename)>

1046 1047
Takes a filename and returns the modification time. It returns it in the format
of the "mtime" parameter of the perl "stat" function.
1048

1049 1050
=back

1051 1052 1053 1054
=head2 Cryptography

=over 4

1055
=item C<bz_crypt($password, $salt)>
1056

1057 1058
Takes a string and returns a hashed (encrypted) value for it, using a
random salt. An optional salt string may also be passed in.
1059

1060 1061 1062
Please always use this function instead of the built-in perl C<crypt>
function, when checking or setting a password. Bugzilla does not use
C<crypt>.
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

=begin undocumented

Random salts are generated because the alternative is usually
to use the first two characters of the password itself, and since
the salt appears in plaintext at the beginning of the encrypted
password string this has the effect of revealing the first two
characters of the password to anyone who views the encrypted version.

=end undocumented

1074 1075 1076 1077 1078 1079
=item C<generate_random_password($password_length)>

Returns an alphanumeric string with the specified length
(10 characters by default). Use this function to generate passwords
and tokens.

1080
=back
1081 1082 1083 1084 1085

=head2 Validation

=over 4

1086 1087 1088 1089
=item C<validate_email_syntax($email)>

Do a syntax checking for a legal email address and returns 1 if
the check is successful, else returns 0.
1090
Untaints C<$email> if successful.
1091 1092

=item C<validate_date($date)>
1093

1094 1095
Make sure the date has the correct format and returns 1 if
the check is successful, else returns 0.
1096 1097

=back
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

=head2 Database

=over

=item C<on_main_db>

Runs a block of code always on the main DB. Useful for when you're inside
a subroutine and need to do some writes to the database, but don't know
if Bugzilla is currently using the shadowdb or not. Used like:

 on_main_db {
     my $dbh = Bugzilla->dbh;
     $dbh->do("INSERT ...");
 }

1114
=back