/
Render.pm
2106 lines (1726 loc) · 67.3 KB
/
Render.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# See bottom of file for license and copyright information
package Foswiki::Render;
=begin TML
---+ package Foswiki::Render
This module provides most of the actual HTML rendering code in Foswiki.
=cut
use strict;
use warnings;
use Assert;
use Error qw(:try);
use Foswiki::Time ();
use Foswiki::Sandbox ();
use Foswiki::Render::Anchors ();
# Counter used to generate unique placeholders for when we lift blocks
# (such as <verbatim> out of the text during rendering.
our $placeholderMarker = 0;
# Limiting lookbehind and lookahead for wikiwords and emphasis.
# use like \b
our $STARTWW = qr/^|(?<=[\s\(])/m;
our $ENDWW = qr/$|(?=[\s,.;:!?)])/m;
# Note: the following marker sequences are used in text to mark things that
# have been hoisted or need to be marked for further processing. The strings
# are carefully chosen so that they (1) are not normally present in written
# text and (2) they do not combine with other characters to form valid
# wide-byte characters. A subset of the 7-bit control characters is used
# (codepoint < 0x07). Warning: the RENDERZONE_MARKER in Foswiki.pm uses \3
# Marker used to indicate the start of a table
our $TABLEMARKER = "\0\1\2TABLE\2\1\0";
# Marker used to indicate table rows that are valid header/footer rows
our $TRMARK = "is\1all\1th";
# General purpose marker used to mark escapes inthe text; for example, we
# use it to mark hoisted blocks, such as verbatim blocks.
our $REMARKER = "\0";
# Default format for a link to a non-existant topic
use constant DEFAULT_NEWLINKFORMAT => <<'NLF';
<span class="foswikiNewLink">$text<a href="%SCRIPTURLPATH{"edit"}%/$web/$topic?topicparent=%WEB%.%TOPIC%" rel="nofollow" title="%MAKETEXT{"Create this topic"}%">?</a></span>
NLF
BEGIN {
# Do a dynamic 'use locale' for this module
if ( $Foswiki::cfg{UseLocale} ) {
require locale;
import locale();
}
}
=begin TML
---++ ClassMethod new ($session)
Creates a new renderer
=cut
sub new {
my ( $class, $session ) = @_;
my $this = bless( { session => $session }, $class );
return $this;
}
=begin TML
---++ ObjectMethod finish()
Break circular references.
=cut
# Note to developers; please undef *all* fields in the object explicitly,
# whether they are references or not. That way this method is "golden
# documentation" of the live fields in the object.
sub finish {
my $this = shift;
undef $this->{NEWLINKFORMAT};
undef $this->{LINKTOOLTIPINFO};
undef $this->{LIST};
undef $this->{ffCache};
undef $this->{session};
}
sub _newLinkFormat {
my $this = shift;
unless ( $this->{NEWLINKFORMAT} ) {
$this->{NEWLINKFORMAT} =
$this->{session}->{prefs}->getPreference('NEWLINKFORMAT')
|| DEFAULT_NEWLINKFORMAT;
}
return $this->{NEWLINKFORMAT};
}
=begin TML
---++ ObjectMethod renderParent($topicObject, $params) -> $text
Render parent meta-data
=cut
sub renderParent {
my ( $this, $topicObject, $ah ) = @_;
my $dontRecurse = $ah->{dontrecurse} || 0;
my $depth = $ah->{depth} || 0;
my $noWebHome = $ah->{nowebhome} || 0;
my $prefix = $ah->{prefix} || '';
my $suffix = $ah->{suffix} || '';
my $usesep = $ah->{separator} || ' > ';
my $format = $ah->{format} || '[[$web.$topic][$topic]]';
my ( $web, $topic ) = ( $topicObject->web, $topicObject->topic );
return '' unless $web && $topic;
my %visited;
$visited{ $web . '.' . $topic } = 1;
my $pWeb = $web;
my $pTopic;
my $text = '';
my $parentMeta = $topicObject->get('TOPICPARENT');
my $parent;
$parent = $parentMeta->{name} if $parentMeta;
my @stack;
my $currentDepth = 0;
$depth = 1 if $dontRecurse;
while ($parent) {
$currentDepth++;
( $pWeb, $pTopic ) =
$this->{session}->normalizeWebTopicName( $pWeb, $parent );
$parent = $pWeb . '.' . $pTopic;
last
if ( $noWebHome && ( $pTopic eq $Foswiki::cfg{HomeTopicName} )
|| $visited{$parent} );
$visited{$parent} = 1;
$text = $format;
$text =~ s/\$web/$pWeb/g;
$text =~ s/\$topic/$pTopic/g;
if ( !$depth or $currentDepth == $depth ) {
unshift( @stack, $text );
}
last if $currentDepth == $depth;
# Compromise; rather than supporting a hack in the store to support
# rapid access to parent meta (as in TWiki) accept the hit
# of reading the whole topic.
my $topicObject =
Foswiki::Meta->load( $this->{session}, $pWeb, $pTopic );
my $parentMeta = $topicObject->get('TOPICPARENT');
$parent = $parentMeta->{name} if $parentMeta;
}
$text = join( $usesep, @stack );
if ($text) {
$text = $prefix . $text if ($prefix);
$text .= $suffix if ($suffix);
}
return $text;
}
=begin TML
---++ ObjectMethod renderMoved($topicObject, $params) -> $text
Render moved meta-data
=cut
sub renderMoved {
my ( $this, $topicObject, $params ) = @_;
my $text = '';
my $moved = $topicObject->get('TOPICMOVED');
if ($moved) {
my ( $fromWeb, $fromTopic ) =
$this->{session}
->normalizeWebTopicName( $topicObject->web, $moved->{from} );
my ( $toWeb, $toTopic ) =
$this->{session}
->normalizeWebTopicName( $topicObject->web, $moved->{to} );
my $by = $moved->{by};
my $u = $by;
my $users = $this->{session}->{users};
$by = $users->webDotWikiName($u) if $u;
my $date = Foswiki::Time::formatTime( $moved->{date}, '', 'gmtime' );
# Only allow put back if current web and topic match
# stored information
my $putBack = '';
if ( $topicObject->web eq $toWeb && $topicObject->topic eq $toTopic ) {
$putBack = ' - '
. CGI::a(
{
title => (
$this->{session}->i18n->maketext(
'Click to move topic back to previous location, with option to change references.'
)
),
href => $this->{session}->getScriptUrl(
0, 'rename', $topicObject->web, $topicObject->topic,
newweb => $fromWeb,
newtopic => $fromTopic,
confirm => 'on',
nonwikiword => 'checked'
),
rel => 'nofollow'
},
$this->{session}->i18n->maketext('put it back')
);
}
$text = CGI::i(
{},
$this->{session}->i18n->maketext(
"[_1] moved from [_2] on [_3] by [_4]",
"<nop>$toWeb.<nop>$toTopic", "<nop>$fromWeb.<nop>$fromTopic",
$date, $by
)
) . $putBack;
}
return $text;
}
# Add a list item, of the given type and indent depth. The list item may
# cause the opening or closing of lists currently being handled.
sub _addListItem {
my ( $this, $result, $type, $element, $indent ) = @_;
$indent =~ s/ /\t/g;
my $depth = length($indent);
my $size = scalar( @{ $this->{LIST} } );
# The whitespaces either side of the tags are required for the
# emphasis REs to work.
if ( $size < $depth ) {
my $firstTime = 1;
while ( $size < $depth ) {
push( @{ $this->{LIST} }, { type => $type, element => $element } );
push @$result, ' <' . $element . ">\n" unless ($firstTime);
push @$result, ' <' . $type . ">\n";
$firstTime = 0;
$size++;
}
}
else {
while ( $size > $depth ) {
my $tags = pop( @{ $this->{LIST} } );
push @$result,
"\n</" . $tags->{element} . '></' . $tags->{type} . '> ';
$size--;
}
if ($size) {
push @$result,
"\n</" . $this->{LIST}->[ $size - 1 ]->{element} . '> ';
}
else {
push @$result, "\n";
}
}
if ($size) {
my $oldt = $this->{LIST}->[ $size - 1 ];
if ( $oldt->{type} ne $type ) {
push @$result, ' </' . $oldt->{type} . '><' . $type . ">\n";
pop( @{ $this->{LIST} } );
push( @{ $this->{LIST} }, { type => $type, element => $element } );
}
}
}
# Given that we have just seen the end of a table, work out the thead,
# tbody and tfoot sections
sub _addTHEADandTFOOT {
my ($lines) = @_;
# scan back to the head of the table
my $i = scalar(@$lines) - 1;
my @thRows;
my $inFoot = 1;
my $footLines = 0;
my $headLines = 0;
while ( $i >= 0 && $lines->[$i] ne $TABLEMARKER ) {
if ( $lines->[$i] =~ /^\s*$/ ) {
# Remove blank lines in tables; they generate spurious <p>'s
splice( @$lines, $i, 1 );
}
elsif ( $lines->[$i] =~ s/$TRMARK=(["'])(.*?)\1//i ) {
if ($2) {
if ($inFoot) {
$footLines++;
}
else {
$headLines++;
}
}
else {
$inFoot = 0;
$headLines = 0;
}
}
$i--;
}
$lines->[$i] = CGI::start_table(
{
class => 'foswikiTable',
border => 1,
cellspacing => 0,
cellpadding => 0
}
);
if ( $footLines && !$headLines ) {
$headLines = $footLines;
$footLines = 0;
}
if ($footLines) {
push( @$lines, '</tfoot>' );
my $firstFoot = scalar(@$lines) - $footLines;
splice( @$lines, $firstFoot, 0, '</tbody><tfoot>' );
}
else {
push( @$lines, '</tbody>' );
}
if ($headLines) {
splice( @$lines, $i + 1 + $headLines, 0, '</thead><tbody>' );
splice( @$lines, $i + 1, 0, '<thead>' );
}
else {
splice( @$lines, $i + 1, 0, '<tbody>' );
}
}
sub _emitTR {
my ( $this, $row ) = @_;
$row =~ s/\t/ /g; # change tabs to space
$row =~ s/\s*$//; # remove trailing spaces
# calc COLSPAN
$row =~ s/(\|\|+)/
'colspan'.$REMARKER.length($1).'|'/ge;
my $cells = '';
my $containsTableHeader;
my $isAllTH = 1;
foreach ( split( /\|/, $row ) ) {
my %attr;
# Avoid matching single columns
if (s/colspan$REMARKER([0-9]+)//o) {
$attr{colspan} = $1;
}
s/^\s+$/ /;
my ( $l1, $l2 ) = ( 0, 0 );
if (/^(\s*).*?(\s*)$/) {
$l1 = length($1);
$l2 = length($2);
}
if ( $l1 >= 2 ) {
if ( $l2 <= 1 ) {
$attr{align} = 'right';
}
else {
$attr{align} = 'center';
}
}
# implicit untaint is OK, because we are just taking topic data
# and rendering it; no security step is bypassed.
if (/^\s*\*(.*)\*\s*$/) {
$cells .= CGI::th( \%attr, CGI::strong( {}, " $1 " ) ) . "\n";
}
else {
$cells .= CGI::td( \%attr, " $_ " ) . "\n";
$isAllTH = 0;
}
}
return CGI::Tr( { $TRMARK => $isAllTH }, $cells );
}
sub _fixedFontText {
my ( $text, $embolden ) = @_;
# preserve white space, so replace it by ' ' patterns
$text =~ s/\t/ /g;
$text =~ s|((?:[\s]{2})+)([^\s])|' ' x (length($1) / 2) . $2|eg;
$text = CGI->b($text) if $embolden;
return CGI->code($text);
}
# Build an HTML <Hn> element with suitable anchor for linking
# from %<nop>TOC%
sub _makeAnchorHeading {
my ( $this, $text, $level, $anchors ) = @_;
# - Build '<nop><h1><a name='atext'></a> heading </h1>' markup
# - Initial '<nop>' is needed to prevent subsequent matches.
# filter '!!', '%NOTOC%'
$text =~ s/$Foswiki::regex{headerPatternNoTOC}//o;
my $html =
'<nop><h'
. $level . '>'
. $anchors->makeHTMLTarget($text) . ' '
. $text . ' </h'
. $level . '>';
return $html;
}
# Returns =title='...'= tooltip info if the LINKTOOLTIPINFO preference
# is set. Warning: Slower performance if enabled.
sub _linkToolTipInfo {
my ( $this, $web, $topic ) = @_;
unless ( defined( $this->{LINKTOOLTIPINFO} ) ) {
$this->{LINKTOOLTIPINFO} =
$this->{session}->{prefs}->getPreference('LINKTOOLTIPINFO')
|| '';
$this->{LINKTOOLTIPINFO} = '$username - $date - r$rev: $summary'
if ( 'on' eq lc( $this->{LINKTOOLTIPINFO} ) );
}
return '' unless ( $this->{LINKTOOLTIPINFO} );
return '' if ( $this->{LINKTOOLTIPINFO} =~ /^off$/i );
return '' unless ( $this->{session}->inContext('view') );
# These are safe to untaint blindly because this method is only
# called when a regex matches a valid wikiword
$web = Foswiki::Sandbox::untaintUnchecked($web);
$topic = Foswiki::Sandbox::untaintUnchecked($topic);
# FIXME: This is slow, it can be improved by caching topic rev
# info and summary
my $users = $this->{session}->{users};
my $topicObject = Foswiki::Meta->new( $this->{session}, $web, $topic );
my $info = $topicObject->getRevisionInfo();
my $tooltip = $this->{LINKTOOLTIPINFO};
$tooltip =~ s/\$web/<nop>$web/g;
$tooltip =~ s/\$topic/<nop>$topic/g;
$tooltip =~ s/\$rev/1.$info->{version}/g;
$tooltip =~ s/\$date/Foswiki::Time::formatTime( $info->{date} )/ge;
$tooltip =~ s/\$username/
$users->getLoginName($info->{author}) || $info->{author}/ge;
$tooltip =~ s/\$wikiname/
$users->getWikiName($info->{author}) || $info->{author}/ge;
$tooltip =~ s/\$wikiusername/
$users->webDotWikiName($info->{author}) || $info->{author}/ge;
if ( $tooltip =~ /\$summary/ ) {
my $summary;
if ( $topicObject->haveAccess('VIEW') ) {
$summary = $topicObject->text || '';
}
else {
$summary =
$this->{session}
->inlineAlert( 'alerts', 'access_denied', "$web.$topic" );
}
$summary = $topicObject->summariseText();
$summary =~
s/[\"\']//g; # remove quotes (not allowed in title attribute)
$tooltip =~ s/\$summary/$summary/g;
}
return $tooltip;
}
=begin TML
---++ ObjectMethod internalLink ( $web, $topic, $linkText, $anchor, $linkIfAbsent, $keepWebPrefix, $hasExplicitLinkLabel ) -> $html
Generate a link.
Note: Topic names may be spaced out. Spaced out names are converted
to <nop>WikWords, for example, "spaced topic name" points to "SpacedTopicName".
* =$web= - the web containing the topic
* =$topic= - the topic to be link
* =$linkText= - text to use for the link
* =$anchor= - the link anchor, if any
* =$linkIfAbsent= - boolean: false means suppress link for
non-existing pages
* =$keepWebPrefix= - boolean: true to keep web prefix (for
non existing Web.TOPIC)
* =$hasExplicitLinkLabel= - boolean: true if
[[link][explicit link label]]
Called from outside the package by Func::internalLink
Calls _renderWikiWord, which in turn will use Plurals.pm to match fold
plurals to equivalency with their singular form
SMELL: why is this available to Func?
=cut
sub internalLink {
my ( $this, $web, $topic, $linkText, $anchor, $linkIfAbsent, $keepWebPrefix,
$hasExplicitLinkLabel, $params )
= @_;
# SMELL - shouldn't it be callable by Foswiki::Func as well?
#PN: Webname/Subweb/ -> Webname/Subweb
$web =~ s/\/\Z//o;
if ( $linkText eq $web ) {
$linkText =~ s/\//\./go;
}
#WebHome links to tother webs render as the WebName
if ( ( $linkText eq $Foswiki::cfg{HomeTopicName} )
&& ( $web ne $this->{session}->{webName} ) )
{
$linkText = $web;
}
# Get rid of leading/trailing spaces in topic name
$topic =~ s/^\s*//o;
$topic =~ s/\s*$//o;
# Allow spacing out, etc.
# Plugin authors use $hasExplicitLinkLabel to determine if the link label
# should be rendered differently even if the topic author has used a
# specific link label.
$linkText =
$this->{session}->{plugins}
->dispatch( 'renderWikiWordHandler', $linkText, $hasExplicitLinkLabel,
$web, $topic )
|| $linkText;
# Turn spaced-out names into WikiWords - upper case first letter of
# whole link, and first of each word. TODO: Try to turn this off,
# avoiding spaces being stripped elsewhere
$topic = ucfirst($topic);
$topic =~ s/\s([$Foswiki::regex{mixedAlphaNum}])/\U$1/go;
# If locales are in effect, the above conversions will taint the topic
# name (Foswiki:Tasks:Item2091)
$topic = Foswiki::Sandbox::untaintUnchecked($topic);
# Add <nop> before WikiWord inside link text to prevent double links
$linkText =~ s/(?<=[\s\(])([$Foswiki::regex{upperAlpha}])/<nop>$1/go;
return _renderWikiWord( $this, $web, $topic, $linkText, $anchor,
$linkIfAbsent, $keepWebPrefix, $params );
}
# TODO: this should be overridable by plugins.
sub _renderWikiWord {
my ( $this, $web, $topic, $linkText, $anchor, $linkIfAbsent, $keepWebPrefix,
$params )
= @_;
my $session = $this->{session};
my $topicExists = $session->topicExists( $web, $topic );
my $singular = '';
unless ($topicExists) {
# topic not found - try to singularise
require Foswiki::Plurals;
$singular = Foswiki::Plurals::singularForm( $web, $topic );
if ($singular) {
$topicExists = $session->topicExists( $web, $singular );
$topic = $singular if $topicExists;
}
}
if ($topicExists) {
# add a dependency so that the page gets invalidated as soon as the
# topic is deleted
$this->{session}->{cache}->addDependency( $web, $topic )
if $Foswiki::cfg{Cache}{Enabled};
return _renderExistingWikiWord( $this, $web, $topic, $linkText, $anchor,
$params );
}
if ($linkIfAbsent) {
# CDot: disabled until SuggestSingularNotPlural is resolved
# if ($singular && $singular ne $topic) {
# #unshift( @topics, $singular);
# }
# add a dependency so that the page gets invalidated as soon as the
# WikiWord comes into existance
# Note we *ignore* the params if the target topic does not exist
$this->{session}->{cache}->addDependency( $web, $topic )
if $Foswiki::cfg{Cache}{Enabled};
return _renderNonExistingWikiWord( $this, $web, $topic, $linkText );
}
if ($keepWebPrefix) {
return $web . '.' . $linkText;
}
return $linkText;
}
sub _renderExistingWikiWord {
my ( $this, $web, $topic, $text, $anchor, $params ) = @_;
my @cssClasses;
push( @cssClasses, 'foswikiCurrentWebHomeLink' )
if ( ( $web eq $this->{session}->{webName} )
&& ( $topic eq $Foswiki::cfg{HomeTopicName} ) );
my $inCurrentTopic = 0;
if ( ( $web eq $this->{session}->{webName} )
&& ( $topic eq $this->{session}->{topicName} ) )
{
push( @cssClasses, 'foswikiCurrentTopicLink' );
$inCurrentTopic = 1;
}
my %attrs;
my $href = $this->{session}->getScriptUrl( 0, 'view', $web, $topic );
if ($params) {
$href .= $params;
}
if ($anchor) {
$anchor = Foswiki::Render::Anchors::make($anchor);
$anchor = Foswiki::urlEncode($anchor);
# No point in trying to make it unique; just aim at the first
# occurrence
# Item8556 - drop path if same topic
$href = $inCurrentTopic ? "#$anchor" : "$href#$anchor";
}
$attrs{class} = join( ' ', @cssClasses ) if ( $#cssClasses >= 0 );
$attrs{href} = $href;
my $tooltip = _linkToolTipInfo( $this, $web, $topic );
$attrs{title} = $tooltip if $tooltip;
my $link = CGI::a( \%attrs, $text );
# When we pass the tooltip text to CGI::a it may contain
# <nop>s, and CGI::a will convert the < to <. This is a
# basic problem with <nop>.
$link =~ s/<nop>/<nop>/g;
return $link;
}
sub _renderNonExistingWikiWord {
my ( $this, $web, $topic, $text ) = @_;
my $ans = $this->_newLinkFormat;
$ans =~ s/\$web/$web/g;
$ans =~ s/\$topic/$topic/g;
$ans =~ s/\$text/$text/g;
my $topicObject = Foswiki::Meta->new(
$this->{session},
$this->{session}->{webName},
$this->{session}->{topicName}
);
return $topicObject->expandMacros($ans);
}
# _handleWikiWord is called for a wiki word that needs linking.
# Handle the various link constructions. e.g.:
# WikiWord
# Web.WikiWord
# Web.WikiWord#anchor
#
# This routine adds missing parameters before passing off to internallink
sub _handleWikiWord {
my ( $this, $topicObject, $web, $topic, $anchor ) = @_;
my $linkIfAbsent = 1;
my $keepWeb = 0;
my $text;
# For some strange reason, $web doesn't get untainted by the regex
# that invokes this function. We can untaint it safely, because it's
# validated by the RE.
$web = Foswiki::Sandbox::untaintUnchecked($web);
$web = $topicObject->web() unless ( defined($web) );
if ( defined($anchor) ) {
ASSERT( ( $anchor =~ m/\#.*/ ) ) if DEBUG; # must include a hash.
}
else {
$anchor = '';
}
if ( defined($anchor) ) {
# 'Web.TopicName#anchor' or 'Web.ABBREV#anchor' link
$text = $topic . $anchor;
}
else {
$anchor = '';
# 'Web.TopicName' or 'Web.ABBREV' link:
if ( $topic eq $Foswiki::cfg{HomeTopicName}
&& $web ne $this->{session}->{webName} )
{
$text = $web;
}
else {
$text = $topic;
}
}
# true to keep web prefix for non-existing Web.TOPIC
# Have to leave "web part" of ABR.ABR.ABR intact if topic not found
$keepWeb =
( $topic =~ /^$Foswiki::regex{abbrevRegex}$/o
&& $web ne $this->{session}->{webName} );
# false means suppress link for non-existing pages
$linkIfAbsent = ( $topic !~ /^$Foswiki::regex{abbrevRegex}$/o );
return $this->internalLink( $web, $topic, $text, $anchor, $linkIfAbsent,
$keepWeb, undef );
}
# Protect WikiWords, TLAs and URLs from further rendering with <nop>
sub _escapeAutoLinks {
my $text = shift;
if ($text) {
# WikiWords, TLAs, and email addresses
$text =~ s/(?<=[\s\(])
(
(?:
(?:($Foswiki::regex{webNameRegex})\.)?
(?: $Foswiki::regex{wikiWordRegex}
| $Foswiki::regex{abbrevRegex} )
)
| $Foswiki::regex{emailAddrRegex}
)/<nop>$1/gox;
# Explicit links
$text =~ s/($Foswiki::regex{linkProtocolPattern}):(?=\S)/$1<nop>:/go;
}
return $text;
}
# Handle SquareBracketed links mentioned on page $web.$topic
# format: [[$link]]
# format: [[$link][$text]]
sub _handleSquareBracketedLink {
my ( $this, $topicObject, $link, $text ) = @_;
# Strip leading/trailing spaces
$link =~ s/^\s+//;
$link =~ s/\s+$//;
my $hasExplicitLinkLabel = 0;
if ( defined($text) ) {
# [[$link][$text]]
$hasExplicitLinkLabel = 1;
$text = _escapeAutoLinks($text);
}
if ( $link =~ m#^($Foswiki::regex{linkProtocolPattern}:|/)# ) {
# Explicit external [[http://$link]] or [[http://$link][$text]]
# or explicit absolute [[/$link]] or [[/$link][$text]]
if ( !defined($text) && $link =~ /^(\S+)\s+(.*)$/ ) {
# Legacy case of '[[URL anchor display text]]' link
# implicit untaint is OK as we are just recycling topic content
$link = $1;
$text = _escapeAutoLinks($2);
}
return _externalLink( $this, $link, $text );
}
# Extract '?params'
# $link =~ s/(\?.*?)(?>#|$)//;
my $params = '';
if ( $link =~ s/(\?.*$)// ) {
$params = $1;
}
$text = _escapeAutoLinks($link) unless defined $text;
# Extract '#anchor'
# $link =~ s/(\#[a-zA-Z_0-9\-]*$)//;
my $anchor = '';
if ( $link =~ s/($Foswiki::regex{anchorRegex}$)// ) {
$anchor = $1;
#$text =~ s/#$anchor//;
}
# filter out &any; entities (legacy)
$link =~ s/\&[a-z]+\;//gi;
# filter out { entities (legacy)
$link =~ s/\&\#[0-9]+\;//g;
# Filter junk
$link =~ s/$Foswiki::cfg{NameFilter}+/ /g;
ASSERT( UNTAINTED($link) ) if DEBUG;
# Capitalise first word
$link = ucfirst($link);
# Collapse spaces and capitalise following letter
$link =~ s/\s([$Foswiki::regex{mixedAlphaNum}])/\U$1/go;
# Get rid of remaining spaces, i.e. spaces in front of -'s and ('s
$link =~ s/\s//go;
# The link is used in the topic name, and if locales are in effect,
# the above conversions will taint the name (Foswiki:Tasks:Item2091)
$link = Foswiki::Sandbox::untaintUnchecked($link);
$link ||= $topicObject->topic;
# Topic defaults to the current topic
my ( $web, $topic ) =
$this->{session}->normalizeWebTopicName( $topicObject->web, $link );
return $this->internalLink( $web, $topic, $text, $anchor, 1, undef,
$hasExplicitLinkLabel, $params );
}
# Handle an external link typed directly into text. If it's an image
# (as indicated by the file type), and no text is specified, then use
# an img tag, otherwise generate a link.
sub _externalLink {
my ( $this, $url, $text ) = @_;
if ( $url =~ /^[^?]*\.(gif|jpg|jpeg|png)$/i && !$text ) {
my $filename = $url;
$filename =~ s@.*/([^/]*)@$1@go;
return CGI::img( { src => $url, alt => $filename } );
}
my $opt = '';
if ( $url =~ /^mailto:/i ) {
if ( $Foswiki::cfg{AntiSpam}{EmailPadding} ) {
$url =~ s/(\@[\w\_\-\+]+)(\.)
/$1$Foswiki::cfg{AntiSpam}{EmailPadding}$2/x;
if ($text) {
$text =~ s/(\@[\w\_\-\+]+)(\.)
/$1$Foswiki::cfg{AntiSpam}{EmailPadding}$2/x;
}
}
if ( $Foswiki::cfg{AntiSpam}{HideUserDetails} ) {
# Much harder obfuscation scheme. For link text we only encode '@'
# See also http://develop.twiki.org/~twiki4/cgi-bin/view/Bugs/Item2928
# and http://develop.twiki.org/~twiki4/cgi-bin/view/Bugs/Item3430
# before touching this
$url =~ s/(\W)/'&#'.ord($1).';'/ge;
if ($text) {
$text =~ s/\@/'&#'.ord('@').';'/ge;
}
}
}
else {
$opt = ' target="_top"';
}
$text ||= $url;
# Item5787: if a URL has spaces, escape them so the URL has less
# chance of being broken by later rendering.
$url =~ s/ /%20/g;
# SMELL: Can't use CGI::a here, because it encodes ampersands in
# the link, and those have already been encoded once in the
# rendering loop (they are identified as "stand-alone"). One
# encoding works; two is too many. None would be better for everyone!
return '<a href="' . $url . '"' . $opt . '>' . $text . '</a>';
}
# Generate a "mailTo" link
sub _mailLink {
my ( $this, $text ) = @_;
my $url = $text;
$url = 'mailto:' . $url unless $url =~ /^mailto:/i;
return _externalLink( $this, $url, $text );
}
=begin TML
---++ ObjectMethod renderFORMFIELD ( %params, $topic, $web ) -> $html
Returns the fully rendered expansion of a %FORMFIELD{}% tag.
=cut
sub renderFORMFIELD {
my ( $this, $params, $topicObject ) = @_;
my $formField = $params->{_DEFAULT};
return '' unless defined $formField;
my $altText = $params->{alttext};
my $default = $params->{default};
my $rev = $params->{rev} || '';
my $format = $params->{format};
unless ( defined $format ) {
$format = '$value';
}
# SMELL: this local creation of a cache looks very suspicious. Suspect
# this may have been a one-off optimisation.
my $formTopicObject = $this->{ffCache}{ $topicObject->getPath() . $rev };
unless ($formTopicObject) {
$formTopicObject =
Foswiki::Meta->load( $this->{session}, $topicObject->web,
$topicObject->topic, $rev );
unless ( $formTopicObject->haveAccess('VIEW') ) {
# Access violation, create dummy meta with empty text, so
# it looks like it was already loaded.
$formTopicObject =
Foswiki::Meta->new( $this->{session}, $topicObject->web,
$topicObject->topic, '' );
}
$this->{ffCache}{ $formTopicObject->getPath() . $rev } =
$formTopicObject;
}
my $text = $format;
my $found = 0;
my $title = '';
my @fields = $formTopicObject->find('FIELD');
foreach my $field (@fields) {
my $name = $field->{name};
$title = $field->{title} || $name;
if ( $title eq $formField || $name eq $formField ) {
$found = 1;
$text =~ s/\$title/$title/go;
my $value = $field->{value};
if ( !length($value) ) {
$value = defined($default) ? $default : '';
}
$text =~ s/\$value/$value/go;
$text =~ s/\$name/$name/g;
if ( $text =~ m/\$form/ ) {
my @defform = $formTopicObject->find('FORM');
my $form = $defform[0]; # only one form per topic
my $fname = $form->{name};
$text =~ s/\$form/$fname/g;
}
last; # one hit suffices
}
}
unless ($found) {
$text = $altText || '';
}
$text = Foswiki::expandStandardEscapes($text);
# render nop exclamation marks before words as <nop>
$text =~ s/!(\w+)/<nop>$1/gs;
return $text;
}
=begin TML
---++ ObjectMethod getRenderedVersion ( $text, $topicObject ) -> $html
The main rendering function.
=cut
sub getRenderedVersion {
my ( $this, $text, $topicObject ) = @_;
ASSERT( $topicObject->isa('Foswiki::Meta') ) if DEBUG;
return '' unless $text; # nothing to do
my $session = $this->{session};
my $plugins = $session->{plugins};
my $prefs = $session->{prefs};
@{ $this->{LIST} } = ();