Template.pm 39.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 22 23 24
# -*- 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>
#                 Jacob Steenhagen <jake@bugzilla.org>
#                 Bradley Baetz <bbaetz@student.usyd.edu.au>
#                 Christopher Aillon <christopher@aillon.com>
25
#                 Tobias Burnus <burnus@net-b.de>
26
#                 Myk Melez <myk@mozilla.org>
27
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
28
#                 Frédéric Buclin <LpSolit@gmail.com>
29
#                 Greg Hendricks <ghendricks@novell.com>
30
#                 David D. Kilzer <ddkilzer@kilzer.net>
31

32 33 34 35 36

package Bugzilla::Template;

use strict;

37
use Bugzilla::Bug;
38
use Bugzilla::Constants;
39
use Bugzilla::Hook;
40
use Bugzilla::Install::Requirements;
41 42 43
use Bugzilla::Install::Util qw(install_string template_include_path 
                               include_languages);
use Bugzilla::Keyword;
44
use Bugzilla::Util;
45
use Bugzilla::User;
46
use Bugzilla::Error;
47
use Bugzilla::Search;
48
use Bugzilla::Status;
49
use Bugzilla::Token;
50

51
use Cwd qw(abs_path);
52
use MIME::Base64;
53
use Date::Format ();
54
use File::Basename qw(basename dirname);
55
use File::Find;
56
use File::Path qw(rmtree mkpath);
57 58
use File::Spec;
use IO::Dir;
59
use List::MoreUtils qw(firstidx);
60
use Scalar::Util qw(blessed);
61 62 63

use base qw(Template);

64 65 66 67 68
use constant FORMAT_TRIPLE => '%19s|%-28s|%-28s';
use constant FORMAT_3_SIZE => [19,28,28];
use constant FORMAT_DOUBLE => '%19s %-55s';
use constant FORMAT_2_SIZE => [19,55];

69
# Convert the constants in the Bugzilla::Constants module into a hash we can
70 71
# pass to the template object for reflection into its "constants" namespace
# (which is like its "variables" namespace, but for constants).  To do so, we
72 73
# traverse the arrays of exported and exportable symbols and ignoring the rest
# (which, if Constants.pm exports only constants, as it should, will be nothing else).
74 75 76 77 78
sub _load_constants {
    my %constants;
    foreach my $constant (@Bugzilla::Constants::EXPORT,
                          @Bugzilla::Constants::EXPORT_OK)
    {
79 80 81 82 83 84
        if (ref Bugzilla::Constants->$constant) {
            $constants{$constant} = Bugzilla::Constants->$constant;
        }
        else {
            my @list = (Bugzilla::Constants->$constant);
            $constants{$constant} = (scalar(@list) == 1) ? $list[0] : \@list;
85 86
        }
    }
87
    return \%constants;
88 89
}

