Template.pm 47.7 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7

8 9 10

package Bugzilla::Template;

11
use 5.10.1;
12
use strict;
13
use warnings;
14

15
use Bugzilla::Constants;
16
use Bugzilla::WebService::Constants;
17
use Bugzilla::Hook;
18
use Bugzilla::Install::Requirements;
19 20
use Bugzilla::Install::Util qw(install_string template_include_path 
                               include_languages);
21
use Bugzilla::Classification;
22
use Bugzilla::Keyword;
23
use Bugzilla::Util;
24
use Bugzilla::Error;
25
use Bugzilla::Search;
26
use Bugzilla::Token;
27

28
use Cwd qw(abs_path);
29
use MIME::Base64;
30
use Date::Format ();
31
use Digest::MD5 qw(md5_hex);
32
use File::Basename qw(basename dirname);
33
use File::Find;
34
use File::Path qw(rmtree mkpath);
35
use File::Slurp;
36 37
use File::Spec;
use IO::Dir;
38
use List::MoreUtils qw(firstidx);
39
use Scalar::Util qw(blessed);
40

41
use parent qw(Template);
42

43 44 45 46 47
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];

48 49 50
# Pseudo-constant.
sub SAFE_URL_REGEXP {
    my $safe_protocols = join('|', SAFE_PROTOCOLS);
51
    return qr/($safe_protocols):[^:\s<>\"][^\s<>\"]+[\w\/]/i;
52 53
}

54 55 56
# Convert the constants in the Bugzilla::Constants and Bugzilla::WebService::Constants
# modules into a hash we can pass to the template object for reflection into its "constants" 
# namespace (which is like its "variables" namespace, but for constants). To do so, we
57 58
# 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).
59 60 61 62 63
sub _load_constants {
    my %constants;
    foreach my $constant (@Bugzilla::Constants::EXPORT,
                          @Bugzilla::Constants::EXPORT_OK)
    {
64 65 66 67 68 69
        if (ref Bugzilla::Constants->$constant) {
            $constants{$constant} = Bugzilla::Constants->$constant;
        }
        else {
            my @list = (Bugzilla::Constants->$constant);
            $constants{$constant} = (scalar(@list) == 1) ? $list[0] : \@list;
70 71
        }
    }
72 73 74 75 76 77 78 79 80 81 82 83

    foreach my $constant (@Bugzilla::WebService::Constants::EXPORT, 
                          @Bugzilla::WebService::Constants::EXPORT_OK)
    {
        if (ref Bugzilla::WebService::Constants->$constant) {
            $constants{$constant} = Bugzilla::WebService::Constants->$constant;
        }
        else {
            my @list = (Bugzilla::WebService::Constants->$constant);
            $constants{$constant} = (scalar(@list) == 1) ? $list[0] : \@list;
        }
    }
84
    return \%constants;
85 86
}

87 88 89
# 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
90
# Templates may also be found in the extensions/ tree
91 92
sub _include_path {
    my $lang = shift || '';
93
    my $cache = Bugzilla->request_cache;
94 95
    $cache->{"template_include_path_$lang"} ||= 
        template_include_path({ language => $lang });
96
    return $cache->{"template_include_path_$lang"};
97 98
}

99 100 101 102
sub get_format {
    my $self = shift;
    my ($template, $format, $ctype) = @_;

103 104
    $ctype //= 'html';
    $format //= '';
105

106 107 108 109 110 111
    # ctype and format can have letters and a hyphen only.
    if ($ctype =~ /[^a-zA-Z\-]/ || $format =~ /[^a-zA-Z\-]/) {
        ThrowUserError('format_not_found', {'format' => $format,
                                            'ctype'  => $ctype,
                                            'invalid' => 1});
    }
112 113 114 115 116 117 118 119 120 121 122 123
    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
    # 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,
137
        'format'      => $format,
138 139 140 141
        'extension'   => $ctype,
        'ctype'       => Bugzilla::Constants::contenttypes->{$ctype}
    };
}
142

143 144 145 146 147 148 149 150
# 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 {
151
    my ($text, $bug, $comment, $user, $bug_link_func) = @_;
152
    return $text unless $text;
153
    $user ||= Bugzilla->user;
154
    $bug_link_func ||= \&get_bug_link;
155 156 157 158 159

    # 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
160 161 162 163 164
    # Do this by replacing matches with \x{FDD2}$count\x{FDD3}
    # \x{FDDx} is used because it's unlikely to occur in the text
    # and are reserved unicode characters. We disable warnings for now
    # until we require Perl 5.13.9 or newer.
    no warnings 'utf8';
165

