Util.pm 25.8 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 34
use base qw(Exporter);
@Bugzilla::Util::EXPORT = qw(is_tainted 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 get_netaddr correct_urlbase
39
                             lsearch
40
                             diff_arrays diff_strings
41
                             trim wrap_hard wrap_comment find_wrap_point
42
                             format_time format_time_decimal validate_date
43
                             validate_time
44
                             file_mod_time is_7bit_clean
45
                             bz_crypt generate_random_password
46
                             validate_email_syntax clean_text
47
                             get_text disable_utf8);
48

49
use Bugzilla::Constants;
50

51 52
use Date::Parse;
use Date::Format;
53
use Text::Wrap;
54

55
# This is from the perlsec page, slightly modified to remove a warning
56 57 58 59 60 61 62 63 64 65
# From that page:
#      This function makes use of the fact that the presence of
#      tainted data anywhere within an expression renders the
#      entire expression tainted.
# Don't ask me how it works...
sub is_tainted {
    return not eval { my $foo = join('',@_), kill 0; 1; };
}

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 75
    my $match = $_[0] =~ /^(\d+)$/;
    $_[0] = $match ? $1 : undef;
76 77 78
    return (defined($_[0]));
}

79
sub detaint_signed {
80 81
    my $match = $_[0] =~ /^([-+]?\d+)$/;
    $_[0] = $match ? $1 : undef;
82 83 84 85 86 87 88
    # Remove any leading plus sign.
    if (defined($_[0]) && $_[0] =~ /^\+(\d+)$/) {
        $_[0] = $1;
    }
    return (defined($_[0]));
}

89 90 91 92 93 94 95 96 97
sub html_quote {
    my ($var) = (@_);
    $var =~ s/\&/\&amp;/g;
    $var =~ s/</\&lt;/g;
    $var =~ s/>/\&gt;/g;
    $var =~ s/\"/\&quot;/g;
    return $var;
}

98 99 100 101 102 103 104 105 106 107 108 109
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
                   dfn samp kbd big small sub sup tt dd dt dl ul li ol);

    # Are HTML::Scrubber and HTML::Parser installed?
    eval { require HTML::Scrubber;
           require HTML::Parser;
    };

110
    if ($@) { # Package(s) not installed.
111 112 113 114 115 116 117 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        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;
    }
    else { # Packages installed.
        # 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);
    }
}

178
# This originally came from CGI.pm, by Lincoln D. Stein
179 180
sub url_quote {
    my ($toencode) = (@_);
181 182
    utf8::encode($toencode) # The below regex works only on bytes
        if Bugzilla->params->{'utf8'} && utf8::is_utf8($toencode);
183 184 185 186
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

187 188 189 190 191 192 193
sub css_class_quote {
    my ($toencode) = (@_);
    $toencode =~ s/ /_/g;
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("&#x%x;",ord($1))/eg;
    return $toencode;
}

194 195 196 197 198 199 200 201 202 203
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;
    return $var;
}

204 205 206 207
# 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.
208 209 210 211 212 213 214
sub url_decode {
    my ($todecode) = (@_);
    $todecode =~ tr/+/ /;       # pluses become spaces
    $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
    return $todecode;
}

215
sub i_am_cgi {
216 217 218 219 220
    # 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;
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
sub correct_urlbase {
    my $ssl = Bugzilla->params->{'ssl'};
    return Bugzilla->params->{'urlbase'} if $ssl eq 'never';

    my $sslbase = Bugzilla->params->{'sslbase'};
    if ($sslbase) {
        return $sslbase if $ssl eq 'always';
        # Authenticated Sessions
        return $sslbase if Bugzilla->user->id;
    }

    # Set to "authenticated sessions" but nobody's logged in, or
    # sslbase isn't set.
    return Bugzilla->params->{'urlbase'};
}

237 238 239 240 241 242 243 244 245 246 247 248
sub lsearch {
    my ($list,$item) = (@_);
    my $count = 0;
    foreach my $i (@$list) {
        if ($i eq $item) {
            return $count;
        }
        $count++;
    }
    return -1;
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
sub diff_arrays {
    my ($old_ref, $new_ref) = @_;

    my @old = @$old_ref;
    my @new = @$new_ref;

    # For each pair of (old, new) entries:
    # 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) {
            next if ($newv eq '');
            if ($oldv eq $newv) {
                $newv = $oldv = '';
            }
        }
    }

    my @removed = grep { $_ ne '' } @old;
    my @added = grep { $_ ne '' } @new;
    return (\@removed, \@added);
}