90 91 92
# Returns the path to the templates based on the Accept-Language
# settings of the user and of the available languages
# If no Accept-Language is present it uses the defined default
93
# Templates may also be found in the extensions/ tree
94 95
sub _include_path {
    my $lang = shift || '';
96
    my $cache = Bugzilla->request_cache;
97 98
    $cache->{"template_include_path_$lang"} ||= 
        template_include_path({ language => $lang });
99
    return $cache->{"template_include_path_$lang"};
100 101
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
sub get_format {
    my $self = shift;
    my ($template, $format, $ctype) = @_;

    $ctype ||= 'html';
    $format ||= '';

    # Security - allow letters and a hyphen only
    $ctype =~ s/[^a-zA-Z\-]//g;
    $format =~ s/[^a-zA-Z\-]//g;
    trick_taint($ctype);
    trick_taint($format);

    $template .= ($format ? "-$format" : "");
    $template .= ".$ctype.tmpl";

    # Now check that the template actually exists. We only want to check
    # if the template exists; any other errors (eg parse errors) will
    # end up being detected later.
    eval {
        $self->context->template($template);
    };
124
    # This parsing may seem fragile, but it's OK:
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    # http://lists.template-toolkit.org/pipermail/templates/2003-March/004370.html
    # Even if it is wrong, any sort of error is going to cause a failure
    # eventually, so the only issue would be an incorrect error message
    if ($@ && $@->info =~ /: not found$/) {
        ThrowUserError('format_not_found', {'format' => $format,
                                            'ctype'  => $ctype});
    }

    # Else, just return the info
    return
    {
        'template'    => $template,
        'extension'   => $ctype,
        'ctype'       => Bugzilla::Constants::contenttypes->{$ctype}
    };
}
141

142 143 144 145 146 147 148 149
# This routine quoteUrls contains inspirations from the HTML::FromText CPAN
# module by Gareth Rees <garethr@cre.canon.co.uk>.  It has been heavily hacked,
# all that is really recognizable from the original is bits of the regular
# expressions.
# This has been rewritten to be faster, mainly by substituting 'as we go'.
# If you want to modify this routine, read the comments carefully

sub quoteUrls {
150
    my ($text, $bug, $comment) = (@_);
151 152 153 154 155 156 157
    return $text unless $text;

    # We use /g for speed, but uris can have other things inside them
    # (http://foo/bug#3 for example). Filtering that out filters valid
    # bug refs out, so we have to do replacements.
    # mailto can't contain space or #, so we don't have to bother for that
    # Do this by escaping \0 to \1\0, and replacing matches with \0\0$count\0\0
158
    # \0 is used because it's unlikely to occur in the text, so the cost of
159 160 161 162 163 164 165 166 167 168
    # doing this should be very small

    # escape the 2nd escape char we're using
    my $chr1 = chr(1);
    $text =~ s/\0/$chr1\0/g;

    # However, note that adding the title (for buglinks) can affect things
    # In particular, attachment matches go before bug titles, so that titles
    # with 'attachment 1' don't double match.
    # Dupe checks go afterwards, because that uses ^ and \Z, which won't occur
169
    # if it was substituted as a bug title (since that always involve leading
170 171
    # and trailing text)

172
    # Because of entities, it's easier (and quicker) to do this before escaping
173 174 175 176 177

    my @things;
    my $count = 0;
    my $tmp;

178
    my @hook_regexes;
179
    Bugzilla::Hook::process('bug_format_comment',
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        { text => \$text, bug => $bug, regexes => \@hook_regexes,
          comment => $comment });

    foreach my $re (@hook_regexes) {
        my ($match, $replace) = @$re{qw(match replace)};
        if (ref($replace) eq 'CODE') {
            $text =~ s/$match/($things[$count++] = $replace->({matches => [
                                                               $1, $2, $3, $4,
                                                               $5, $6, $7, $8, 
                                                               $9, $10]}))
                               && ("\0\0" . ($count-1) . "\0\0")/egx;
        }
        else {
            $text =~ s/$match/($things[$count++] = $replace) 
                              && ("\0\0" . ($count-1) . "\0\0")/egx;
        }
    }

198
    # Provide tooltips for full bug links (Bug 74355)
199 200 201
    my $urlbase_re = '(' . join('|',
        map { qr/$_/ } grep($_, Bugzilla->params->{'urlbase'}, 
                            Bugzilla->params->{'sslbase'})) . ')';
202
    $text =~ s~\b(${urlbase_re}\Qshow_bug.cgi?id=\E([0-9]+)(\#c([0-9]+))?)\b
203
              ~($things[$count++] = get_bug_link($3, $1, { comment_num => $5 })) &&
204 205 206
               ("\0\0" . ($count-1) . "\0\0")
              ~egox;

207
    # non-mailto protocols
208 209
    my $safe_protocols = join('|', SAFE_PROTOCOLS);
    my $protocol_re = qr/($safe_protocols)/i;
210 211 212 213 214 215 216 217 218

    $text =~ s~\b(${protocol_re}:  # The protocol:
                  [^\s<>\"]+       # Any non-whitespace
                  [\w\/])          # so that we end in \w or /
              ~($tmp = html_quote($1)) &&
               ($things[$count++] = "<a href=\"$tmp\">$tmp</a>") &&
               ("\0\0" . ($count-1) . "\0\0")
              ~egox;

219
    # We have to quote now, otherwise the html itself is escaped
220 221 222 223 224 225 226 227 228 229 230 231 232
    # THIS MEANS THAT A LITERAL ", <, >, ' MUST BE ESCAPED FOR A MATCH

    $text = html_quote($text);

    # Color quoted text
    $text =~ s~^(&gt;.+)$~<span class="quote">$1</span >~mg;
    $text =~ s~</span >\n<span class="quote">~\n~g;

    # mailto:
    # Use |<nothing> so that $1 is defined regardless
    $text =~ s~\b(mailto:|)?([\w\.\-\+\=]+\@[\w\-]+(?:\.[\w\-]+)+)\b
              ~<a href=\"mailto:$2\">$1$2</a>~igx;

233
    # attachment links
234
    $text =~ s~\b(attachment\s*\#?\s*(\d+))
235 236 237 238 239
              ~($things[$count++] = get_attachment_link($2, $1)) &&
               ("\0\0" . ($count-1) . "\0\0")
              ~egmxi;

    # Current bug ID this comment belongs to
240
    my $current_bugurl = $bug ? ("show_bug.cgi?id=" . $bug->id) : "";
241 242 243 244 245

    # This handles bug a, comment b type stuff. Because we're using /g
    # we have to do this in one pattern, and so this is semi-messy.
    # Also, we can't use $bug_re?$comment_re? because that will match the
    # empty string
246
    my $bug_word = template_var('terms')->{bug};
247 248 249
    my $bug_re = qr/\Q$bug_word\E\s*\#?\s*(\d+)/i;
    my $comment_re = qr/comment\s*\#?\s*(\d+)/i;
    $text =~ s~\b($bug_re(?:\s*,?\s*$comment_re)?|$comment_re)
250 251
              ~ # We have several choices. $1 here is the link, and $2-4 are set
                # depending on which part matched
252
               (defined($2) ? get_bug_link($2, $1, { comment_num => $3 }) :
253 254 255
                              "<a href=\"$current_bugurl#c$4\">$1</a>")
              ~egox;

256 257
    # Old duplicate markers. These don't use $bug_word because they are old
    # and were never customizable.
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    $text =~ s~(?<=^\*\*\*\ This\ bug\ has\ been\ marked\ as\ a\ duplicate\ of\ )
               (\d+)
               (?=\ \*\*\*\Z)
              ~get_bug_link($1, $1)
              ~egmx;

    # Now remove the encoding hacks
    $text =~ s/\0\0(\d+)\0\0/$things[$1]/eg;
    $text =~ s/$chr1\0/\0/g;

    return $text;
}

# Creates a link to an attachment, including its title.
sub get_attachment_link {
    my ($attachid, $link_text) = @_;
    my $dbh = Bugzilla->dbh;

276
    my $attachment = new Bugzilla::Attachment($attachid);
277

278
    if ($attachment) {
279 280
        my $title = "";
        my $className = "";
281 282
        if (Bugzilla->user->can_see_bug($attachment->bug_id)) {
            $title = $attachment->description;
283
        }
284
        if ($attachment->isobsolete) {
285 286 287
            $className = "bz_obsolete";
        }
        # Prevent code injection in the title.
288
        $title = html_quote(clean_text($title));
289

290
        $link_text =~ s/ \[details\]$//;
291
        my $linkval = "attachment.cgi?id=$attachid";
292 293 294 295

        # If the attachment is a patch, try to link to the diff rather
        # than the text, by default.
        my $patchlink = "";
296
        if ($attachment->ispatch and Bugzilla->feature('patch_viewer')) {
297
            $patchlink = '&amp;action=diff';
298 299
        }

300 301
        # Whitespace matters here because these links are in <pre> tags.
        return qq|<span class="$className">|
302
               . qq|<a href="${linkval}${patchlink}" name="attach_${attachid}" title="$title">$link_text</a>|
303
               . qq| <a href="${linkval}&amp;action=edit" title="$title">[details]</a>|
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
               . qq|</span>|;
    }
    else {
        return qq{$link_text};
    }
}

# Creates a link to a bug, including its title.
# It takes either two or three parameters:
#  - The bug number
#  - The link text, to place between the <a>..</a>
#  - An optional comment number, for linking to a particular
#    comment in the bug

sub get_bug_link {
319
    my ($bug, $link_text, $options) = @_;
320 321
    my $dbh = Bugzilla->dbh;

322 323
    if (!$bug) {
        return html_quote('<missing bug number>');
324 325
    }

326 327 328 329 330 331
    $bug = blessed($bug) ? $bug : new Bugzilla::Bug($bug);
    return $link_text if $bug->{error};
    
    # Initialize these variables to be "" so that we don't get warnings
    # if we don't change them below (which is highly likely).
    my ($pre, $title, $post) = ("", "", "");
332
    my @css_classes = ("bz_bug_link");
333

334
    $title = get_text('get_status', { status => $bug->bug_status });
335 336 337

    push @css_classes, "bz_status_" . css_class_quote($bug->bug_status);

338
    if ($bug->resolution) {
339
        push @css_classes, "bz_closed";
340 341 342 343 344
        $title .= ' ' . get_text('get_resolution',
                                 { resolution => $bug->resolution });
    }
    if (Bugzilla->user->can_see_bug($bug)) {
        $title .= " - " . $bug->short_desc;
345 346 347
        if ($options->{use_alias} && $link_text =~ /^\d+$/ && $bug->alias) {
            $link_text = $bug->alias;
        }
348 349 350 351 352
    }
    # Prevent code injection in the title.
    $title = html_quote(clean_text($title));

    my $linkval = "show_bug.cgi?id=" . $bug->id;
353
    if (defined $options->{comment_num}) {
354
        $linkval .= "#c" . $options->{comment_num};
355
    }
356 357 358 359

    $pre  = '<span class="' . join(" ", @css_classes) . '">';
    $post = '</span>';

360
    return qq{$pre<a href="$linkval" title="$title">$link_text</a>$post};
361 362
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
# We use this instead of format because format doesn't deal well with
# multi-byte languages.
sub multiline_sprintf {
    my ($format, $args, $sizes) = @_;
    my @parts;
    my @my_sizes = @$sizes; # Copy this so we don't modify the input array.
    foreach my $string (@$args) {
        my $size = shift @my_sizes;
        my @pieces = split("\n", wrap_hard($string, $size));
        push(@parts, \@pieces);
    }

    my $formatted;
    while (1) {
        # Get the first item of each part.
        my @line = map { shift @$_ } @parts;
        # If they're all undef, we're done.
        last if !grep { defined $_ } @line;
        # Make any single undef item into ''
        @line = map { defined $_ ? $_ : '' } @line;
        # And append a formatted line
        $formatted .= sprintf($format, @line);
        # Remove trailing spaces, or they become lots of =20's in
        # quoted-printable emails.
        $formatted =~ s/\s+$//;
        $formatted .= "\n";
    }
    return $formatted;
}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 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 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
#####################
# Header Generation #
#####################

# Returns the last modification time of a file, as an integer number of
# seconds since the epoch.
sub _mtime { return (stat($_[0]))[9] }

sub mtime_filter {
    my ($file_url) = @_;
    my $cgi_path = bz_locations()->{'cgi_path'};
    my $file_path = "$cgi_path/$file_url";
    return "$file_url?" . _mtime($file_path);
}

# Set up the skin CSS cascade:
#
#  1. YUI CSS
#  2. Standard Bugzilla stylesheet set (persistent)
#  3. Standard Bugzilla stylesheet set (selectable)
#  4. All third-party "skin" stylesheet sets (selectable)
#  5. Page-specific styles
#  6. Custom Bugzilla stylesheet set (persistent)
#
# "Selectable" skin file sets may be either preferred or alternate.
# Exactly one is preferred, determined by the "skin" user preference.
sub css_files {
    my ($style_urls, $yui, $yui_css) = @_;
    
    # global.css goes on every page, and so does IE-fixes.css.
    my @requested_css = ('skins/standard/global.css', @$style_urls,
                         'skins/standard/IE-fixes.css');

    my @yui_required_css;
    foreach my $yui_name (@$yui) {
        next if !$yui_css->{$yui_name};
        push(@yui_required_css, "js/yui/assets/skins/sam/$yui_name.css");
    }
    unshift(@requested_css, @yui_required_css);
    
    my @css_sets = map { _css_link_set($_) } @requested_css;
    
    my %by_type = (standard => [], alternate => {}, skin => [], custom => []);
    foreach my $set (@css_sets) {
        foreach my $key (keys %$set) {
            if ($key eq 'alternate') {
                foreach my $alternate_skin (keys %{ $set->{alternate} }) {
                    my $files = $by_type{alternate}->{$alternate_skin} ||= [];
                    push(@$files, $set->{alternate}->{$alternate_skin});
                }
            }
            else {
                push(@{ $by_type{$key} }, $set->{$key});
            }
        }
    }
    
    return \%by_type;
}

sub _css_link_set {
    my ($file_name) = @_;

    my $standard_mtime = _mtime($file_name);
    my %set = (standard => $file_name . "?$standard_mtime");
    
    # We use (^|/) to allow Extensions to use the skins system if they
    # want.
    if ($file_name !~ m{(^|/)skins/standard/}) {
        return \%set;
    }
    
    my $user = Bugzilla->user;
    my $cgi_path = bz_locations()->{'cgi_path'};
    my $all_skins = $user->settings->{'skin'}->legal_values;    
    my %skin_urls;
    foreach my $option (@$all_skins) {
        next if $option eq 'standard';
        my $skin_file_name = $file_name;
        $skin_file_name =~ s{(^|/)skins/standard/}{skins/contrib/$option/};
        if (my $mtime = _mtime("$cgi_path/$skin_file_name")) {
            $skin_urls{$option} = $skin_file_name . "?$mtime";
        }
    }
    $set{alternate} = \%skin_urls;
    
    my $skin = $user->settings->{'skin'}->{'value'};
    if ($skin ne 'standard' and defined $set{alternate}->{$skin}) {
        $set{skin} = delete $set{alternate}->{$skin};
    }
    
    my $custom_file_name = $file_name;
    $custom_file_name =~ s{(^|/)skins/standard/}{skins/custom/};
    if (my $custom_mtime = _mtime("$cgi_path/$custom_file_name")) {
        $set{custom} = $custom_file_name . "?$custom_mtime";
    }
    
    return \%set;
}

# YUI dependency resolution
sub yui_resolve_deps {
    my ($yui, $yui_deps) = @_;
    
    my @yui_resolved;
    foreach my $yui_name (@$yui) {
        my $deps = $yui_deps->{$yui_name} || [];
        foreach my $dep (reverse @$deps) {
            push(@yui_resolved, $dep) if !grep { $_ eq $dep } @yui_resolved;
        }
        push(@yui_resolved, $yui_name) if !grep { $_ eq $yui_name } @yui_resolved;
    }
    return \@yui_resolved;
}

508 509 510
###############################################################################
# Templatization Code

511 512 513 514 515 516
# The Template Toolkit throws an error if a loop iterates >1000 times.
# We want to raise that limit.
# NOTE: If you change this number, you MUST RE-RUN checksetup.pl!!!
# If you do not re-run checksetup.pl, the change you make will not apply
$Template::Directive::WHILE_MAX = 1000000;

517 518 519 520
# Use the Toolkit Template's Stash module to add utility pseudo-methods
# to template variables.
use Template::Stash;

521 522 523
# Allow keys to start with an underscore or a dot.
$Template::Stash::PRIVATE = undef;

524 525 526 527 528 529
# Add "contains***" methods to list variables that search for one or more 
# items in a list and return boolean values representing whether or not 
# one/all/any item(s) were found.
$Template::Stash::LIST_OPS->{ contains } =
  sub {
      my ($list, $item) = @_;
530 531 532 533 534
      if (ref $item && $item->isa('Bugzilla::Object')) {
          return grep($_->id == $item->id, @$list);
      } else {
          return grep($_ eq $item, @$list);
      }
535 536 537 538 539 540
  };

$Template::Stash::LIST_OPS->{ containsany } =
  sub {
      my ($list, $items) = @_;
      foreach my $item (@$items) { 
541 542 543 544 545
          if (ref $item && $item->isa('Bugzilla::Object')) {
              return 1 if grep($_->id == $item->id, @$list);
          } else {
              return 1 if grep($_ eq $item, @$list);
          }
546 547 548 549
      }
      return 0;
  };

550 551 552 553 554 555 556
# Clone the array reference to leave the original one unaltered.
$Template::Stash::LIST_OPS->{ clone } =
  sub {
      my $list = shift;
      return [@$list];
  };

557 558 559 560 561 562 563
# Allow us to still get the scalar if we use the list operation ".0" on it,
# as we often do for defaults in query.cgi and other places.
$Template::Stash::SCALAR_OPS->{ 0 } = 
  sub {
      return $_[0];
  };

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
# Add a "truncate" method to the Template Toolkit's "scalar" object
# that truncates a string to a certain length.
$Template::Stash::SCALAR_OPS->{ truncate } = 
  sub {
      my ($string, $length, $ellipsis) = @_;
      $ellipsis ||= "";
      
      return $string if !$length || length($string) <= $length;
      
      my $strlen = $length - length($ellipsis);
      my $newstr = substr($string, 0, $strlen) . $ellipsis;
      return $newstr;
  };

# Create the template object that processes templates and specify
# configuration parameters that apply to all templates.

###############################################################################

583 584 585 586 587 588 589 590 591 592 593
sub process {
    my $self = shift;
    # All of this current_langs stuff allows template_inner to correctly
    # determine what-language Template object it should instantiate.
    my $current_langs = Bugzilla->request_cache->{template_current_lang} ||= [];
    unshift(@$current_langs, $self->context->{bz_language});
    my $retval = $self->SUPER::process(@_);
    shift @$current_langs;
    return $retval;
}

594 595 596 597 598 599 600
# Construct the Template object

# Note that all of the failure cases here can't use templateable errors,
# since we won't have a template to use...

sub create {
    my $class = shift;
601 602
    my %opts = @_;

603 604
    # IMPORTANT - If you make any FILTER changes here, make sure to
    # make them in t/004.template.t also, if required.
605

606
    my $config = {
607
        # Colon-separated list of directories containing templates.
608 609
        INCLUDE_PATH => $opts{'include_path'} 
                        || _include_path($opts{'language'}),
610 611 612 613 614 615 616 617

        # Remove white-space before template directives (PRE_CHOMP) and at the
        # beginning and end of templates and template blocks (TRIM) for better
        # looking, more compact content.  Use the plus sign at the beginning
        # of directives to maintain white space (i.e. [%+ DIRECTIVE %]).
        PRE_CHOMP => 1,
        TRIM => 1,

618 619 620 621 622 623 624 625
        # Bugzilla::Template::Plugin::Hook uses the absolute (in mod_perl)
        # or relative (in mod_cgi) paths of hook files to explicitly compile
        # a specific file. Also, these paths may be absolute at any time
        # if a packager has modified bz_locations() to contain absolute
        # paths.
        ABSOLUTE => 1,
        RELATIVE => $ENV{MOD_PERL} ? 0 : 1,

626
        COMPILE_DIR => bz_locations()->{'datadir'} . "/template",
627

628
        # Initialize templates (f.e. by loading plugins like Hook).
629
        PRE_PROCESS => ["global/initialize.none.tmpl"],
630

631 632
        ENCODING => Bugzilla->params->{'utf8'} ? 'UTF-8' : undef,

633 634
        # Functions for processing text within templates in various ways.
        # IMPORTANT!  When adding a filter here that does not override a
635
        # built-in filter, please also add a stub filter to t/004template.t.
636
        FILTERS => {
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

            # Render text in required style.

            inactive => [
                sub {
                    my($context, $isinactive) = @_;
                    return sub {
                        return $isinactive ? '<span class="bz_inactive">'.$_[0].'</span>' : $_[0];
                    }
                }, 1
            ],

            closed => [
                sub {
                    my($context, $isclosed) = @_;
                    return sub {
                        return $isclosed ? '<span class="bz_closed">'.$_[0].'</span>' : $_[0];
                    }
                }, 1
            ],

            obsolete => [
                sub {
                    my($context, $isobsolete) = @_;
                    return sub {
                        return $isobsolete ? '<span class="bz_obsolete">'.$_[0].'</span>' : $_[0];
                    }
                }, 1
            ],
666 667 668 669 670

            # Returns the text with backslashes, single/double quotes,
            # and newlines/carriage returns escaped for use in JS strings.
            js => sub {
                my ($var) = @_;
671
                $var =~ s/([\\\'\"\/])/\\$1/g;
672 673
                $var =~ s/\n/\\n/g;
                $var =~ s/\r/\\r/g;
674
                $var =~ s/\@/\\x40/g; # anti-spam for email addresses
675
                $var =~ s/</\\x3c/g;
676 677
                return $var;
            },
678 679 680 681 682 683 684
            
            # Converts data to base64
            base64 => sub {
                my ($data) = @_;
                return encode_base64($data);
            },
            
685 686 687 688 689 690
            # HTML collapses newlines in element attributes to a single space,
            # so form elements which may have whitespace (ie comments) need
            # to be encoded using &#013;
            # See bugs 4928, 22983 and 32000 for more details
            html_linebreak => sub {
                my ($var) = @_;
691
                $var = html_quote($var);
692 693 694 695 696 697 698
                $var =~ s/\r\n/\&#013;/g;
                $var =~ s/\n\r/\&#013;/g;
                $var =~ s/\r/\&#013;/g;
                $var =~ s/\n/\&#013;/g;
                return $var;
            },

699 700 701 702 703 704 705 706
            # Prevents line break on hyphens and whitespaces.
            no_break => sub {
                my ($var) = @_;
                $var =~ s/ /\&nbsp;/g;
                $var =~ s/-/\&#8209;/g;
                return $var;
            },

707 708
            xml => \&Bugzilla::Util::xml_quote ,

709 710 711 712
            # This filter is similar to url_quote but used a \ instead of a %
            # as prefix. In addition it replaces a ' ' by a '_'.
            css_class_quote => \&Bugzilla::Util::css_class_quote ,

713
            quoteUrls => [ sub {
714
                               my ($context, $bug, $comment) = @_;
715 716
                               return sub {
                                   my $text = shift;
717
                                   return quoteUrls($text, $bug, $comment);
718 719 720 721
                               };
                           },
                           1
                         ],
722 723

            bug_link => [ sub {
724
                              my ($context, $bug, $options) = @_;
725 726
                              return sub {
                                  my $text = shift;
727
                                  return get_bug_link($bug, $text, $options);
728 729 730 731 732
                              };
                          },
                          1
                        ],

733 734 735 736 737 738
            bug_list_link => sub
            {
                my $buglist = shift;
                return join(", ", map(get_bug_link($_, $_), split(/ *, */, $buglist)));
            },

739 740 741 742 743 744 745 746 747 748 749 750
            # In CSV, quotes are doubled, and any value containing a quote or a
            # comma is enclosed in quotes.
            csv => sub
            {
                my ($var) = @_;
                $var =~ s/\"/\"\"/g;
                if ($var !~ /^-?(\d+\.)?\d*$/) {
                    $var = "\"$var\"";
                }
                return $var;
            } ,

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
            # Format a filesize in bytes to a human readable value
            unitconvert => sub
            {
                my ($data) = @_;
                my $retval = "";
                my %units = (
                    'KB' => 1024,
                    'MB' => 1024 * 1024,
                    'GB' => 1024 * 1024 * 1024,
                );

                if ($data < 1024) {
                    return "$data bytes";
                } 
                else {
                    my $u;
                    foreach $u ('GB', 'MB', 'KB') {
                        if ($data >= $units{$u}) {
                            return sprintf("%.2f %s", $data/$units{$u}, $u);
                        }
                    }
                }
            },

775
            # Format a time for display (more info in Bugzilla::Util)
776
            time => [ sub {
777
                          my ($context, $format, $timezone) = @_;
778 779
                          return sub {
                              my $time = shift;
780
                              return format_time($time, $format, $timezone);
781 782 783 784
                          };
                      },
                      1
                    ],
785

786
            html => \&Bugzilla::Util::html_quote,
787 788 789

            html_light => \&Bugzilla::Util::html_light_quote,

790
            email => \&Bugzilla::Util::email_filter,
791 792
            
            mtime_url => \&mtime_filter,
793

794 795 796 797 798 799 800 801 802
            # iCalendar contentline filter
            ics => [ sub {
                         my ($context, @args) = @_;
                         return sub {
                             my ($var) = shift;
                             my ($par) = shift @args;
                             my ($output) = "";

                             $var =~ s/[\r\n]/ /g;
803
                             $var =~ s/([;\\\",])/\\$1/g;
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818

                             if ($par) {
                                 $output = sprintf("%s:%s", $par, $var);
                             } else {
                                 $output = $var;
                             }
                             
                             $output =~ s/(.{75,75})/$1\n /g;

                             return $output;
                         };
                     },
                     1
                     ],

819 820 821 822 823 824 825 826 827 828 829 830 831
            # Note that using this filter is even more dangerous than
            # using "none," and you should only use it when you're SURE
            # the output won't be displayed directly to a web browser.
            txt => sub {
                my ($var) = @_;
                # Trivial HTML tag remover
                $var =~ s/<[^>]*>//g;
                # And this basically reverses the html filter.
                $var =~ s/\&#64;/@/g;
                $var =~ s/\&lt;/</g;
                $var =~ s/\&gt;/>/g;
                $var =~ s/\&quot;/\"/g;
                $var =~ s/\&amp;/\&/g;
832
                # Now remove extra whitespace...
833 834
                my $collapse_filter = $Template::Filters::FILTERS->{collapse};
                $var = $collapse_filter->($var);
835 836 837 838 839 840 841 842 843
                # And if we're not in the WebService, wrap the message.
                # (Wrapping the message in the WebService is unnecessary
                # and causes awkward things like \n's appearing in error
                # messages in JSON-RPC.)
                unless (Bugzilla->usage_mode == USAGE_MODE_JSON
                        or Bugzilla->usage_mode == USAGE_MODE_XMLRPC)
                {
                    $var = wrap_comment($var, 72);
                }
844 845
                $var =~ s/\&nbsp;/ /g;

846 847 848
                return $var;
            },

849
            # Wrap a displayed comment to the appropriate length
850 851 852 853 854
            wrap_comment => [
                sub {
                    my ($context, $cols) = @_;
                    return sub { wrap_comment($_[0], $cols) }
                }, 1],
855

856 857 858 859
            # We force filtering of every variable in key security-critical
            # places; we have a none filter for people to use when they 
            # really, really don't want a variable to be changed.
            none => sub { return $_[0]; } ,
860 861 862 863
        },

        PLUGIN_BASE => 'Bugzilla::Template::Plugin',

864
        CONSTANTS => _load_constants(),
865

866 867 868
        # Default variables for all templates
        VARIABLES => {
            # Function for retrieving global parameters.
869
            'Param' => sub { return Bugzilla->params->{$_[0]}; },
870 871 872 873

            # Function to create date strings
            'time2str' => \&Date::Format::time2str,

874 875 876 877 878 879 880 881
            # Fixed size column formatting for bugmail.
            'format_columns' => sub {
                my $cols = shift;
                my $format = ($cols == 3) ? FORMAT_TRIPLE : FORMAT_DOUBLE;
                my $col_size = ($cols == 3) ? FORMAT_3_SIZE : FORMAT_2_SIZE;
                return multiline_sprintf($format, \@_, $col_size);
            },

882
            # Generic linear search function
883 884 885 886
            'lsearch' => sub {
                my ($array, $item) = @_;
                return firstidx { $_ eq $item } @$array;
            },
887

888
            # Currently logged in user, if any
889
            # If an sudo session is in progress, this is the user we're faking
890
            'user' => sub { return Bugzilla->user; },
891 892 893 894 895 896 897 898
           
            # Currenly active language
            # XXX Eventually this should probably be replaced with something
            # like Bugzilla->language.
            'current_language' => sub {
                my ($language) = include_languages();
                return $language;
            },
899

900 901 902 903
            # If an sudo session is in progress, this is the user who
            # started the session.
            'sudoer' => sub { return Bugzilla->sudoer; },

904 905 906
            # Allow templates to access the "corect" URLBase value
            'urlbase' => sub { return Bugzilla::Util::correct_urlbase(); },

907 908 909 910 911 912 913 914
            # Allow templates to access docs url with users' preferred language
            'docs_urlbase' => sub { 
                my ($language) = include_languages();
                my $docs_urlbase = Bugzilla->params->{'docs_urlbase'};
                $docs_urlbase =~ s/\%lang\%/$language/;
                return $docs_urlbase;
            },

915 916 917
            # Allow templates to generate a token themselves.
            'issue_hash_token' => \&Bugzilla::Token::issue_hash_token,

918 919 920
            # A way for all templates to get at Field data, cached.
            'bug_fields' => sub {
                my $cache = Bugzilla->request_cache;
921 922
                $cache->{template_bug_fields} ||=
                    Bugzilla->fields({ by_name => 1 });
923 924
                return $cache->{template_bug_fields};
            },
925 926 927
            
            'css_files' => \&css_files,
            yui_resolve_deps => \&yui_resolve_deps,
928

929 930
            # Whether or not keywords are enabled, in this Bugzilla.
            'use_keywords' => sub { return Bugzilla::Keyword->any_exist; },
931

932 933 934
            # All the keywords.
            'all_keywords' => sub { return Bugzilla::Keyword->get_all(); },

935 936
            'feature_enabled' => sub { return Bugzilla->feature(@_); },

937 938 939 940 941
            # field_descs can be somewhat slow to generate, so we generate
            # it only once per-language no matter how many times
            # $template->process() is called.
            'field_descs' => sub { return template_var('field_descs') },

942 943
            'install_string' => \&Bugzilla::Install::Util::install_string,

944 945
            'report_columns' => \&Bugzilla::Search::REPORT_COLUMNS,

946 947 948 949 950 951
            # These don't work as normal constants.
            DB_MODULE        => \&Bugzilla::Constants::DB_MODULE,
            REQUIRED_MODULES => 
                \&Bugzilla::Install::Requirements::REQUIRED_MODULES,
            OPTIONAL_MODULES => sub {
                my @optional = @{OPTIONAL_MODULES()};
952 953 954 955 956 957 958
                foreach my $item (@optional) {
                    my @features;
                    foreach my $feat_id (@{ $item->{feature} }) {
                        push(@features, install_string("feature_$feat_id"));
                    }
                    $item->{feature} = \@features;
                }
959 960
                return \@optional;
            },
961
        },
962
    };
963

964 965
    local $Template::Config::CONTEXT = 'Bugzilla::Template::Context';

966
    Bugzilla::Hook::process('template_before_create', { config => $config });
967 968
    my $template = $class->new($config) 
        || die("Template creation failed: " . $class->error());
969 970 971 972 973

    # Pass on our current language to any template hooks or inner templates
    # called by this Template object.
    $template->context->{bz_language} = $opts{language} || '';

974
    return $template;
975 976
}

977
# Used as part of the two subroutines below.
978
our %_templates_to_precompile;
979 980 981 982 983 984
sub precompile_templates {
    my ($output) = @_;

    # Remove the compiled templates.
    my $datadir = bz_locations()->{'datadir'};
    if (-e "$datadir/template") {
985
        print install_string('template_removing_dir') . "\n" if $output;
986

987 988
        # This frequently fails if the webserver made the files, because
        # then the webserver owns the directories.
989 990
        rmtree("$datadir/template");

991 992 993 994 995 996 997 998 999 1000
        # Check that the directory was really removed, and if not, move it
        # into data/deleteme/.
        if (-e "$datadir/template") {
            print STDERR "\n\n",
                install_string('template_removal_failed', 
                               { datadir => $datadir }), "\n\n";
            mkpath("$datadir/deleteme");
            my $random = generate_random_password();
            rename("$datadir/template", "$datadir/deleteme/$random")
              or die "move failed: $!";
1001 1002 1003
        }
    }

1004
    print install_string('template_precompile') if $output;
1005

1006
    my $paths = template_include_path();
1007 1008 1009 1010

    foreach my $dir (@$paths) {
        my $template = Bugzilla::Template->create(include_path => [$dir]);

1011
        %_templates_to_precompile = ();
1012 1013
        # Traverse the template hierarchy.
        find({ wanted => \&_precompile_push, no_chdir => 1 }, $dir);
1014 1015 1016
        # The sort isn't totally necessary, but it makes debugging easier
        # by making the templates always be compiled in the same order.
        foreach my $file (sort keys %_templates_to_precompile) {
1017
            $file =~ s{^\Q$dir\E/}{};
1018 1019 1020 1021 1022
            # Compile the template but throw away the result. This has the side-
            # effect of writing the compiled version to disk.
            $template->context->template($file);
        }
    }
1023

1024 1025 1026
    # Under mod_perl, we look for templates using the absolute path of the
    # template directory, which causes Template Toolkit to look for their 
    # *compiled* versions using the full absolute path under the data/template
1027
    # directory. (Like data/template/var/www/html/bugzilla/.) To avoid
1028
    # re-compiling templates under mod_perl, we symlink to the
1029 1030
    # already-compiled templates. This doesn't work on Windows.
    if (!ON_WINDOWS) {
1031 1032 1033
        # We do these separately in case they're in different locations.
        _do_template_symlink(bz_locations()->{'templatedir'});
        _do_template_symlink(bz_locations()->{'extensionsdir'});
1034
    }
1035

1036 1037
    # If anything created a Template object before now, clear it out.
    delete Bugzilla->request_cache->{template};
1038 1039

    print install_string('done') . "\n" if $output;
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
}

# Helper for precompile_templates
sub _precompile_push {
    my $name = $File::Find::name;
    return if (-d $name);
    return if ($name =~ /\/CVS\//);
    return if ($name !~ /\.tmpl$/);
    $_templates_to_precompile{$name} = 1;
}

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
# Helper for precompile_templates
sub _do_template_symlink {
    my $dir_to_symlink = shift;

    my $abs_path = abs_path($dir_to_symlink);

    # If $dir_to_symlink is already an absolute path (as might happen
    # with packagers who set $libpath to an absolute path), then we don't
    # need to do this symlink.
    return if ($abs_path eq $dir_to_symlink);

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    my $abs_root  = dirname($abs_path);
    my $dir_name  = basename($abs_path);
    my $datadir   = bz_locations()->{'datadir'};
    my $container = "$datadir/template$abs_root";
    mkpath($container);
    my $target = "$datadir/template/$dir_name";
    # Check if the directory exists, because if there are no extensions,
    # there won't be an "data/template/extensions" directory to link to.
    if (-d $target) {
        # We use abs2rel so that the symlink will look like 
        # "../../../../template" which works, while just 
        # "data/template/template/" doesn't work.
        my $relative_target = File::Spec->abs2rel($target, $container);

        my $link_name = "$container/$dir_name";
        symlink($relative_target, $link_name)
          or warn "Could not make $link_name a symlink to $relative_target: $!";
    }
1080 1081
}

1082 1083 1084 1085 1086 1087
1;

__END__

=head1 NAME

1088
Bugzilla::Template - Wrapper around the Template Toolkit C<Template> object
1089

1090
=head1 SYNOPSIS
1091 1092

  my $template = Bugzilla::Template->create;
1093 1094 1095 1096
  my $format = $template->get_format("foo/bar",
                                     scalar($cgi->param('format')),
                                     scalar($cgi->param('ctype')));

1097 1098 1099 1100 1101 1102 1103 1104
=head1 DESCRIPTION

This is basically a wrapper so that the correct arguments get passed into
the C<Template> constructor.

It should not be used directly by scripts or modules - instead, use
C<Bugzilla-E<gt>instance-E<gt>template> to get an already created module.

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
=head1 SUBROUTINES

=over

=item C<precompile_templates($output)>

Description: Compiles all of Bugzilla's templates in every language.
             Used mostly by F<checksetup.pl>.

Params:      C<$output> - C<true> if you want the function to print
               out information about what it's doing.

Returns:     nothing

=back

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
=head1 METHODS

=over

=item C<get_format($file, $format, $ctype)>

 Description: Construct a format object from URL parameters.

 Params:      $file   - Name of the template to display.
              $format - When the template exists under several formats
                        (e.g. table or graph), specify the one to choose.
              $ctype  - Content type, see Bugzilla::Constants::contenttypes.

 Returns:     A format object.

=back

1138 1139 1140
=head1 SEE ALSO

L<Bugzilla>, L<Template>