166 167 168 169
    # If the comment is already wrapped, we should ignore newlines when
    # looking for matching regexps. Else we should take them into account.
    my $s = ($comment && $comment->already_wrapped) ? qr/\s/ : qr/\h/;

170 171 172 173
    # 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
174
    # if it was substituted as a bug title (since that always involve leading
175 176
    # and trailing text)

177
    # Because of entities, it's easier (and quicker) to do this before escaping
178 179 180 181 182

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

183
    my @hook_regexes;
184
    Bugzilla::Hook::process('bug_format_comment',
185
        { text => \$text, bug => $bug, regexes => \@hook_regexes,
186
          comment => $comment, user => $user });
187 188 189 190 191 192 193 194

    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]}))
195
                               && ("\x{FDD2}" . ($count-1) . "\x{FDD3}")/egx;
196 197 198
        }
        else {
            $text =~ s/$match/($things[$count++] = $replace) 
199
                              && ("\x{FDD2}" . ($count-1) . "\x{FDD3}")/egx;
200 201 202
        }
    }

203
    # Provide tooltips for full bug links (Bug 74355)
204 205 206
    my $urlbase_re = '(' . join('|',
        map { qr/$_/ } grep($_, Bugzilla->params->{'urlbase'}, 
                            Bugzilla->params->{'sslbase'})) . ')';