272 273
sub trim {
    my ($str) = @_;
274 275 276 277
    if ($str) {
      $str =~ s/^\s+//g;
      $str =~ s/\s+$//g;
    }
278 279 280
    return $str;
}

281 282 283 284 285 286 287 288 289
sub diff_strings {
    my ($oldstr, $newstr) = @_;

    # Split the old and new strings into arrays containing their values.
    $oldstr =~ s/[\s,]+/ /g;
    $newstr =~ s/[\s,]+/ /g;
    my @old = split(" ", $oldstr);
    my @new = split(" ", $newstr);

290
    my ($rem, $add) = diff_arrays(\@old, \@new);
291

292 293
    my $removed = join (", ", @$rem);
    my $added = join (", ", @$add);
294 295 296 297

    return ($removed, $added);
}

298
sub wrap_comment {
299
    my ($comment, $cols) = @_;
300 301 302
    my $wrappedcomment = "";

    # Use 'local', as recommended by Text::Wrap's perldoc.
303
    local $Text::Wrap::columns = $cols || COMMENT_COLS;
304 305 306 307 308 309 310 311 312 313 314
    # 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 {
315 316 317 318 319
        # 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;
320 321 322 323
        $wrappedcomment .= (wrap('', '', $line) . "\n");
      }
    }

324
    chomp($wrappedcomment); # Text::Wrap adds an extra newline at the end.
325
    return $wrappedcomment;
326 327
}

328
sub find_wrap_point {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    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;
}

347 348 349 350 351 352 353 354 355 356 357
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;
}

358
sub format_time {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    my ($date, $format) = @_;

    # If $format is undefined, try to guess the correct date format.    
    my $show_timezone;
    if (!defined($format)) {
        if ($date =~ m/^(\d{4})[-\.](\d{2})[-\.](\d{2}) (\d{2}):(\d{2})(:(\d{2}))?$/) {
            my $sec = $7;
            if (defined $sec) {
                $format = "%Y-%m-%d %T";
            } else {
                $format = "%Y-%m-%d %R";
            }
        } else {
            # Default date format. See Date::Format for other formats available.
            $format = "%Y-%m-%d %R";
        }
        # By default, we want the timezone to be displayed.
        $show_timezone = 1;
377 378
    }
    else {
379
        # Search for %Z or %z, meaning we want the timezone to be displayed.
380 381
        # Till bug 182238 gets fixed, we assume Bugzilla->params->{'timezone'}
        # is used.
382
        $show_timezone = ($format =~ s/\s?%Z$//i);
383 384
    }

385 386 387 388 389
    # str2time($date) is undefined if $date has an invalid date format.
    my $time = str2time($date);

    if (defined $time) {
        $date = time2str($format, $time);
390
        $date .= " " . Bugzilla->params->{'timezone'} if $show_timezone;
391 392 393 394
    }
    else {
        # Don't let invalid (time) strings to be passed to templates!
        $date = '';
395
    }
396
    return trim($date);
397 398
}

399 400 401 402 403 404 405 406 407 408 409 410
sub format_time_decimal {
    my ($time) = (@_);

    my $newtime = sprintf("%.2f", $time);

    if ($newtime =~ /0\Z/) {
        $newtime = sprintf("%.1f", $time);
    }

    return $newtime;
}

411
sub file_mod_time {
412 413 414 415 416 417 418
    my ($filename) = (@_);
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
        $atime,$mtime,$ctime,$blksize,$blocks)
        = stat($filename);
    return $mtime;
}

419
sub bz_crypt {
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    my ($password) = @_;

    # The list of characters that can appear in a salt.  Salts and hashes
    # are both encoded as a sequence of characters from a set containing
    # 64 characters, each one of which represents 6 bits of the salt/hash.
    # The encoding is similar to BASE64, the difference being that the
    # BASE64 plus sign (+) is replaced with a forward slash (/).
    my @saltchars = (0..9, 'A'..'Z', 'a'..'z', '.', '/');

    # Generate the salt.  We use an 8 character (48 bit) salt for maximum
    # security on systems whose crypt uses MD5.  Systems with older
    # versions of crypt will just use the first two characters of the salt.
    my $salt = '';
    for ( my $i=0 ; $i < 8 ; ++$i ) {
        $salt .= $saltchars[rand(64)];
    }

    # Crypt the password.
    my $cryptedpassword = crypt($password, $salt);

    # Return the crypted password.
    return $cryptedpassword;
}

