/
Foswiki.pm
4051 lines (3244 loc) · 127 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;
use v5.14; # First version to accept v-numbers.
=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 Cwd qw( abs_path );
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 Scalar::Util ();
use Foswiki::Exception;
#use Foswiki::Store::PlainFile ();
# 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{&<>"'};
# 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;
use Try::Tiny;
use Moo;
use namespace::clean;
extends qw( Foswiki::Object );
use Assert;
sub SINGLE_SINGLETONS { 0 }
sub SINGLE_SINGLETONS_TRACE { 0 }
has access => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
require Foswiki::Access;
return Foswiki::Access->create( $_[0] );
},
);
has attach => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
require Foswiki::Attach;
new Foswiki::Attach( session => $_[0] );
},
);
has cache => (
is => 'rw',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
my $this = shift;
if ( $Foswiki::cfg{Cache}{Enabled}
&& $Foswiki::cfg{Cache}{Implementation} )
{
eval "require $Foswiki::cfg{Cache}{Implementation}";
ASSERT( !$@, $@ ) if DEBUG;
return $Foswiki::cfg{Cache}{Implementation}->new();
}
return undef;
},
);
has context => (
is => 'rw',
lazy => 1,
clearer => 1,
default => sub { {} },
);
has digester => (
is => 'ro',
lazy => 1,
clearer => 1,
default => sub { return Digest::MD5->new; },
);
has forms => (
is => 'ro',
lazy => 1,
clearer => 1,
default => sub { {} },
);
# Heap is to be used for data persistent over session lifetime.
# Usage: $sessiom->heap->{key} = <your data>;
has heap => (
is => 'rw',
clearer => 1,
lazy => 1,
default => sub { {} },
);
has i18n => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
load_package('Foswiki::I18N');
# language information; must be loaded after
# *all possible preferences sources* are available
Foswiki::I18N->new( session => $_[0] );
},
);
has invalidTopic => (
is => 'rw',
clearer => 1,
);
has invalidWeb => (
is => 'rw',
clearer => 1,
);
has logger => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
my $this = shift;
my $logger;
if ( $Foswiki::cfg{Log}{Implementation} ne 'none' ) {
load_package( $Foswiki::cfg{Log}{Implementation} );
if ($@) {
print STDERR "Logger load failed: $@";
}
else {
$logger = $Foswiki::cfg{Log}{Implementation}->new();
}
}
$logger = Foswiki::Logger->new() unless defined $logger;
return $logger;
},
);
has net => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
load_package('Foswiki::Net');
return Foswiki::Net->new( session => $_[0] );
},
);
has plugins => (
is => 'rw',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub { return Foswiki::Plugins->new( session => $_[0] ); },
);
has prefs => (
is => 'ro',
lazy => 1,
predicate => 1,
clearer => 1,
default => sub { return Foswiki::Prefs->new( session => $_[0] ); },
);
has remoteUser => (
is => 'rw',
clearer => 1,
);
has renderer => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
load_package('Foswiki::Render');
Foswiki::Render->new( session => $_[0] );
},
);
has request => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
coerce => sub { defined $_[0] ? $_[0] : Foswiki::Request->new },
default => sub {
return Foswiki::Request->new;
},
isa => Foswiki::Object::isaCLASS( 'request', 'Foswiki::Request' ),
);
has requestedWebName => ( is => 'rw', clearer => 1, );
has response => (
is => 'rw',
lazy => 1,
clearer => 1,
default => sub { return Foswiki::Response->new; },
);
has sandbox => (
is => 'ro',
default => 'Foswiki::Sandbox',
clearer => 1,
);
has scriptUrlPath => (
is => 'ro',
lazy => 1,
clearer => 1,
default => sub {
my $this = shift;
my $scriptUrlPath = $Foswiki::cfg{ScriptUrlPath};
my $url = $this->request->url;
if ( $Foswiki::cfg{GetScriptUrlFromCgi}
&& $url
&& $url =~ m{^[^:]*://[^/]*(.*)/.*$}
&& $1 )
{
# SMELL: this is a really dangerous hack. It will fail
# spectacularly with mod_perl.
# SMELL: why not just use $query->script_name?
# SMELL: unchecked implicit untaint?
$scriptUrlPath = $1;
}
return $scriptUrlPath;
},
);
has search => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
require Foswiki::Search;
return Foswiki::Search->new( session => $_[0] );
},
);
has store => (
is => 'rw',
lazy => 1,
clearer => 1,
predicate => 1,
isa =>
Foswiki::Object::isaCLASS( 'store', 'Foswiki::Store', noUndef => 1, ),
default => sub {
my $baseClass = $_[0]->_baseStoreClass;
ASSERT( $baseClass, "Foswiki::store base class is not defined" )
if DEBUG;
return $baseClass->new;
},
);
has _baseStoreClass => (
is => 'rw',
clearer => 1,
#default => 'Foswiki::Store::PlainFile',
isa => sub {
ASSERT( defined( $_[0] ), "Foswiki::_baseStoreClass cannot be undef" );
},
);
has templates => (
is => 'ro',
lazy => 1,
predicate => 1,
clearer => 1,
default => sub {
require Foswiki::Templates;
return Foswiki::Templates->new( session => $_[0] );
},
);
has topicName => (
is => 'rw',
clearer => 1,
);
# SMELL Shouldn't urlHost attribute be available from the request object?
has urlHost => (
is => 'rw',
lazy => 1,
clearer => 1,
default => sub {
my $this = shift;
#{urlHost} is needed by loadSession..
my $url = $this->request->url();
my $urlHost;
if ( $url
&& !$Foswiki::cfg{ForceDefaultUrlHost}
&& $url =~ m{^([^:]*://[^/]*).*$} )
{
$urlHost = $1;
if ( $Foswiki::cfg{RemovePortNumber} ) {
$urlHost =~ s/\:[0-9]+$//;
}
# If the urlHost in the url is localhost, this is a lot less
# useful than the default url host. This is because new CGI("")
# assigns this host by default - it's a default setting, used
# when there is nothing better available.
if ( $urlHost =~ m/^(https?:\/\/)localhost$/i ) {
my $protocol = $1;
#only replace localhost _if_ the protocol matches the one specified in the DefaultUrlHost
if ( $Foswiki::cfg{DefaultUrlHost} =~ m/^$protocol/i ) {
$urlHost = $Foswiki::cfg{DefaultUrlHost};
}
}
}
else {
$urlHost = $Foswiki::cfg{DefaultUrlHost};
}
ASSERT($urlHost) if DEBUG;
return $urlHost;
},
);
has user => (
is => 'rw',
clearer => 1,
);
has users => (
is => 'rw',
lazy => 1,
predicate => 1,
clearer => 1,
default => sub { return Foswiki::Users->new( session => $_[0] ); },
);
has webName => (
is => 'rw',
clearer => 1,
);
has zones => (
is => 'ro',
lazy => 1,
clearer => 1,
predicate => 1,
default => sub {
load_package('Foswiki::Render::Zones');
return Foswiki::Render::Zones->new( session => $_[0] );
},
);
# Collection of macros objects
has _macros => (
is => 'rw',
lazy => 1,
clearer => 1,
default => sub { {} },
);
our @_newParameters = qw( user request context );
# 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.0');
$RELEASE = 'Foswiki-2.1.0';
# 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.
# If an entry is defined it could be of two values: either a coderef or a
# string. String must contain class/module name of a macro object. This is
# for macros which previously were storing their data on session objects.
%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,
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 {
$bootstrap_message = Foswiki::Configure::Load::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} };
# 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{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
---++ ClassMethod new( $defaultUser, $query, \%initialContext )
Constructs a new Foswiki session object. A unique session object exists for
every transaction with Foswiki, for example every browser request, or every
script run. Session objects do not persist between mod_perl runs.
* =$defaultUser= is the username (*not* the wikiname) of the default
user you want to be logged-in, if none is available from a session
or browser. Used mainly for unit tests and debugging, it is typically
undef, in which case the default user is taken from
$Foswiki::cfg{DefaultUserName}.
* =$query= the Foswiki::Request query (may be undef, in which case an
empty query is used)
* =\%initialContext= - reference to a hash containing context
name=value pairs to be pre-installed in the context hash. May be undef.
=cut
around BUILDARGS => sub {