207
    $text =~ s~\b(${urlbase_re}\Qshow_bug.cgi?id=\E([0-9]+)(\#c([0-9]+))?)\b
208
              ~($things[$count++] = $bug_link_func->($3, $1, { comment_num => $5, user => $user })) &&
209
               ("\x{FDD2}" . ($count-1) . "\x{FDD3}")
210 211
              ~egox;

212
    # non-mailto protocols
213 214
    my $safe_protocols = SAFE_URL_REGEXP();
    $text =~ s~\b($safe_protocols)
215 216
              ~($tmp = html_quote($1)) &&
               ($things[$count++] = "<a href=\"$tmp\">$tmp</a>") &&
217
               ("\x{FDD2}" . ($count-1) . "\x{FDD3}")
218 219
              ~egox;

220
    # We have to quote now, otherwise the html itself is escaped
221 222 223 224 225 226 227 228 229 230
    # 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
231 232
    # &#64; is the encoded '@' character.
    $text =~ s~\b(mailto:|)?([\w\.\-\+\=]+&\#64;[\w\-]+(?:\.[\w\-]+)+)\b
233 234
              ~<a href=\"mailto:$2\">$1$2</a>~igx;

235
    # attachment links
236
    $text =~ s~\b(attachment$s*\#?$s*(\d+)(?:$s+\[details\])?)
237
              ~($things[$count++] = get_attachment_link($2, $1, $user)) &&
238
               ("\x{FDD2}" . ($count-1) . "\x{FDD3}")
239 240 241
              ~egmxi;

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

    # 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
248
    my $bug_word = template_var('terms')->{bug};
249
    my $bug_re = qr/\Q$bug_word\E$s*\#?$s*(\d+)/i;
250
    my $comment_word = template_var('terms')->{comment};
251 252
    my $comment_re = qr/(?:\Q$comment_word\E|comment)$s*\#?$s*(\d+)/i;
    $text =~ s~\b($bug_re(?:$s*,?$s*$comment_re)?|$comment_re)
253 254
              ~ # We have several choices. $1 here is the link, and $2-4 are set
                # depending on which part matched
255
               (defined($2) ? $bug_link_func->($2, $1, { comment_num => $3, user => $user }) :
256
                              "<a href=\"$current_bugurl#c$4\">$1</a>")
257
              ~egx;
258

259 260 261 262 263
    # Handle a list of bug ids: bugs 1, #2, 3, 4
    # Currently, the only delimiter supported is comma.
    # Concluding "and" and "or" are not supported.
    my $bugs_word = template_var('terms')->{bugs};

264 265
    my $bugs_re = qr/\Q$bugs_word\E$s*\#?$s*
                     \d+(?:$s*,$s*\#?$s*\d+)+/ix;
266

267 268
    $text =~ s{($bugs_re)}{
        my $match = $1;
269
        $match =~ s/((?:#$s*)?(\d+))/$bug_link_func->($2, $1);/eg;
270 271
        $match;
    }eg;
272

273 274
    my $comments_word = template_var('terms')->{comments};

275 276
    my $comments_re = qr/(?:comments|\Q$comments_word\E)$s*\#?$s*
                         \d+(?:$s*,$s*\#?$s*\d+)+/ix;
277

278 279
    $text =~ s{($comments_re)}{
        my $match = $1;
280
        $match =~ s|((?:#$s*)?(\d+))|<a href="$current_bugurl#c$2">$1</a>|g;
281 282
        $match;
    }eg;
283

284 285
    # Old duplicate markers. These don't use $bug_word because they are old
    # and were never customizable.
286 287 288
    $text =~ s~(?<=^\*\*\*\ This\ bug\ has\ been\ marked\ as\ a\ duplicate\ of\ )
               (\d+)
               (?=\ \*\*\*\Z)
289
              ~$bug_link_func->($1, $1, { user => $user })
290 291
              ~egmx;

292 293
    # Now remove the encoding hacks in reverse order
    for (my $i = $#things; $i >= 0; $i--) {
294
        $text =~ s/\x{FDD2}($i)\x{FDD3}/$things[$i]/eg;
295
    }
296 297 298 299 300 301

    return $text;
}

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

306
    my $attachment = new Bugzilla::Attachment({ id => $attachid, cache => 1 });
307

308
    if ($attachment) {
309 310
        my $title = "";
        my $className = "";
311 312 313
        if ($user->can_see_bug($attachment->bug_id)
            && (!$attachment->isprivate || $user->is_insider))
        {
314
            $title = $attachment->description;
315
        }
316
        if ($attachment->isobsolete) {
317 318 319
            $className = "bz_obsolete";
        }
        # Prevent code injection in the title.
320
        $title = html_quote(clean_text($title));
321

322
        $link_text =~ s/ \[details\]$//;
323
        my $linkval = "attachment.cgi?id=$attachid";
324 325 326 327

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

332 333
        # Whitespace matters here because these links are in <pre> tags.
        return qq|<span class="$className">|
334
               . qq|<a href="${linkval}${patchlink}" name="attach_${attachid}" title="$title">$link_text</a>|
335
               . qq| <a href="${linkval}&amp;action=edit" title="$title">[details]</a>|
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
               . 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 {
351
    my ($bug, $link_text, $options) = @_;
352
    $options ||= {};
353
    $options->{user} ||= Bugzilla->user;
354 355
    my $dbh = Bugzilla->dbh;

356
    if (defined $bug && $bug ne '') {
357 358
        if (!blessed($bug)) {
            require Bugzilla::Bug;
359
            $bug = new Bugzilla::Bug({ id => $bug, cache => 1 });
360
        }
361
        return $link_text if $bug->{error};
362 363
    }

364 365 366 367 368
    my $template = Bugzilla->template_inner;
    my $linkified;
    $template->process('bug/link.html.tmpl', 
        { bug => $bug, link_text => $link_text, %$options }, \$linkified);
    return $linkified;
369 370
}

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
# 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;
}

401 402 403 404 405 406 407 408 409
#####################
# 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 {
410 411 412 413 414 415 416 417 418 419 420
    my ($file_url, $mtime) = @_;
    # This environment var is set in the .htaccess if we have mod_headers
    # and mod_expires installed, to make sure that JS and CSS with "?"
    # after them will still be cached by clients.
    return $file_url if !$ENV{BZ_CACHE_CONTROL};
    if (!$mtime) {
        my $cgi_path = bz_locations()->{'cgi_path'};
        my $file_path = "$cgi_path/$file_url";
        $mtime = _mtime($file_path);
    }
    return "$file_url?$mtime";
421 422 423 424
}

# Set up the skin CSS cascade:
#
425 426 427 428 429 430
#  1. standard/global.css
#  2. YUI CSS
#  3. Standard Bugzilla stylesheet set
#  4. Third-party "skin" stylesheet set, per user prefs
#  5. Inline css passed to global/header.html.tmpl
#  6. Custom Bugzilla stylesheet set
431

432 433
sub css_files {
    my ($style_urls, $yui, $yui_css) = @_;
434 435 436

    # global.css goes on every page.
    my @requested_css = ('skins/standard/global.css', @$style_urls);
437 438 439 440 441 442 443 444 445 446

    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;
    
447
    my %by_type = (standard => [], skin => [], custom => []);
448 449
    foreach my $set (@css_sets) {
        foreach my $key (keys %$set) {
450
            push(@{ $by_type{$key} }, $set->{$key});
451 452
        }
    }
453 454 455 456 457 458

    # build unified
    $by_type{unified_standard_skin} = _concatenate_css($by_type{standard},
                                                       $by_type{skin});
    $by_type{unified_custom} = _concatenate_css($by_type{custom});

459 460 461 462 463 464
    return \%by_type;
}

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

465
    my %set = (standard => mtime_filter($file_name));
466 467 468

    # We use (?:^|/) to allow Extensions to use the skins system if they want.
    if ($file_name !~ m{(?:^|/)skins/standard/}) {
469 470
        return \%set;
    }
471 472

    my $skin = Bugzilla->user->settings->{skin}->{value};
473
    my $cgi_path = bz_locations()->{'cgi_path'};
474
    my $skin_file_name = $file_name;
475
    $skin_file_name =~ s{(?:^|/)skins/standard/}{skins/contrib/$skin/};
476 477
    if (my $mtime = _mtime("$cgi_path/$skin_file_name")) {
        $set{skin} = mtime_filter($skin_file_name, $mtime);
478
    }
479

480
    my $custom_file_name = $file_name;
481
    $custom_file_name =~ s{(?:^|/)skins/standard/}{skins/custom/};
482
    if (my $custom_mtime = _mtime("$cgi_path/$custom_file_name")) {
483
        $set{custom} = mtime_filter($custom_file_name, $custom_mtime);
484
    }
485

486 487 488
    return \%set;
}

489 490 491 492 493 494
sub _concatenate_css {
    my @sources = map { @$_ } @_;
    return unless @sources;

    my %files =
        map {
495
            (my $file = $_) =~ s/(^[^\?]+)\?.+/$1/;
496 497 498 499
            $_ => $file;
        } @sources;

    my $cgi_path   = bz_locations()->{cgi_path};
500
    my $skins_path = bz_locations()->{assetsdir};
501 502 503 504 505

    # build minified files
    my @minified;
    foreach my $source (@sources) {
        next unless -e "$cgi_path/$files{$source}";
506
        my $file = $skins_path . '/' . md5_hex($source) . '.css';
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        if (!-e $file) {
            my $content = read_file("$cgi_path/$files{$source}");

            # minify
            $content =~ s{/\*.*?\*/}{}sg;   # comments
            $content =~ s{(^\s+|\s+$)}{}mg; # leading/trailing whitespace
            $content =~ s{\n}{}g;           # single line

            # rewrite urls
            $content =~ s{url\(([^\)]+)\)}{_css_url_rewrite($source, $1)}eig;

            write_file($file, "/* $files{$source} */\n" . $content . "\n");
        }
        push @minified, $file;
    }

    # concat files
524
    my $file = $skins_path . '/' . md5_hex(join(' ', @sources)) . '.css';
525 526 527 528 529 530 531 532
    if (!-e $file) {
        my $content = '';
        foreach my $source (@minified) {
            $content .= read_file($source);
        }
        write_file($file, $content);
    }

533
    $file =~ s/^\Q$cgi_path\E\///o;
534 535 536 537 538 539 540 541 542 543 544 545
    return mtime_filter($file);
}

sub _css_url_rewrite {
    my ($source, $url) = @_;
    # rewrite relative urls as the unified stylesheet lives in a different
    # directory from the source
    $url =~ s/(^['"]|['"]$)//g;
    return $url if substr($url, 0, 1) eq '/';
    return 'url(../../' . dirname($source) . '/' . $url . ')';
}

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
sub _concatenate_js {
    return @_ unless CONCATENATE_ASSETS;
    my ($sources) = @_;
    return [] unless $sources && ref($sources);

    my %files =
        map {
            (my $file = $_) =~ s/(^[^\?]+)\?.+/$1/;
            $_ => $file;
        } @$sources;

    my $cgi_path   = bz_locations()->{cgi_path};
    my $skins_path = bz_locations()->{assetsdir};

    # build minified files
    my @minified;
    foreach my $source (@$sources) {
        next unless -e "$cgi_path/$files{$source}";
        my $file = $skins_path . '/' . md5_hex($source) . '.js';
        if (!-e $file) {
            my $content = read_file("$cgi_path/$files{$source}");

            # minimal minification
            $content =~ s#/\*.*?\*/##sg;    # block comments
            $content =~ s#(^ +| +$)##gm;    # leading/trailing spaces
            $content =~ s#^//.+$##gm;       # single line comments
            $content =~ s#\n{2,}#\n#g;      # blank lines
            $content =~ s#(^\s+|\s+$)##g;   # whitespace at the start/end of file

            write_file($file, "/* $files{$source} */\n" . $content . "\n");
        }
        push @minified, $file;
    }

    # concat files
    my $file = $skins_path . '/' . md5_hex(join(' ', @$sources)) . '.js';
    if (!-e $file) {
        my $content = '';
        foreach my $source (@minified) {
            $content .= read_file($source);
        }
        write_file($file, $content);
    }

    $file =~ s/^\Q$cgi_path\E\///o;
    return [ $file ];
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
# 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;
}

609 610 611
###############################################################################
# Templatization Code

612 613 614 615 616 617
# 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;

618 619 620 621
# Use the Toolkit Template's Stash module to add utility pseudo-methods
# to template variables.
use Template::Stash;

622 623 624
# Allow keys to start with an underscore or a dot.
$Template::Stash::PRIVATE = undef;

625 626 627 628 629 630
# 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) = @_;
631 632 633 634 635
      if (ref $item && $item->isa('Bugzilla::Object')) {
          return grep($_->id == $item->id, @$list);
      } else {
          return grep($_ eq $item, @$list);
      }
636 637 638 639 640 641
  };

$Template::Stash::LIST_OPS->{ containsany } =
  sub {
      my ($list, $items) = @_;
      foreach my $item (@$items) { 
642 643 644 645 646
          if (ref $item && $item->isa('Bugzilla::Object')) {
              return 1 if grep($_->id == $item->id, @$list);
          } else {
              return 1 if grep($_ eq $item, @$list);
          }
647 648 649 650
      }
      return 0;
  };

651 652 653 654 655 656 657
# Clone the array reference to leave the original one unaltered.
$Template::Stash::LIST_OPS->{ clone } =
  sub {
      my $list = shift;
      return [@$list];
  };

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
# Allow us to sort the list of fields correctly
$Template::Stash::LIST_OPS->{ sort_by_field_name } =
    sub {
        sub field_name {
            if ($_[0] eq 'noop') {
                # Sort --- first
                return '';
            }
            # Otherwise sort by field_desc or description
            return $_[1]{$_[0]} || $_[0];
        }
        my ($list, $field_desc) = @_;
        return [ sort { lc field_name($a, $field_desc) cmp lc field_name($b, $field_desc) } @$list ];
    };

673 674 675 676 677 678 679
# 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];
  };

680 681 682 683 684 685
# 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) = @_;
      return $string if !$length || length($string) <= $length;
686 687

      $ellipsis ||= '';
688 689 690 691 692 693 694 695 696 697
      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.

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

698 699 700 701 702 703 704 705 706 707 708
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;
}

709 710 711 712 713 714 715
# 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;
716 717
    my %opts = @_;

718 719
    # IMPORTANT - If you make any FILTER changes here, make sure to
    # make them in t/004.template.t also, if required.
720

721
    my $config = {
722
        # Colon-separated list of directories containing templates.
723 724
        INCLUDE_PATH => $opts{'include_path'} 
                        || _include_path($opts{'language'}),
725 726 727 728 729 730 731 732

        # 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,

733 734 735 736 737 738 739 740
        # 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,

741
        COMPILE_DIR => bz_locations()->{'template_cache'},
742

743 744 745 746
        # Don't check for a template update until 1 hour has passed since the
        # last check.
        STAT_TTL    => 60 * 60,

747
        # Initialize templates (f.e. by loading plugins like Hook).
748
        PRE_PROCESS => ["global/variables.none.tmpl"],
749

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

752 753
        # Functions for processing text within templates in various ways.
        # IMPORTANT!  When adding a filter here that does not override a
754
        # built-in filter, please also add a stub filter to t/004template.t.
755
        FILTERS => {
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

            # 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
            ],
785 786 787 788 789

            # Returns the text with backslashes, single/double quotes,
            # and newlines/carriage returns escaped for use in JS strings.
            js => sub {
                my ($var) = @_;
790
                $var =~ s/([\\\'\"\/])/\\$1/g;
791 792
                $var =~ s/\n/\\n/g;
                $var =~ s/\r/\\r/g;
793
                $var =~ s/\@/\\x40/g; # anti-spam for email addresses
794
                $var =~ s/</\\x3c/g;
795
                $var =~ s/>/\\x3e/g;
796 797
                return $var;
            },
798 799 800 801 802 803
            
            # Converts data to base64
            base64 => sub {
                my ($data) = @_;
                return encode_base64($data);
            },
804 805 806 807 808 809 810 811 812 813 814 815

            # Strips out control characters excepting whitespace
            strip_control_chars => sub {
                my ($data) = @_;
                state $use_utf8 = Bugzilla->params->{'utf8'};
                # Only run for utf8 to avoid issues with other multibyte encodings 
                # that may be reassigning meaning to ascii characters.
                if ($use_utf8) {
                    $data =~ s/(?![\t\r\n])[[:cntrl:]]//g;
                }
                return $data;
            },
816
            
817 818 819 820 821 822
            # 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) = @_;
823
                $var = html_quote($var);
824 825 826 827 828 829 830
                $var =~ s/\r\n/\&#013;/g;
                $var =~ s/\n\r/\&#013;/g;
                $var =~ s/\r/\&#013;/g;
                $var =~ s/\n/\&#013;/g;
                return $var;
            },

831 832 833 834 835 836 837 838
            # Prevents line break on hyphens and whitespaces.
            no_break => sub {
                my ($var) = @_;
                $var =~ s/ /\&nbsp;/g;
                $var =~ s/-/\&#8209;/g;
                return $var;
            },

839 840
            xml => \&Bugzilla::Util::xml_quote ,

841 842 843 844
            # 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 ,

845 846 847
            # Removes control characters and trims extra whitespace.
            clean_text => \&Bugzilla::Util::clean_text ,

848
            quoteUrls => [ sub {
849
                               my ($context, $bug, $comment, $user) = @_;
850 851
                               return sub {
                                   my $text = shift;
852
                                   return quoteUrls($text, $bug, $comment, $user);
853 854 855 856
                               };
                           },
                           1
                         ],
857

858 859 860 861 862 863
            markdown => [ sub {
                              my ($context, $bug, $comment, $user) = @_;
                              return sub {
                                  my $text = shift;
                                  return unless $text;

864 865 866
                                  if (Bugzilla->feature('markdown')
                                      && ((ref($comment) eq 'HASH' && $comment->{is_markdown})
                                         || (ref($comment) eq 'Bugzilla::Comment' && $comment->is_markdown)))
867 868 869 870 871 872 873 874 875
                                  {
                                      return Bugzilla->markdown->markdown($text);
                                  }
                                  return quoteUrls($text, $bug, $comment, $user);
                              };
                          },
                          1
                        ],

876
            bug_link => [ sub {
877
                              my ($context, $bug, $options) = @_;
878 879
                              return sub {
                                  my $text = shift;
880
                                  return get_bug_link($bug, $text, $options);
881 882 883 884 885
                              };
                          },
                          1
                        ],

886 887 888
            bug_list_link => sub {
                my ($buglist, $options) = @_;
                return join(", ", map(get_bug_link($_, $_, $options), split(/ *, */, $buglist)));
889 890
            },

891 892 893 894 895 896 897 898 899 900 901 902
            # 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;
            } ,

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
            # 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);
                        }
                    }
                }
            },

927
            # Format a time for display (more info in Bugzilla::Util)
928
            time => [ sub {
929
                          my ($context, $format, $timezone) = @_;
930 931
                          return sub {
                              my $time = shift;
932
                              return format_time($time, $format, $timezone);
933 934 935 936
                          };
                      },
                      1
                    ],
937

938
            html => \&Bugzilla::Util::html_quote,
939 940 941

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

942
            email => \&Bugzilla::Util::email_filter,
943
            
944
            mtime => \&mtime_filter,
945

946 947 948 949 950 951 952 953 954
            # iCalendar contentline filter
            ics => [ sub {
                         my ($context, @args) = @_;
                         return sub {
                             my ($var) = shift;
                             my ($par) = shift @args;
                             my ($output) = "";

                             $var =~ s/[\r\n]/ /g;
955
                             $var =~ s/([;\\\",])/\\$1/g;
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

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

                             return $output;
                         };
                     },
                     1
                     ],

971 972 973 974 975 976 977 978 979 980 981 982 983
            # 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;
984
                # Now remove extra whitespace...
985 986
                my $collapse_filter = $Template::Filters::FILTERS->{collapse};
                $var = $collapse_filter->($var);
987 988 989 990
                # 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.)
991
                unless (i_am_webservice()) {
992 993
                    $var = wrap_comment($var, 72);
                }
994 995
                $var =~ s/\&nbsp;/ /g;

996 997 998
                return $var;
            },

999
            # Wrap a displayed comment to the appropriate length
1000 1001 1002 1003 1004
            wrap_comment => [
                sub {
                    my ($context, $cols) = @_;
                    return sub { wrap_comment($_[0], $cols) }
                }, 1],
1005

1006 1007 1008 1009
            # 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]; } ,
1010 1011 1012 1013
        },

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

1014
        CONSTANTS => _load_constants(),
1015

1016 1017 1018
        # Default variables for all templates
        VARIABLES => {
            # Function for retrieving global parameters.
1019
            'Param' => sub { return Bugzilla->params->{$_[0]}; },
1020 1021 1022 1023

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

1024 1025 1026 1027 1028 1029 1030 1031
            # 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);
            },

1032
            # Generic linear search function
1033 1034 1035 1036
            'lsearch' => sub {
                my ($array, $item) = @_;
                return firstidx { $_ eq $item } @$array;
            },
1037

1038
            # Currently logged in user, if any
1039
            # If an sudo session is in progress, this is the user we're faking
1040
            'user' => sub { return Bugzilla->user; },
1041

1042
            # Currenly active language
1043
            'current_language' => sub { return Bugzilla->current_language; },
1044

1045 1046 1047 1048
            # If an sudo session is in progress, this is the user who
            # started the session.
            'sudoer' => sub { return Bugzilla->sudoer; },

1049
            # Allow templates to access the "correct" URLBase value
1050 1051
            'urlbase' => sub { return Bugzilla::Util::correct_urlbase(); },

1052 1053
            # Allow templates to access docs url with users' preferred language
            'docs_urlbase' => sub { 
1054
                my $language = Bugzilla->current_language;
1055 1056 1057 1058 1059
                my $docs_urlbase = Bugzilla->params->{'docs_urlbase'};
                $docs_urlbase =~ s/\%lang\%/$language/;
                return $docs_urlbase;
            },

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
            # Check whether the URL is safe.
            'is_safe_url' => sub {
                my $url = shift;
                return 0 unless $url;

                my $safe_url_regexp = SAFE_URL_REGEXP();
                return 1 if $url =~ /^$safe_url_regexp$/;
                # Pointing to a local file with no colon in its name is fine.
                return 1 if $url =~ /^[^\s<>\":]+[\w\/]$/i;
                # If we come here, then we cannot guarantee it's safe.
                return 0;
            },

1073 1074 1075
            # Allow templates to generate a token themselves.
            'issue_hash_token' => \&Bugzilla::Token::issue_hash_token,

1076 1077 1078 1079 1080
            'get_login_request_token' => sub {
                my $cookie = Bugzilla->cgi->cookie('Bugzilla_login_request_cookie');
                return $cookie ? issue_hash_token(['login_request', $cookie]) : '';
            },

1081 1082 1083 1084 1085 1086
            'get_api_token' => sub {
                return '' unless Bugzilla->user->id;
                my $cache = Bugzilla->request_cache;
                return $cache->{api_token} //= issue_api_token();
            },

1087 1088 1089
            # A way for all templates to get at Field data, cached.
            'bug_fields' => sub {
                my $cache = Bugzilla->request_cache;
1090 1091
                $cache->{template_bug_fields} ||=
                    Bugzilla->fields({ by_name => 1 });
1092 1093
                return $cache->{template_bug_fields};
            },
1094 1095 1096 1097 1098 1099 1100 1101 1102

            # A general purpose cache to store rendered templates for reuse.
            # Make sure to not mix language-specific data.
            'template_cache' => sub {
                my $cache = Bugzilla->request_cache->{template_cache} ||= {};
                $cache->{users} ||= {};
                return $cache;
            },

1103 1104
            'css_files' => \&css_files,
            yui_resolve_deps => \&yui_resolve_deps,
1105
            concatenate_js => \&_concatenate_js,
1106

1107 1108 1109 1110 1111
            # All classifications (sorted by sortkey, name)
            'all_classifications' => sub {
                return [map { $_->name } Bugzilla::Classification->get_all()];
            },

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

1115
            # All the keywords.
1116 1117 1118
            'all_keywords' => sub {
                return [map { $_->name } Bugzilla::Keyword->get_all()];
            },
1119

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

1122 1123 1124 1125
            # 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') },
1126 1127 1128 1129 1130

            # Calling bug/field-help.none.tmpl once per label is very
            # expensive, so we generate it once per-language.
            'help_html' => sub { return template_var('help_html') },

1131 1132 1133
            # This way we don't have to load field-descs.none.tmpl in
            # many templates.
            'display_value' => \&Bugzilla::Util::display_value,
1134

1135 1136
            'install_string' => \&Bugzilla::Install::Util::install_string,

1137 1138
            'report_columns' => \&Bugzilla::Search::REPORT_COLUMNS,

1139 1140 1141 1142 1143 1144
            # 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()};
1145 1146 1147 1148 1149 1150 1151
                foreach my $item (@optional) {
                    my @features;
                    foreach my $feat_id (@{ $item->{feature} }) {
                        push(@features, install_string("feature_$feat_id"));
                    }
                    $item->{feature} = \@features;
                }
1152 1153
                return \@optional;
            },
1154
            'default_authorizer' => sub { return Bugzilla::Auth->new() },
1155
        },
1156
    };
