/
Foswiki.pm
3950 lines (3084 loc) · 124 KB
/
Foswiki.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
package Foswiki;
=begin TML
---+ package Foswiki
Foswiki operates by creating a singleton object (known as the Session
object) that acts as a point of reference for all the different
modules in the system. This package is the class for this singleton,
and also contains the vast bulk of the basic constants and the per-
site configuration mechanisms.
Global variables are avoided wherever possible to avoid problems
with CGI accelerators such as mod_perl.
---++ Public Data members
* =request= Pointer to the Foswiki::Request
* =response= Pointer to the Foswiki::Response
* =context= Hash of context ids
* =plugins= Foswiki::Plugins singleton
* =prefs= Foswiki::Prefs singleton
* =remoteUser= Login ID when using ApacheLogin. Maintained for
compatibility only, do not use.
* =requestedWebName= Name of web found in URL path or =web= URL parameter
* =scriptUrlPath= URL path to the current script. May be dynamically
extracted from the URL path if {GetScriptUrlFromCgi}.
Only required to support {GetScriptUrlFromCgi} and
not consistently used. Avoid.
* =access= Foswiki::Access singleton
* =store= Foswiki::Store singleton
* =topicName= Name of topic found in URL path or =topic= URL
parameter
* =urlHost= Host part of the URL (including the protocol)
determined during intialisation and defaulting to
{DefaultUrlHost}
* =user= Unique user ID of logged-in user
* =users= Foswiki::Users singleton
* =webName= Name of web found in URL path, or =web= URL parameter,
or {UsersWebName}
=cut
use strict;
use warnings;
use Assert;
use Cwd qw( abs_path );
use Error qw( :try );
use File::Spec ();
use Monitor ();
use CGI (); # Always required to get html generation tags;
use Digest::MD5 (); # For passthru and validation
use Foswiki::Configure::Load ();
use 5.006; # First version to accept v-numbers.
# Item13331 - use CGI::ENCODE_ENTITIES introduced in CGI>=4.14 to restrict encoding
# in CGI's html rendering code to only these; note that CGI's default values
# still breaks some unicode byte strings
$CGI::ENCODE_ENTITIES = q{&<>"'};
#SMELL: Perl 5.10.0 on Mac OSX Snow Leopard warns "v-string in use/require non-portable"
require 5.008_008; # see http://foswiki.org/Development/RequirePerl588
# Site configuration constants
our %cfg;
# Other computed constants
our $foswikiLibDir;
our %regex;
our %macros;
our %contextFreeSyntax;
our $VERSION;
our $RELEASE;
our $UNICODE = 1; # flag that extensions can use to test if the core is unicode
our $TRUE = 1;
our $FALSE = 0;
our $engine;
our $TranslationToken = "\0"; # Do not deprecate - used in many plugins
our $system_message; # Important broadcast message from the system
my $bootstrap_message = ''; # Bootstrap message.
# Note: the following marker is used in text to mark RENDERZONE
# macros that have been hoisted from the source text of a page. It is
# carefully chosen so that it is (1) not normally present in written
# text (2) does not combine with other characters to form valid
# wide-byte characters and (3) does not conflict with other markers used
# by Foswiki/Render.pm
our $RENDERZONE_MARKER = "\3";
# Used by takeOut/putBack blocks
our $BLOCKID = 0;
our $OC = "<!--\0";
our $CC = "\0-->";
# This variable is set if Foswiki is running in unit test mode.
# It is provided so that modules can detect unit test mode to avoid
# corrupting data spaces.
our $inUnitTestMode = 0;
sub SINGLE_SINGLETONS { 0 }
sub SINGLE_SINGLETONS_TRACE { 0 }
# Returns the full path of the directory containing Foswiki.pm
sub _getLibDir {
return $foswikiLibDir if $foswikiLibDir;
$foswikiLibDir = $INC{'Foswiki.pm'};
# fix path relative to location of called script
if ( $foswikiLibDir =~ m/^\./ ) {
print STDERR
"WARNING: Foswiki lib path $foswikiLibDir is relative; you should make it absolute, otherwise some scripts may not run from the command line.";
my $bin;
# SMELL : Should not assume environment variables; get data from request
if ( $ENV{SCRIPT_FILENAME}
&& $ENV{SCRIPT_FILENAME} =~ m#^(.+)/.+?$# )
{
# CGI script name
# implicit untaint OK, because of use of $SCRIPT_FILENAME
$bin = $1;
}
elsif ( $0 =~ m#^(.*)/.*?$# ) {
# program name
# implicit untaint OK, because of use of $PROGRAM_NAME ($0)
$bin = $1;
}
else {
# last ditch; relative to current directory.
require Cwd;
$bin = Cwd::cwd();
}
$foswikiLibDir = "$bin/$foswikiLibDir/";
# normalize "/../" and "/./"
while ( $foswikiLibDir =~ s|([\\/])[^\\/]+[\\/]\.\.[\\/]|$1| ) {
}
$foswikiLibDir =~ s|([\\/])\.[\\/]|$1|g;
}
$foswikiLibDir =~ s|([\\/])[\\/]*|$1|g; # reduce "//" to "/"
$foswikiLibDir =~ s|[\\/]$||; # cut trailing "/"
return $foswikiLibDir;
}
# Character encoding/decoding stubs. Done so we can ovveride
# if necessary (e.g. on OSX we may want to monkey-patch in a
# NFC/NFD module)
#
# Note, NFC normalization is being done only for network and directory
# read operations, but NOT for topic data. Adding normalization here
# caused performance issues because some versions of Unicode::Normalize
# have removed the XS versions. We really only need to normalize directory
# names not file contents.
=begin TML
---++ StaticMethod decode_utf8($octets) -> $unicode
Decode a binary string of octets known to be encoded using UTF-8 into
perl characters (unicode).
=cut
*decode_utf8 = \&Encode::decode_utf8;
=begin TML
---++ StaticMethod encode_utf8($unicode) -> $octets
Encode a perl character string into a binary string of octets
encoded using UTF-8.
=cut
*encode_utf8 = \&Encode::encode_utf8;
BEGIN {
# First thing we do; make sure we print unicode errors
binmode( STDERR, ":utf8" );
#Monitor::MARK("Start of BEGIN block in Foswiki.pm");
if (DEBUG) {
if ( not $Assert::soft ) {
# If ASSERTs are on (and not soft), then warnings are errors.
# Paranoid, but the only way to be sure we eliminate them all.
# ASSERTS are turned on by defining the environment variable
# FOSWIKI_ASSERTS. If ASSERTs are off, this is assumed to be a
# production environment, and no stack traces or paths are
# output to the browser.
$SIG{'__WARN__'} = sub { die @_ };
$Error::Debug = 1; # verbose stack traces, please
}
else {
# ASSERTs are soft, so warnings are not errors
# but ASSERTs are enabled. This is useful for tracking down
# problems that only manifest on production servers.
$Error::Debug = 0; # no verbose stack traces
}
}
else {
$Error::Debug = 0; # no verbose stack traces
}
# DO NOT CHANGE THE FORMAT OF $VERSION.
# Use $RELEASE for a descriptive version.
use version 0.77; $VERSION = version->declare('v2.1.2_001');
$RELEASE = 'Foswiki-2.1.3-Beta1';
# Default handlers for different %TAGS%
# Where an entry is set as 'undef', the tag will be demand-loaded
# from Foswiki::Macros, if it is used. This tactic is used to reduce
# the load time of this module, especially when it is used from
# REST handlers.
%macros = (
ADDTOHEAD => undef,
# deprecated, use ADDTOZONE instead
ADDTOZONE => undef,
ALLVARIABLES => sub { $_[0]->{prefs}->stringify() },
ATTACHURL => undef,
ATTACHURLPATH => undef,
DATE => sub {
Foswiki::Time::formatTime(
time(),
$Foswiki::cfg{DefaultDateFormat},
$Foswiki::cfg{DisplayTimeValues}
);
},
DISPLAYTIME => sub {
Foswiki::Time::formatTime(
time(),
$_[1]->{_DEFAULT} || '',
$Foswiki::cfg{DisplayTimeValues}
);
},
ENCODE => undef,
ENV => undef,
EXPAND => undef,
FORMAT => undef,
FORMFIELD => undef,
FOSWIKI_BROADCAST => sub { $Foswiki::system_message || '' },
GMTIME => sub {
Foswiki::Time::formatTime( time(), $_[1]->{_DEFAULT} || '',
'gmtime' );
},
GROUPINFO => undef,
GROUPS => undef,
HTTP_HOST =>
#deprecated functionality, now implemented using %ENV%
sub { $_[0]->{request}->header('Host') || '' },
HTTP => undef,
HTTPS => undef,
ICON => undef,
ICONURL => undef,
ICONURLPATH => undef,
IF => undef,
INCLUDE => undef,
INTURLENCODE => undef,
LANGUAGE => sub { $_[0]->i18n->language(); },
LANGUAGES => undef,
MAKETEXT => undef,
META => undef, # deprecated
METASEARCH => undef, # deprecated
NONCE => undef,
PENDINGREGISTRATIONS => undef,
PERLDEPENDENCYREPORT => undef,
NOP =>
# Remove NOP tag in template topics but show content.
# Used in template _topics_ (not templates, per se, but
# topics used as templates for new topics)
sub { $_[1]->{_RAW} ? $_[1]->{_RAW} : '<nop>' },
PLUGINVERSION => sub {
$_[0]->{plugins}->getPluginVersion( $_[1]->{_DEFAULT} );
},
PUBURL => undef,
PUBURLPATH => undef,
QUERY => undef,
QUERYPARAMS => undef,
QUERYSTRING => sub {
my $s = $_[0]->{request}->queryString();
# Aggressively encode QUERYSTRING (even more than the
# default) because it might be leveraged for XSS
$s =~ s/(['\/])/'%'.sprintf('%02x', ord($1))/ge;
return $s;
},
RELATIVETOPICPATH => undef,
REMOTE_ADDR =>
# DEPRECATED, now implemented using %ENV%
#move to compatibility plugin in Foswiki 2.0
sub { $_[0]->{request}->remoteAddress() || ''; },
REMOTE_PORT =>
# DEPRECATED
# CGI/1.1 (RFC 3875) doesn't specify REMOTE_PORT,
# but some webservers implement it. However, since
# it's not RFC compliant, Foswiki should not rely on
# it. So we get more portability.
sub { '' },
REMOTE_USER =>
# DEPRECATED
sub { $_[0]->{request}->remoteUser() || '' },
RENDERZONE => undef,
REVINFO => undef,
REVTITLE => undef,
REVARG => undef,
SCRIPTNAME => sub { $_[0]->{request}->action() },
SCRIPTURL => undef,
SCRIPTURLPATH => undef,
SEARCH => undef,
SEP =>
# Shortcut to %TMPL:P{"sep"}%
sub { $_[0]->templates->expandTemplate('sep') },
SERVERTIME => sub {
Foswiki::Time::formatTime( time(), $_[1]->{_DEFAULT} || '',
'servertime' );
},
SERVERINFORMATION => undef,
SET => undef,
SHOWPREFERENCE => undef,
SPACEDTOPIC => undef,
SPACEOUT => undef,
'TMPL:P' => sub { $_[0]->templates->tmplP( $_[1] ) },
TOPICLIST => undef,
URLENCODE => undef,
URLPARAM => undef,
USERINFO => undef,
USERNAME => undef,
VAR => undef,
WEBLIST => undef,
WIKINAME => undef,
WIKIUSERNAME => undef,
DISPLAYDEPENDENCIES => undef,
# Constant tag strings _not_ dependent on config. These get nicely
# optimised by the compiler.
STOPSECTION => sub { '' },
ENDSECTION => sub { '' },
WIKIVERSION => sub { $VERSION },
WIKIRELEASE => sub { $RELEASE },
STARTSECTION => sub { '' },
STARTINCLUDE => sub { '' },
STOPINCLUDE => sub { '' },
ENDINCLUDE => sub { '' },
);
$contextFreeSyntax{IF} = 1;
# Load LocalSite.cfg
if ( Foswiki::Configure::Load::readConfig( 0, 0, 0 ) ) {
$Foswiki::cfg{isVALID} = 1;
}
else {
require Foswiki::Configure::Bootstrap;
$bootstrap_message = Foswiki::Configure::Bootstrap::bootstrapConfig();
eval 'require Foswiki::Plugins::ConfigurePlugin';
die
"LocalSite.cfg load failed, and ConfigurePlugin could not be loaded: $@"
if $@;
}
if ( $Foswiki::cfg{UseLocale} ) {
require locale;
import locale();
}
# Set environment var FOSWIKI_NOTAINT to disable taint checks even
# if Taint::Runtime is installed
elsif ( DEBUG && !$ENV{FOSWIKI_NOTAINT} ) {
eval { require Taint::Runtime; };
if ($@) {
print STDERR
"DEVELOPER WARNING: taint mode could not be enabled. Is Taint::Runtime installed?\n";
}
else {
# Enable taint checking
Taint::Runtime::_taint_start();
}
}
# If not set, default to strikeone validation
$Foswiki::cfg{Validation}{Method} ||= 'strikeone';
$Foswiki::cfg{Validation}{ValidForTime} = $Foswiki::cfg{LeaseLength}
unless defined $Foswiki::cfg{Validation}{ValidForTime};
$Foswiki::cfg{Validation}{MaxKeys} = 1000
unless defined $Foswiki::cfg{Validation}{MaxKeys};
# Constant tags dependent on the config
$macros{ALLOWLOGINNAME} =
sub { $Foswiki::cfg{Register}{AllowLoginName} || 0 };
$macros{AUTHREALM} = sub { $Foswiki::cfg{AuthRealm} };
$macros{DEFAULTURLHOST} = sub { $Foswiki::cfg{DefaultUrlHost} };
$macros{HOMETOPIC} = sub { $Foswiki::cfg{HomeTopicName} };
$macros{LOCALSITEPREFS} = sub { $Foswiki::cfg{LocalSitePreferences} };
$macros{NOFOLLOW} =
sub { $Foswiki::cfg{NoFollow} ? 'rel=' . $Foswiki::cfg{NoFollow} : '' };
$macros{NOTIFYTOPIC} = sub { $Foswiki::cfg{NotifyTopicName} };
$macros{SCRIPTSUFFIX} = sub { $Foswiki::cfg{ScriptSuffix} };
$macros{STATISTICSTOPIC} = sub { $Foswiki::cfg{Stats}{TopicName} };
$macros{SYSTEMWEB} = sub { $Foswiki::cfg{SystemWebName} };
$macros{TRASHWEB} = sub { $Foswiki::cfg{TrashWebName} };
$macros{SANDBOXWEB} = sub { $Foswiki::cfg{SandboxWebName} };
$macros{WIKIADMINLOGIN} = sub { $Foswiki::cfg{AdminUserLogin} };
$macros{USERSWEB} = sub { $Foswiki::cfg{UsersWebName} };
$macros{WEBPREFSTOPIC} = sub { $Foswiki::cfg{WebPrefsTopicName} };
$macros{WIKIPREFSTOPIC} = sub { $Foswiki::cfg{SitePrefsTopicName} };
$macros{WIKIUSERSTOPIC} = sub { $Foswiki::cfg{UsersTopicName} };
$macros{WIKIWEBMASTER} = sub { $Foswiki::cfg{WebMasterEmail} };
$macros{WIKIWEBMASTERNAME} = sub { $Foswiki::cfg{WebMasterName} };
$macros{WIKIAGENTEMAIL} = sub {
$Foswiki::cfg{Email}{WikiAgentEmail} || $Foswiki::cfg{WebMasterEmail};
};
$macros{WIKIAGENTNAME} = sub {
$Foswiki::cfg{Email}{WikiAgentName} || $Foswiki::cfg{WebMasterName};
};
# locale setup
#
#
# Note that 'use locale' must be done in BEGIN block for regexes and
# sorting to work properly, although regexes can still work without
# this in 'non-locale regexes' mode.
if ( $Foswiki::cfg{UseLocale} ) {
# Set environment variables for grep
$ENV{LC_CTYPE} = $Foswiki::cfg{Site}{Locale};
# Load POSIX for I18N support.
require POSIX;
import POSIX qw( locale_h LC_CTYPE LC_COLLATE );
# SMELL: mod_perl compatibility note: If Foswiki is running under Apache,
# won't this play with the Apache process's locale settings too?
# What effects would this have?
setlocale( &LC_CTYPE, $Foswiki::cfg{Site}{Locale} );
setlocale( &LC_COLLATE, $Foswiki::cfg{Site}{Locale} );
}
$macros{CHARSET} = sub {
'utf-8';
};
$macros{LANG} = sub {
my $lang = 'en'; # the default
if ( $Foswiki::cfg{UseLocale}
&& $Foswiki::cfg{Site}{Locale} =~ m/^([a-z]+)(?:_([a-z]+))?/i )
{
# Locale identifiers use _ as the separator in the language, but a minus sign is required
# for HTML (see http://www.ietf.org/rfc/rfc1766.txt)
$lang = $1 . ( $2 ? "-$2" : '' );
}
return $lang;
};
# Set up pre-compiled regexes for use in rendering.
# In the regex hash, all precompiled REs have "Regex" at the
# end of the name. Anything else is a string, either intended
# for use as a character class, or as a sub-expression in
# another compiled RE.
# Character class components for use in regexes.
# (Pre-UTF-8 compatibility; not used in core)
$regex{upperAlpha} = '[:upper:]';
$regex{lowerAlpha} = '[:lower:]';
$regex{numeric} = '[:digit:]';
$regex{mixedAlpha} = '[:alpha:]';
$regex{mixedAlphaNum} = '[:alnum:]';
$regex{lowerAlphaNum} = '[:lower:][:digit:]';
$regex{upperAlphaNum} = '[:upper:][:digit:]';
# Compile regexes for efficiency and ease of use
# Note: qr// locks in regex modes (i.e. '-xism' here) - see Friedl
# book at http://regex.info/.
$regex{linkProtocolPattern} = $Foswiki::cfg{LinkProtocolPattern}
|| '(file|ftp|gopher|https|http|irc|mailto|news|nntp|telnet)';
# Header patterns based on '+++'. The '###' are reserved for numbered
# headers
# '---++ Header', '---## Header'
$regex{headerPatternDa} = qr/^---+(\++|\#+)(.*)$/m;
# '<h6>Header</h6>
$regex{headerPatternHt} = qr/^<h([1-6])>(.+?)<\/h\1>/mi;
# '---++!! Header' or '---++ Header %NOTOC% ^top'
$regex{headerPatternNoTOC} = '(\!\!+|%NOTOC%)';
# Foswiki concept regexes
$regex{wikiWordRegex} = qr(
[[:upper:]]+
[[:lower:][:digit:]]+
[[:upper:]]+
[[:alnum:]]*
)xo;
$regex{webNameBaseRegex} = qr/[[:upper:]]+[[:alnum:]_]*/;
if ( $Foswiki::cfg{EnableHierarchicalWebs} ) {
$regex{webNameRegex} = qr(
$regex{webNameBaseRegex}
(?:(?:[\.\/]$regex{webNameBaseRegex})+)*
)xo;
}
else {
$regex{webNameRegex} = $regex{webNameBaseRegex};
}
$regex{defaultWebNameRegex} = qr/_[[:alnum:]_]+/;
$regex{anchorRegex} = qr/\#[[:alnum:]:._]+/;
my $abbrevLength = $Foswiki::cfg{AcronymLength} || 3;
$regex{abbrevRegex} = qr/[[:upper:]]{$abbrevLength,}s?\b/;
$regex{topicNameRegex} =
qr/(?:(?:$regex{wikiWordRegex})|(?:$regex{abbrevRegex}))/;
# Email regex, e.g. for WebNotify processing and email matching
# during rendering.
my $emailAtom = qr([A-Z0-9\Q!#\$%&'*+-/=?^_`{|}~\E])i; # Per RFC 5322 ]
# Valid TLD's at http://data.iana.org/TLD/tlds-alpha-by-domain.txt
# Version 2012022300, Last Updated Thu Feb 23 15:07:02 2012 UTC
my $validTLD = $Foswiki::cfg{Email}{ValidTLD};
unless ( eval { qr/$validTLD/ } ) {
$validTLD =
qr(AERO|ARPA|ASIA|BIZ|CAT|COM|COOP|EDU|GOV|INFO|INT|JOBS|MIL|MOBI|MUSEUM|NAME|NET|ORG|PRO|TEL|TRAVEL|XXX)i;
# Too early to log, should do something here other than die (which prevents fixing)
# warn is trapped and turned into a die...
#warn( "{Email}{ValidTLD} does not compile, using default" );
}
$regex{emailAddrRegex} = qr(
(?: # LEFT Side of Email address
(?:$emailAtom+ # Valid characters left side of email address
(?:\.$emailAtom+)* # And 0 or more dotted atoms
)
|
(?:"[\x21\x23-\x5B\x5D-\x7E\s]+?") # or a quoted string per RFC 5322
)
@
(?: # RIGHT side of Email address
(?: # FQDN
[a-z0-9-]+ # hostname part
(?:\.[a-z0-9-]+)* # 0 or more alphanumeric domains following a dot.
\.(?: # TLD
(?:[a-z]{2,2}) # 2 character TLD
|
$validTLD # TLD's longer than 2 characters
)
)
|
(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]) # dotted triplets IP Address
)
)oxi;
# Item11185: This is how things were before we began Operation Unicode:
#
# $regex{filenameInvalidCharRegex} = qr/[^[:alnum:]\. _-]/;
#
# It was only used in Foswiki::Sandbox::sanitizeAttachmentName(), which now
# uses $Foswiki::cfg{NameFilter} instead.
# See RobustnessTests::test_sanitizeAttachmentName
#
# Actually, this is used in GenPDFPrincePlugin; let's copy NameFilter
$regex{webTopicInvalidCharRegex} = qr/$Foswiki::cfg{NameFilter}/;
$regex{filenameInvalidCharRegex} = qr/$Foswiki::cfg{AttachmentNameFilter}/;
# Multi-character alpha-based regexes
$regex{mixedAlphaNumRegex} = qr/[[:alnum:]]*/;
# %TAG% name
$regex{tagNameRegex} = '[A-Za-z][A-Za-z0-9_:]*';
# Set statement in a topic
$regex{bulletRegex} = '^(?:\t| )+\*';
$regex{setRegex} = $regex{bulletRegex} . '\s+(Set|Local)\s+';
$regex{setVarRegex} =
$regex{setRegex} . '(' . $regex{tagNameRegex} . ')\s*=\s*(.*)$';
# Character encoding regexes
# Regex to match only a valid UTF-8 character, taking care to avoid
# security holes due to overlong encodings by excluding the relevant
# gaps in UTF-8 encoding space - see 'perldoc perlunicode', Unicode
# Encodings section. Tested against Markus Kuhn's UTF-8 test file
# at http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt.
$regex{validUtf8CharRegex} = qr{
# Single byte - ASCII
[\x00-\x7F]
|
# 2 bytes
[\xC2-\xDF][\x80-\xBF]
|
# 3 bytes
# Avoid illegal codepoints - negative lookahead
(?!\xEF\xBF[\xBE\xBF])
# Match valid codepoints
(?:
([\xE0][\xA0-\xBF])|
([\xE1-\xEC\xEE-\xEF][\x80-\xBF])|
([\xED][\x80-\x9F])
)
[\x80-\xBF]
|
# 4 bytes
(?:
([\xF0][\x90-\xBF])|
([\xF1-\xF3][\x80-\xBF])|
([\xF4][\x80-\x8F])
)
[\x80-\xBF][\x80-\xBF]
}xo;
$regex{validUtf8StringRegex} = qr/^(?:$regex{validUtf8CharRegex})+$/;
# Check for unsafe search regex mode (affects filtering in) - default
# to safe mode
$Foswiki::cfg{ForceUnsafeRegexes} = 0
unless defined $Foswiki::cfg{ForceUnsafeRegexes};
# initialize lib directory early because of later 'cd's
_getLibDir();
# initialize the runtime engine
if ( !defined $Foswiki::cfg{Engine} ) {
# Caller did not define an engine; try and work it out (mainly for
# the benefit of pre-1.0 CGI scripts)
$Foswiki::cfg{Engine} = 'Foswiki::Engine::Legacy';
}
$engine = eval qq(use $Foswiki::cfg{Engine}; $Foswiki::cfg{Engine}->new);
die $@ if $@;
#Monitor::MARK('End of BEGIN block in Foswiki.pm');
}
# Components that all requests need
use Foswiki::Response ();
use Foswiki::Request ();
use Foswiki::Logger ();
use Foswiki::Meta ();
use Foswiki::Sandbox ();
use Foswiki::Time ();
use Foswiki::Prefs ();
use Foswiki::Plugins ();
use Foswiki::Users ();
=begin TML
---++ ObjectMethod writeCompletePage( $text, $pageType, $contentType )
Write a complete HTML page with basic header to the browser.
* =$text= is the text of the page script (<html> to </html> if it's HTML)
* =$pageType= - May be "edit", which will cause headers to be generated that force
caching for 24 hours, to prevent Codev.BackFromPreviewLosesText bug, which caused
data loss with IE5 and IE6.
* =$contentType= - page content type | text/html
This method removes noautolink and nop tags before outputting the page unless
$contentType is text/plain.
=cut
sub writeCompletePage {
my ( $this, $text, $pageType, $contentType ) = @_;
# true if the body is to be output without encoding to utf8
# first. This is the case if the body has been gzipped and/or
# rendered from the cache
my $binary_body = 0;
$contentType ||= 'text/html';
my $cgis = $this->{users}->getCGISession();
if ( $cgis
&& $contentType =~ m!^text/html!
&& $Foswiki::cfg{Validation}{Method} ne 'none' )
{
# Don't expire the validation key through login, or when
# endpoint is an error.
Foswiki::Validation::expireValidationKeys($cgis)
unless ( $this->{request}->action() eq 'login'
or ( $ENV{REDIRECT_STATUS} || 0 ) >= 400 );
my $usingStrikeOne = $Foswiki::cfg{Validation}{Method} eq 'strikeone';
if ($usingStrikeOne) {
# add the validation cookie
my $valCookie = Foswiki::Validation::getCookie($cgis);
$valCookie->secure( $this->{request}->secure );
$this->{response}
->cookies( [ $this->{response}->cookies, $valCookie ] );
# Add the strikeone JS module to the page.
my $src = (DEBUG) ? '.uncompressed' : '';
$this->zones()->addToZone(
'script',
'JavascriptFiles/strikeone',
'<script type="text/javascript" src="'
. $this->getPubURL(
$Foswiki::cfg{SystemWebName}, 'JavascriptFiles',
"strikeone$src.js"
)
. '"></script>',
'JQUERYPLUGIN'
);
# Add the onsubmit handler to the form
$text =~ s/(<form[^>]*method=['"]POST['"][^>]*>)/
Foswiki::Validation::addOnSubmit($1)/gei;
}
my $context =
$this->{request}->url( -full => 1, -path => 1, -query => 1 ) . time();
# Inject validation key in HTML forms
$text =~ s/(<form[^>]*method=['"]POST['"][^>]*>)/
$1 . Foswiki::Validation::addValidationKey(
$cgis, $context, $usingStrikeOne )/gei;
#add validation key to HTTP header so we can update it for ajax use
$this->{response}->pushHeader(
'X-Foswiki-Validation',
Foswiki::Validation::generateValidationKey(
$cgis, $context, $usingStrikeOne
)
) if ($cgis);
}
if ( $this->{zones} ) {
$text = $this->zones()->_renderZones($text);
}
# Validate format of content-type (defined in rfc2616)
my $tch = qr/[^\[\]()<>@,;:\\"\/?={}\s]/;
if ( $contentType =~ m/($tch+\/$tch+(\s*;\s*$tch+=($tch+|"[^"]*"))*)$/i ) {
$contentType = $1;
}
else {
# SMELL: can't compute; faking content-type for backwards compatibility;
# any other information might become bogus later anyway
$contentType = "text/plain;contenttype=invalid";
}
my $hdr = "Content-type: " . $1 . "\r\n";
# Call final handler
$this->{plugins}->dispatch( 'completePageHandler', $text, $hdr );
# cache final page, but only view and rest
my $cachedPage;
if ( $contentType ne 'text/plain' ) {
# Remove <nop> and <noautolink> tags
$text =~ s/([\t ]?)[ \t]*<\/?(nop|noautolink)\/?>/$1/gis;
if ( $Foswiki::cfg{Cache}{Enabled}
&& ( $this->inContext('view') || $this->inContext('rest') ) )
{
$cachedPage = $this->{cache}->cachePage( $contentType, $text );
$this->{cache}->renderDirtyAreas( \$text )
if $cachedPage && $cachedPage->{isdirty};
}
# remove <dirtyarea> tags
$text =~ s/<\/?dirtyarea[^>]*>//g;
# Check that the templates specified clean HTML
if (DEBUG) {
# When tracing is enabled in Foswiki::Templates, then there will
# always be a <!--bodyend--> after </html>. So we need to disable
# this check.
require Foswiki::Templates;
if ( !Foswiki::Templates->TRACE
&& $contentType =~ m#text/html#
&& $text =~ m#</html>(.*?\S.*)$#s )
{
ASSERT( 0, <<BOGUS );
Junk after </html>: $1. Templates may be bogus
- Check for excess blank lines at ends of .tmpl files
- or newlines after %TMPL:INCLUDE
- You can enable TRACE in Foswiki::Templates to help debug
BOGUS
}
}
}
$this->{response}->pushHeader( 'X-Foswiki-Monitor-renderTime',
$this->{request}->getTime() );
my $hopts = { 'Content-Type' => $contentType };
$this->setCacheControl( $pageType, $hopts );
if ($cachedPage) {
$text = '' unless $this->setETags( $cachedPage, $hopts );
}
if ( $Foswiki::cfg{HttpCompress} && length($text) ) {
# Generate a zipped page, if the client accepts them
if ( my $encoding = _gzipAccepted() ) {
$hopts->{'Content-Encoding'} = $encoding;
$hopts->{'Vary'} = 'Accept-Encoding';
# check if we take the version from the cache. NOTE: we don't
# set X-Foswiki-Pagecache because this is *not* coming from
# the cache (well it is, but it was only just put there)
if ( $cachedPage && !$cachedPage->{isdirty} ) {
$text = $cachedPage->{data};
}
else {
# Not available from the cache, or it has dirty areas
require Compress::Zlib;
$text = Compress::Zlib::memGzip( encode_utf8($text) );
}
$binary_body = 1;
}
} # Otherwise fall through and generate plain text
# Generate (and print) HTTP headers.
$this->generateHTTPHeaders($hopts);
if ($binary_body) {
$this->{response}->body($text);
}
else {
$this->{response}->print($text);
}
}
# PRIVATE
sub _gzipAccepted {
my $encoding;
if ( ( $ENV{'HTTP_ACCEPT_ENCODING'} || '' ) =~
/(?:^|\b)((?:x-)?gzip)(?:$|\b)/ )
{
$encoding = $1;
}
elsif ( $ENV{'HTTP2'} ) {
# SMELL: $ENV{'HTTP2'} is a non-standard way to detect http2 protocol
$encoding = 'gzip';
}
return $encoding;
}
=begin TML
---++ ObjectMethod satisfiedByCache( $action, $web, $topic ) -> $boolean
Try and satisfy the current request for the given web.topic from the cache, given
the current action (view, edit, rest etc).
If the action is satisfied, the cache content is written to the output and
true is returned. Otherwise ntohing is written, and false is returned.
Designed for calling from Foswiki::UI::*
=cut
sub satisfiedByCache {
my ( $this, $action, $web, $topic ) = @_;
my $cache = $this->{cache};
return 0 unless $cache;
my $cachedPage = $cache->getPage( $web, $topic ) if $cache;
return 0 unless $cachedPage;
Foswiki::Func::writeDebug("found $web.$topic for $action in cache")
if Foswiki::PageCache::TRACE();
if ( int( $this->{response}->status() || 200 ) >= 500 ) {
Foswiki::Func::writeDebug(
"Cache retrieval skipped due to non-200 status code "
. $this->{response}->status() )
if DEBUG;
return 0;
}
Monitor::MARK("found page in cache");
my $hdrs = { 'Content-Type' => $cachedPage->{contenttype} };
# render uncacheable areas
my $text = $cachedPage->{data};
if ( $cachedPage->{isdirty} ) {
$cache->renderDirtyAreas( \$text );
# dirty pages are cached in unicode
$text = encode_utf8($text);
}
elsif ( $Foswiki::cfg{HttpCompress} ) {
# Does the client accept gzip?
if ( my $encoding = _gzipAccepted() ) {
# Cache has compressed data, just whack it out
$hdrs->{'Content-Encoding'} = $encoding;
$hdrs->{'Vary'} = 'Accept-Encoding';
}
else {
# e.g. CLI request satisfied from the cache, or old browser that doesn't
# support gzip. Non-isdirty pages are cached already utf8-encoded, so
# all we have to do is unzip.
require Compress::Zlib;
$text = Compress::Zlib::memGunzip( $cachedPage->{data} );
}
} # else { Non-isdirty pages are stored already utf8-encoded }
# set status
my $response = $this->{response};
if ( $cachedPage->{status} == 302 ) {
$response->redirect( $cachedPage->{location} );
}
else {
# See Item9941
# Don't allow a 200 status to overwrite a status (possibly an error status)
# coming from elsewhere in the code. Note that 401's are not cached (they
# fail Foswiki::PageCache::isCacheable) but all other statuses are.
# SMELL: Cdot doesn't think any other status can get this far.
$response->status( $cachedPage->{status} )
unless int( $cachedPage->{status} ) == 200;
}
# set remaining headers
# Mark the response so we know it was satisfied from the cache
$hdrs->{'X-Foswiki-PageCache'} = 1;
$text = undef unless $this->setETags( $cachedPage, $hdrs );
$this->generateHTTPHeaders($hdrs);
# send it out
$response->body($text) if defined $text;
Monitor::MARK('Wrote HTML');
$this->logger->log(
{
level => 'info',
action => $action,
webTopic => $web . '.' . $topic,
extra => '(cached)',
}
);
return 1;
}
=begin TML
---++ ObjectMethod setCacheControl( $pageType, \%hopts )
Set the cache control headers in a response
* =$pageType= - page type - 'view', ;edit' etc
* =\%hopts - ref to partially filled in hash of headers
=cut
sub setCacheControl {
my ( $this, $pageType, $hopts ) = @_;
if ( $pageType && $pageType eq 'edit' ) {
# Edit pages - future versions will extend to
# of other types of page, with expiry time driven by page type.
# Get time now in HTTP header format
my $lastModifiedString =
Foswiki::Time::formatTime( time, '$http', 'gmtime' );
# Expiry time is set high to avoid any data loss. Each instance of
# Edit page has a unique URL with time-string suffix (fix for
# RefreshEditPage), so this long expiry time simply means that the
# browser Back button always works. The next Edit on this page
# will use another URL and therefore won't use any cached
# version of this Edit page.
my $expireHours = 24;