444 445 446 447 448
sub generate_random_password {
    my $size = shift || 10; # default to 10 chars if nothing specified
    return join("", map{ ('0'..'9','a'..'z','A'..'Z')[rand 62] } (1..$size));
}

449 450
sub validate_email_syntax {
    my ($addr) = @_;
451
    my $match = Bugzilla->params->{'emailregexp'};
452
    my $ret = ($addr =~ /$match/ && $addr !~ /[\\\(\)<>&,;:"\[\] \t\r\n]/);
453 454 455 456
    if ($ret) {
        # We assume these checks to suffice to consider the address untainted.
        trick_taint($_[0]);
    }
457
    return $ret ? 1 : 0;
458 459
}

460 461
sub validate_date {
    my ($date) = @_;
462
    my $date2;
463

464 465 466 467
    # $ts is undefined if the parser fails.
    my $ts = str2time($date);
    if ($ts) {
        $date2 = time2str("%Y-%m-%d", $ts);
468

469 470 471
        $date =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/; 
        $date2 =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/;
    }
472 473
    my $ret = ($ts && $date eq $date2);
    return $ret ? 1 : 0;
474 475
}

476 477 478 479 480 481 482 483
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);
484 485
        if ($time =~ /^(\d{1,2}):(\d\d)(?::(\d\d))?$/) {
            $time = sprintf("%02d:%02d:%02d", $1, $2, $3 || 0);
486
        }
487 488 489 490 491
    }
    my $ret = ($ts && $time eq $time2);
    return $ret ? 1 : 0;
}

492 493 494 495
sub is_7bit_clean {
    return $_[0] !~ /[^\x20-\x7E\x0A\x0D]/;
}

496 497
sub clean_text {
    my ($dtext) = shift;
498 499
    $dtext =~  s/[\x00-\x1F\x7F]+/ /g;   # change control characters into a space
    return trim($dtext);
500 501
}

502 503
sub get_text {
    my ($name, $vars) = @_;
504
    my $template = Bugzilla->template_inner;
505 506 507 508 509 510 511 512 513 514 515
    $vars ||= {};
    $vars->{'message'} = $name;
    my $message;
    $template->process('global/message.txt.tmpl', $vars, \$message)
        || ThrowTemplateError($template->error());
    # Remove the indenting that exists in messages.html.tmpl.
    $message =~ s/^    //gm;
    return $message;
}


516 517 518 519 520 521 522 523 524 525
sub get_netaddr {
    my $ipaddr = shift;

    # Check for a valid IPv4 addr which we know how to parse
    if (!$ipaddr || $ipaddr !~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
        return undef;
    }

    my $addr = unpack("N", pack("CCCC", split(/\./, $ipaddr)));

526
    my $maskbits = Bugzilla->params->{'loginnetmask'};
527 528 529 530 531 532 533 534 535 536

    # Make Bugzilla ignore the IP address if loginnetmask is set to 0
    return "0.0.0.0" if ($maskbits == 0);

    $addr >>= (32-$maskbits);

    $addr <<= (32-$maskbits);
    return join(".", unpack("CCCC", pack("N", $addr)));
}

537 538 539 540 541 542
sub disable_utf8 {
    if (Bugzilla->params->{'utf8'}) {
        binmode STDOUT, ':raw'; # Turn off UTF8 encoding.
    }
}

543 544 545 546
1;

__END__

547 548 549 550 551 552 553 554 555 556 557 558
=head1 NAME

Bugzilla::Util - Generic utility functions for bugzilla

=head1 SYNOPSIS

  use Bugzilla::Util;

  # Functions for dealing with variable tainting
  $rv = is_tainted($var);
  trick_taint($var);
  detaint_natural($var);
559
  detaint_signed($var);
560 561 562

  # Functions for quoting
  html_quote($var);
563
  url_quote($var);
564
  xml_quote($var);
565

566 567
  # Functions for decoding
  $rv = url_decode($var);
568

569
  # Functions that tell you about your environment
570 571 572
  my $is_cgi   = i_am_cgi();
  my $net_addr = get_netaddr($ip_addr);
  my $urlbase  = correct_urlbase();
573

574 575 576
  # Functions for searching
  $loc = lsearch(\@arr, $val);

577 578 579
  # Data manipulation
  ($removed, $added) = diff_arrays(\@old, \@new);