1157 1158
    # Use a per-process provider to cache compiled templates in memory across
    # requests.
1159
    my $provider_key = join(':', @{ $config->{INCLUDE_PATH} });
1160 1161 1162
    my $shared_providers = Bugzilla->process_cache->{shared_providers} ||= {};
    $shared_providers->{$provider_key} ||= Template::Provider->new($config);
    $config->{LOAD_TEMPLATES} = [ $shared_providers->{$provider_key} ];
1163

1164 1165
    local $Template::Config::CONTEXT = 'Bugzilla::Template::Context';

1166
    Bugzilla::Hook::process('template_before_create', { config => $config });
1167 1168
    my $template = $class->new($config) 
        || die("Template creation failed: " . $class->error());
1169 1170 1171 1172 1173

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

1174
    return $template;
1175 1176
}

1177
# Used as part of the two subroutines below.
1178
our %_templates_to_precompile;
1179 1180 1181 1182
sub precompile_templates {
    my ($output) = @_;

    # Remove the compiled templates.
1183
    my $cache_dir = bz_locations()->{'template_cache'};
1184
    my $datadir = bz_locations()->{'datadir'};
1185
    if (-e $cache_dir) {
1186
        print install_string('template_removing_dir') . "\n" if $output;
1187

1188 1189
        # This frequently fails if the webserver made the files, because
        # then the webserver owns the directories.
1190
        rmtree($cache_dir);
1191

1192 1193
        # Check that the directory was really removed, and if not, move it
        # into data/deleteme/.
1194 1195 1196
        if (-e $cache_dir) {
            my $deleteme = "$datadir/deleteme";
            
1197 1198
            print STDERR "\n\n",
                install_string('template_removal_failed', 
1199 1200 1201
                               { deleteme => $deleteme, 
                                 template_cache => $cache_dir }), "\n\n";
            mkpath($deleteme);
1202
            my $random = generate_random_password();
1203
            rename($cache_dir, "$deleteme/$random")
1204
              or die "move failed: $!";
1205 1206 1207
        }
    }

1208
    print install_string('template_precompile') if $output;
1209

1210 1211
    # Pre-compile all available languages.
    my $paths = template_include_path({ language => Bugzilla->languages });
1212 1213 1214 1215

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

1216
        %_templates_to_precompile = ();
1217 1218
        # Traverse the template hierarchy.
        find({ wanted => \&_precompile_push, no_chdir => 1 }, $dir);
1219 1220 1221
        # 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) {
1222
            $file =~ s{^\Q$dir\E/}{};
1223 1224 1225 1226
            # Compile the template but throw away the result. This has the side-
            # effect of writing the compiled version to disk.
            $template->context->template($file);
        }