580
  # Functions for manipulating strings
581
  $val = trim(" abc ");
582
  ($removed, $added) = diff_strings($old, $new);
583
  $wrapped = wrap_comment($comment);
584

585 586 587
  # Functions for formatting time
  format_time($time);

588 589 590
  # Functions for dealing with files
  $time = file_mod_time($filename);

591 592
  # Cryptographic Functions
  $crypted_password = bz_crypt($password);
593
  $new_password = generate_random_password($password_length);
594

595
  # Validation Functions
596 597
  validate_email_syntax($email);
  validate_date($date);
598

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
=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<is_tainted>

Determines whether a particular variable is tainted

=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
632 633
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.>
634 635 636 637 638 639 640

=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.

641 642 643 644 645 646
=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.

647 648 649 650 651 652 653 654 655 656 657 658 659 660
=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)>

Returns a value quoted for use in HTML, with &, E<lt>, E<gt>, and E<34> being
replaced with their appropriate HTML entities.

661 662 663 664 665 666
=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.

667 668 669 670
=item C<url_quote($val)>

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

671 672 673 674 675
=item C<css_class_quote($val)>

Quotes characters so that they may be used as CSS class names. Spaces
are replaced by underscores.

676 677 678 679 680 681
=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.

682 683 684 685
=item C<url_decode($val)>

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

686 687 688 689 690 691 692 693
=back

=head2 Environment and Location

Functions returning information about your environment or location.

=over 4

694 695 696 697 698 699
=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.

700 701 702
=item C<get_netaddr($ipaddr)>

Given an IP address, this returns the associated network address, using
703 704 705
C<Bugzilla->params->{'loginnetmask'}> as the netmask. This can be used
to obtain data in order to restrict weak authentication methods (such as
cookies) to only some addresses.
706

707 708 709 710 711
=item C<correct_urlbase()>

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

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
=back

=head2 Searching

Functions for searching within a set of values.

=over 4

=item C<lsearch($list, $item)>

Returns the position of C<$item> in C<$list>. C<$list> must be a list
reference.

If the item is not in the list, returns -1.

=back

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
=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

747
=head2 String Manipulation
748 749 750 751 752 753 754 755

=over 4

=item C<trim($str)>

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

756 757 758 759 760 761 762 763
=item C<diff_strings($oldstr, $newstr)>

Takes two strings containing a list of comma- or space-separated items
and returns what items were removed from or added to the new one, 
compared to the old one. Returns a list, where the first entry is a scalar
containing removed items, and the second entry is a scalar containing added
items.

764 765 766 767 768
=item C<wrap_hard($string, $size)>

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

769 770 771 772 773 774 775 776 777 778
=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.

779 780 781 782 783 784
=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.

785 786 787 788 789
=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).

790 791 792 793
=item C<disable_utf8()>

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

794 795 796 797
=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).

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
=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

826 827
=back

828 829 830 831 832 833
=head2 Formatting Time

=over 4

=item C<format_time($time)>

834 835 836 837 838 839 840 841 842
Takes a time, converts it to the desired format and appends the timezone
as defined in editparams.cgi, if desired. This routine will be expanded
in the future to adjust for user preferences regarding what timezone to
display times in.

This routine is mainly called from templates to filter dates, see
"FILTER time" in Templates.pm. In this case, $format is undefined and
the routine has to "guess" the date format that was passed to $dbh->sql_date_format().

843

844 845 846 847 848
=item C<format_time_decimal($time)>

Returns a number with 2 digit precision, unless the last digit is a 0. Then it 
returns only 1 digit precision.

849 850 851
=back


852 853 854 855 856 857
=head2 Files

=over 4

=item C<file_mod_time($filename)>

858 859
Takes a filename and returns the modification time. It returns it in the format
of the "mtime" parameter of the perl "stat" function.
860

861 862
=back

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
=head2 Cryptography

=over 4

=item C<bz_crypt($password)>

Takes a string and returns a C<crypt>ed value for it, using a random salt.

Please always use this function instead of the built-in perl "crypt"
when initially encrypting a password.

=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

884 885 886 887 888 889
=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.

890
=back
891 892 893 894 895

=head2 Validation

=over 4

896 897 898 899
=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.
900
Untaints C<$email> if successful.
901 902

=item C<validate_date($date)>
903

904 905
Make sure the date has the correct format and returns 1 if
the check is successful, else returns 0.
906 907

=back