1227 1228

        # Clear out the cached Provider object
1229
        Bugzilla->process_cache->{shared_providers} = undef;
1230
    }
1231

1232 1233 1234
    # 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
1235
    # directory. (Like data/template/var/www/html/bugzilla/.) To avoid
1236
    # re-compiling templates under mod_perl, we symlink to the
1237 1238
    # already-compiled templates. This doesn't work on Windows.
    if (!ON_WINDOWS) {
1239 1240 1241
        # We do these separately in case they're in different locations.
        _do_template_symlink(bz_locations()->{'templatedir'});
        _do_template_symlink(bz_locations()->{'extensionsdir'});
1242
    }
1243

1244 1245
    # If anything created a Template object before now, clear it out.
    delete Bugzilla->request_cache->{template};
1246 1247

    print install_string('done') . "\n" if $output;
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
}

# 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;
}

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
# 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);

1270 1271
    my $abs_root  = dirname($abs_path);
    my $dir_name  = basename($abs_path);
1272 1273
    my $cache_dir   = bz_locations()->{'template_cache'};
    my $container = "$cache_dir$abs_root";
1274
    mkpath($container);
1275
    my $target = "$cache_dir/$dir_name";
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    # 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: $!";
    }
1288 1289
}

1290 1291 1292 1293 1294 1295
1;

__END__

=head1 NAME

1296
Bugzilla::Template - Wrapper around the Template Toolkit C<Template> object
1297

1298
=head1 SYNOPSIS
1299 1300

  my $template = Bugzilla::Template->create;
1301 1302 1303 1304
  my $format = $template->get_format("foo/bar",
                                     scalar($cgi->param('format')),
                                     scalar($cgi->param('ctype')));

1305 1306 1307 1308 1309 1310 1311 1312
=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.

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
=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

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
=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

1346 1347 1348
=head1 SEE ALSO

L<Bugzilla>, L<Template>
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

=head1 B<Methods in need of POD>

=over

=item multiline_sprintf

=item create

=item css_files

=item mtime_filter

=item yui_resolve_deps

=item process

=item get_bug_link

=item quoteUrls

=item get_attachment_link

=item SAFE_URL_REGEXP

=back