/
Foswiki.pm
4386 lines (3546 loc) · 139 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
# See bottom of file for license and copyright information
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::Respose
* =context= Hash of context ids
* moved: =loginManager= Foswiki::LoginManager singleton (moved to Foswiki::Users)
* =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.
* =security= Foswiki::Access singleton
* =SESSION_TAGS= Hash of preference settings whose value is specific to
the current request.
* =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 Assert;
use Error qw( :try );
use CGI; # Always required to get html generation tags;
use Foswiki::Response;
use Foswiki::Request;
require 5.005; # For regex objects and internationalisation
# Site configuration constants
use vars qw( %cfg );
# Uncomment this and the __END__ to enable AutoLoader
#use AutoLoader 'AUTOLOAD';
# You then need to autosplit Foswiki.pm:
# cd lib
# perl -e 'use AutoSplit; autosplit("Foswiki.pm", "auto")'
# Other computed constants
our $foswikiLibDir;
our %regex;
our %functionTags;
our %contextFreeSyntax;
our %restDispatch;
our $VERSION;
our $RELEASE;
our $TRUE = 1;
our $FALSE = 0;
our $sandbox;
our $engine;
our $ifParser;
# Token character that must not occur in any normal text - converted
# to a flag character if it ever does occur (very unlikely)
# Foswiki uses $TranslationToken to mark points in the text. This is
# normally \0, which is not a useful character in any 8-bit character
# set we can find, nor in UTF-8. But if you *do* encounter problems
# with it, the workaround is to change $TranslationToken to something
# longer that is unlikely to occur in your text - for example
# muRfleFli5ble8leep (do *not* use punctuation characters or whitspace
# in the string!)
# See Codev.NationalCharTokenClash for more.
our $TranslationToken = "\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 =~ /^\./ ) {
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;
}
BEGIN {
require Monitor;
require Foswiki::Sandbox; # system command sandbox
require Foswiki::Configure::Load; # read configuration files
if (DEBUG) {
# If ASSERTs are on, then warnings are errors. Paranoid,
# but the only way to be sure we eliminate them all.
# Look out also for $cfg{WarningsAreErrors}, below, which
# is another way to install this handler without enabling
# ASSERTs
# 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 {
$Error::Debug = 0; # no verbose stack traces
}
# DO NOT CHANGE THE FORMAT OF $VERSION
# Automatically expanded on checkin of this module
$VERSION = '$Date$ $Rev$ ';
$RELEASE = 'Foswiki-1.0.0';
$VERSION =~ s/^.*?\((.*)\).*: (\d+) .*?$/$RELEASE, $1, build $2/;
# Default handlers for different %TAGS%
%functionTags = (
ADDTOHEAD => \&ADDTOHEAD,
ALLVARIABLES => \&ALLVARIABLES,
ATTACHURL => \&ATTACHURL,
ATTACHURLPATH => \&ATTACHURLPATH,
COREPOD => \&COREPOD,
DATE => \&DATE,
DISPLAYTIME => \&DISPLAYTIME,
ENCODE => \&ENCODE,
ENV => \&ENV,
FORMFIELD => \&FORMFIELD,
GMTIME => \&GMTIME,
GROUPS => \&GROUPS,
HTTP_HOST => \&HTTP_HOST_deprecated,
HTTP => \&HTTP,
HTTPS => \&HTTPS,
ICON => \&ICON,
ICONURL => \&ICONURL,
ICONURLPATH => \&ICONURLPATH,
IF => \&IF,
INCLUDE => \&INCLUDE,
INTURLENCODE => \&INTURLENCODE_deprecated,
LANGUAGES => \&LANGUAGES,
MAKETEXT => \&MAKETEXT,
META => \&META,
METASEARCH => \&METASEARCH,
NOP => \&NOP,
PLUGINVERSION => \&PLUGINVERSION,
PUBURL => \&PUBURL,
PUBURLPATH => \&PUBURLPATH,
QUERYPARAMS => \&QUERYPARAMS,
QUERYSTRING => \&QUERYSTRING,
RELATIVETOPICPATH => \&RELATIVETOPICPATH,
REMOTE_ADDR => \&REMOTE_ADDR_deprecated,
REMOTE_PORT => \&REMOTE_PORT_deprecated,
REMOTE_USER => \&REMOTE_USER_deprecated,
RENDERHEAD => \&RENDERHEAD,
REVINFO => \&REVINFO,
REVTITLE => \&REVTITLE,
REVARG => \&REVARG,
SCRIPTNAME => \&SCRIPTNAME,
SCRIPTURL => \&SCRIPTURL,
SCRIPTURLPATH => \&SCRIPTURLPATH,
SEARCH => \&SEARCH,
SEP => \&SEP,
SERVERTIME => \&SERVERTIME,
SPACEDTOPIC => \&SPACEDTOPIC_deprecated,
SPACEOUT => \&SPACEOUT,
'TMPL:P' => \&TMPLP,
TOPICLIST => \&TOPICLIST,
URLENCODE => \&ENCODE,
URLPARAM => \&URLPARAM,
LANGUAGE => \&LANGUAGE,
USERINFO => \&USERINFO,
USERNAME => \&USERNAME_deprecated,
VAR => \&VAR,
WEBLIST => \&WEBLIST,
WIKINAME => \&WIKINAME_deprecated,
WIKIUSERNAME => \&WIKIUSERNAME_deprecated,
# Constant tag strings _not_ dependent on config. These get nicely
# optimised by the compiler.
ENDSECTION => sub { '' },
WIKIVERSION => sub { $VERSION },
STARTSECTION => sub { '' },
STARTINCLUDE => sub { '' },
STOPINCLUDE => sub { '' },
);
$contextFreeSyntax{IF} = 1;
unless ( ( $Foswiki::cfg{DetailedOS} = $^O ) ) {
require Config;
$Foswiki::cfg{DetailedOS} = $Config::Config{'osname'};
}
$Foswiki::cfg{OS} = 'UNIX';
if ( $Foswiki::cfg{DetailedOS} =~ /darwin/i ) { # MacOS X
$Foswiki::cfg{OS} = 'UNIX';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /Win/i ) {
$Foswiki::cfg{OS} = 'WINDOWS';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /vms/i ) {
$Foswiki::cfg{OS} = 'VMS';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /bsdos/i ) {
$Foswiki::cfg{OS} = 'UNIX';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /dos/i ) {
$Foswiki::cfg{OS} = 'DOS';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /^MacOS$/i ) { # MacOS 9 or earlier
$Foswiki::cfg{OS} = 'MACINTOSH';
}
elsif ( $Foswiki::cfg{DetailedOS} =~ /os2/i ) {
$Foswiki::cfg{OS} = 'OS2';
}
# readConfig is defined in Foswiki::Configure::Load to allow overriding it
Foswiki::Configure::Load::readConfig();
if ( $Foswiki::cfg{WarningsAreErrors} ) {
# Note: Warnings are always errors if ASSERTs are enabled
$SIG{'__WARN__'} = sub { die @_ };
}
if ( $Foswiki::cfg{UseLocale} ) {
require locale;
import locale();
}
# Constant tags dependent on the config
$functionTags{ALLOWLOGINNAME} =
sub { $Foswiki::cfg{Register}{AllowLoginName} || 0 };
$functionTags{AUTHREALM} = sub { $Foswiki::cfg{AuthRealm} };
$functionTags{DEFAULTURLHOST} = sub { $Foswiki::cfg{DefaultUrlHost} };
$functionTags{HOMETOPIC} = sub { $Foswiki::cfg{HomeTopicName} };
$functionTags{LOCALSITEPREFS} = sub { $Foswiki::cfg{LocalSitePreferences} };
$functionTags{NOFOLLOW} =
sub { $Foswiki::cfg{NoFollow} ? 'rel=' . $Foswiki::cfg{NoFollow} : '' };
$functionTags{NOTIFYTOPIC} = sub { $Foswiki::cfg{NotifyTopicName} };
$functionTags{SCRIPTSUFFIX} = sub { $Foswiki::cfg{ScriptSuffix} };
$functionTags{STATISTICSTOPIC} = sub { $Foswiki::cfg{Stats}{TopicName} };
$functionTags{SYSTEMWEB} = sub { $Foswiki::cfg{SystemWebName} };
$functionTags{TRASHWEB} = sub { $Foswiki::cfg{TrashWebName} };
$functionTags{WIKIADMINLOGIN} = sub { $Foswiki::cfg{AdminUserLogin} };
$functionTags{USERSWEB} = sub { $Foswiki::cfg{UsersWebName} };
$functionTags{WEBPREFSTOPIC} = sub { $Foswiki::cfg{WebPrefsTopicName} };
$functionTags{WIKIPREFSTOPIC} = sub { $Foswiki::cfg{SitePrefsTopicName} };
$functionTags{WIKIUSERSTOPIC} = sub { $Foswiki::cfg{UsersTopicName} };
$functionTags{WIKIWEBMASTER} = sub { $Foswiki::cfg{WebMasterEmail} };
$functionTags{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} );
}
$functionTags{CHARSET} = sub {
$Foswiki::cfg{Site}{CharSet}
|| 'iso-8859-1';
};
$functionTags{LANG} = sub {
$Foswiki::cfg{Site}{Locale} =~ m/^([a-z]+_[a-z]+)/i ? $1 : 'en_US';
};
# Set up pre-compiled regexes for use in rendering. All regexes with
# unchanging variables in match should use the '/o' option.
# 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.
# Build up character class components for use in regexes.
# Depends on locale mode and Perl version, and finally on
# whether locale-based regexes are turned off.
if ( not $Foswiki::cfg{UseLocale}
or $] < 5.006
or not $Foswiki::cfg{Site}{LocaleRegexes} )
{
# No locales needed/working, or Perl 5.005, so just use
# any additional national characters defined in LocalSite.cfg
$regex{upperAlpha} = 'A-Z' . $Foswiki::cfg{UpperNational};
$regex{lowerAlpha} = 'a-z' . $Foswiki::cfg{LowerNational};
$regex{numeric} = '\d';
$regex{mixedAlpha} = $regex{upperAlpha} . $regex{lowerAlpha};
}
else {
# Perl 5.006 or higher with working locales
$regex{upperAlpha} = '[:upper:]';
$regex{lowerAlpha} = '[:lower:]';
$regex{numeric} = '[:digit:]';
$regex{mixedAlpha} = '[:alpha:]';
}
$regex{mixedAlphaNum} = $regex{mixedAlpha} . $regex{numeric};
$regex{lowerAlphaNum} = $regex{lowerAlpha} . $regex{numeric};
$regex{upperAlphaNum} = $regex{upperAlpha} . $regex{numeric};
# 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};
# 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/[$regex{upperAlpha}]+[$regex{lowerAlphaNum}]+[$regex{upperAlpha}]+[$regex{mixedAlphaNum}]*/o;
$regex{webNameBaseRegex} =
qr/[$regex{upperAlpha}]+[$regex{mixedAlphaNum}_]*/o;
if ( $Foswiki::cfg{EnableHierarchicalWebs} ) {
$regex{webNameRegex} =
qr/$regex{webNameBaseRegex}(?:(?:[\.\/]$regex{webNameBaseRegex})+)*/o;
}
else {
$regex{webNameRegex} = $regex{webNameBaseRegex};
}
$regex{defaultWebNameRegex} = qr/_[$regex{mixedAlphaNum}_]+/o;
$regex{anchorRegex} = qr/\#[$regex{mixedAlphaNum}_]+/o;
$regex{abbrevRegex} = qr/[$regex{upperAlpha}]{3,}s?\b/o;
$regex{topicNameRegex} =
qr/(?:(?:$regex{wikiWordRegex})|(?:$regex{abbrevRegex}))/o;
# Simplistic email regex, e.g. for WebNotify processing - no i18n
# characters allowed
$regex{emailAddrRegex} = qr/([a-z0-9!+$%&'*+-\/=?^_`{|}~.]+\@[a-z0-9\.\-]+)/i;
# Filename regex to used to match invalid characters in attachments - allow
# alphanumeric characters, spaces, underscores, etc.
# TODO: Get this to work with I18N chars - currently used only with UseLocale off
$regex{filenameInvalidCharRegex} = qr/[^$regex{mixedAlphaNum}\. _-]/o;
# Multi-character alpha-based regexes
$regex{mixedAlphaNumRegex} = qr/[$regex{mixedAlphaNum}]*/o;
# %TAG% name
$regex{tagNameRegex} =
'[' . $regex{mixedAlpha} . '][' . $regex{mixedAlphaNum} . '_:]*';
# 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
# 7-bit ASCII only
$regex{validAsciiStringRegex} = qr/^[\x00-\x7F]+$/o;
# 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} )+ $/xo;
# 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('Static configuration loaded');
}
=begin TML
---++ ObjectMethod UTF82SiteCharSet( $utf8 ) -> $ascii
Auto-detect UTF-8 vs. site charset in string, and convert UTF-8 into site
charset.
=cut
sub UTF82SiteCharSet {
my ( $this, $text ) = @_;
return $text unless ( defined $Foswiki::cfg{Site}{CharSet} );
# Detect character encoding of the full topic name from URL
return undef if ( $text =~ $regex{validAsciiStringRegex} );
# SMELL: all this regex stuff should go away.
# If not UTF-8 - assume in site character set, no conversion required
if ($^O eq 'darwin') {
#this is a gross over-generalisation - as not all darwins are apple's
# and not all darwins use apple's perl
my $trial = $text;
$trial =~ s/$regex{validUtf8CharRegex}//g;
return unless (length($trial) == 0);
} else {
#SMELL: this seg faults on OSX leopard. (and possibly others)
return undef unless ( $text =~ $regex{validUtf8StringRegex} );
}
# If site charset is already UTF-8, there is no need to convert anything:
if ( $Foswiki::cfg{Site}{CharSet} =~ /^utf-?8$/i ) {
# warn if using Perl older than 5.8
if ( $] < 5.008 ) {
$this->writeWarning( 'UTF-8 not remotely supported on Perl '
. $]
. ' - use Perl 5.8 or higher..' );
}
# We still don't have Codev.UnicodeSupport
$this->writeWarning( 'UTF-8 not yet supported as site charset -'
. 'Foswiki is likely to have problems' );
return $text;
}
# Convert into ISO-8859-1 if it is the site charset. This conversion
# is *not valid for ISO-8859-15*.
if ( $Foswiki::cfg{Site}{CharSet} =~ /^iso-?8859-?1$/i ) {
# ISO-8859-1 maps onto first 256 codepoints of Unicode
# (conversion from 'perldoc perluniintro')
$text =~ s/ ([\xC2\xC3]) ([\x80-\xBF]) /
chr( ord($1) << 6 & 0xC0 | ord($2) & 0x3F )
/egx;
}
else {
# Convert from UTF-8 into some other site charset
if ( $] >= 5.008 ) {
require Encode;
import Encode qw(:fallbacks);
# Map $Foswiki::cfg{Site}{CharSet} into real encoding name
my $charEncoding =
Encode::resolve_alias( $Foswiki::cfg{Site}{CharSet} );
if ( not $charEncoding ) {
$this->writeWarning( 'Conversion to "'
. $Foswiki::cfg{Site}{CharSet}
. '" not supported, or name not recognised - check '
. '"perldoc Encode::Supported"' );
}
else {
# Convert text using Encode:
# - first, convert from UTF8 bytes into internal
# (UTF-8) characters
$text = Encode::decode( 'utf8', $text );
# - then convert into site charset from internal UTF-8,
# inserting \x{NNNN} for characters that can't be converted
$text = Encode::encode( $charEncoding, $text, &FB_PERLQQ() );
}
}
else {
require Unicode::MapUTF8; # Pre-5.8 Perl versions
my $charEncoding = $Foswiki::cfg{Site}{CharSet};
if ( not Unicode::MapUTF8::utf8_supported_charset($charEncoding) ) {
$this->writeWarning( 'Conversion to "'
. $Foswiki::cfg{Site}{CharSet}
. '" not supported, or name not recognised - check '
. '"perldoc Unicode::MapUTF8"' );
}
else {
# Convert text
$text = Unicode::MapUTF8::from_utf8(
{
-string => $text,
-charset => $charEncoding
}
);
# FIXME: Check for failed conversion?
}
}
}
return $text;
}
=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 body (<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 ) = @_;
$contentType ||= 'text/html';
if ( $contentType ne 'text/plain' ) {
# Remove <nop> and <noautolink> tags
$text =~ s/([\t ]?)[ \t]*<\/?(nop|noautolink)\/?>/$1/gis;
$text .= "\n" unless $text =~ /\n$/s;
my $htmlHeader = join( "\n",
map { '<!--' . $_ . '-->' . $this->{_HTMLHEADERS}{$_} }
keys %{ $this->{_HTMLHEADERS} } );
$text =~ s!(</head>)!$htmlHeader$1!i if $htmlHeader;
chomp($text);
}
$this->generateHTTPHeaders( undef, $pageType, $contentType );
my $hdr = $this->{response}->printHeaders;
# Call final handler
$this->{plugins}->dispatch( 'completePageHandler', $text, $hdr );
$this->{response}->print($text);
}
=begin TML
---++ ObjectMethod generateHTTPHeaders( $query, $pageType, $contentType ) -> $header
All parameters are optional.
* =$query= CGI query object | Session CGI query (there is no good reason to set this)
* =$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
=cut
sub generateHTTPHeaders {
my ( $this, $query, $pageType, $contentType ) = @_;
$query = $this->{request} unless $query;
# Handle Edit pages - future versions will extend to caching
# of other types of page, with expiry time driven by page type.
my ( $pluginHeaders, $coreHeaders );
my $hopts = {};
if ( $pageType && $pageType eq 'edit' ) {
# Get time now in HTTP header format
require Foswiki::Time;
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;
my $expireSeconds = $expireHours * 60 * 60;
# and cache control headers, to ensure edit page
# is cached until required expiry time.
$hopts->{'last-modified'} = $lastModifiedString;
$hopts->{expires} = "+${expireHours}h";
$hopts->{'cache-control'} = "max-age=$expireSeconds";
}
# DEPRECATED plugins header handler. Plugins should use
# modifyHeaderHandler instead.
$pluginHeaders = $this->{plugins}->dispatch( 'writeHeaderHandler', $query )
|| '';
if ($pluginHeaders) {
foreach ( split /\r?\n/, $pluginHeaders ) {
# Implicit untaint OK; data from plugin handler
if (m/^([\-a-z]+): (.*)$/i) {
$hopts->{$1} = $2;
}
}
}
$contentType = 'text/html' unless $contentType;
if ( defined( $Foswiki::cfg{Site}{CharSet} ) ) {
$contentType .= '; charset=' . $Foswiki::cfg{Site}{CharSet};
}
# use our version of the content type
$hopts->{'Content-Type'} = $contentType;
# New (since 1.026)
$this->{plugins}
->dispatch( 'modifyHeaderHandler', $hopts, $this->{request} );
# add cookie(s)
$this->{users}->{loginManager}->modifyHeader($hopts);
# The headers method resets all headers to what we pass
# what we want is simply ensure our headers are there
$this->{response}->setDefaultHeaders($hopts);
}
# Tests if the $redirect is an external URL, returning false if
# AllowRedirectUrl is denied
sub _isRedirectSafe {
my $redirect = shift;
return 1 if ( $Foswiki::cfg{AllowRedirectUrl} );
return 1 if $redirect =~ m#^/#; # relative URL - OK
#TODO: this should really use URI
# Compare protocol, host name and port number
if ( $redirect =~ m!^(.*?://[^/]*)! ) {
# implicit untaints OK because result not used. uc retaints
# if use locale anyway.
my $target = uc( $1 );
$Foswiki::cfg{DefaultUrlHost} =~ m!^(.*?://[^/]*)!;
return 1 if ( $target eq uc($1) );
if ( $Foswiki::cfg{PermittedRedirectHostUrls} ) {
foreach my $red (split(
/\s*,\s*/, $Foswiki::cfg{PermittedRedirectHostUrls} )) {
$red =~ m!^(.*?://[^/]*)!;
return 1 if ( $target eq uc($1) );
}
}
}
return 0;
}
=begin TML
---++ ObjectMethod redirectto($url) -> $url
Gets a redirect url from CGI parameter 'redirectto', if present on the query.
If the redirectto CGI parameter specifies a valid redirection target it is
returned; otherwise the original URL passed in the parameter is returned.
Conditions for a valid redirection target are:
* The target matches the linkProtocolPattern regex, and redirection
to the url _isRedirectSafe
* The target specified a topic, or a Web.Topic (redirect will be to
'view')
=cut
sub redirectto {
my ($this, $url) = @_;
ASSERT($url);
my $redirecturl = $this->{request}->param('redirectto');
return $url unless $redirecturl;
if ( $redirecturl =~ m#^$regex{linkProtocolPattern}://#o ) {
# assuming URL
if ( _isRedirectSafe($redirecturl) ) {
return $redirecturl;
}
else {
return $url;
}
}
# assuming 'web.topic' or 'topic'
my ( $w, $t ) =
$this->normalizeWebTopicName( $this->{webName}, $redirecturl );
# capture anchor
my ($topic, $anchor) = split('#', $t, 2);
$t = $topic if $topic;
my @attrs = ();
push (@attrs, '#'=>$anchor) if $anchor;
return $this->getScriptUrl( 1, 'view', $w, $t, @attrs );
}
=begin TML
---++ ObjectMethod redirect( $url, $passthrough )
* $url - url or topic to redirect to
* $passthrough - (optional) parameter to pass through current query
parameters (see below)
Redirects the request to =$url=, *unless*
1 It is overridden by a plugin declaring a =redirectCgiQueryHandler=.
1 =$session->{request}= is =undef= or
Thus a redirect is only generated when in a CGI context.
Normally this method will ignore parameters to the current query. Sometimes,
for example when redirecting to a login page during authentication (and then
again from the login page to the original requested URL), you want to make
sure all parameters are passed on, and for this $passthrough should be set to
true. In this case it will pass all parameters that were passed to the
current query on to the redirect target. If the request_method for the
current query was GET, then all parameters will be passed by encoding them
in the URL (after ?). If the request_method was POST, then there is a risk the
URL would be too big for the receiver, so it caches the form data and passes
over a cache reference in the redirect GET.
NOTE: Passthrough is only meaningful if the redirect target is on the same
server.
=cut
sub redirect {
my ( $this, $url, $passthru ) = @_;
ASSERT(defined $url);
my $query = $this->{request};
# if we got here without a query, there's not much more we can do
return unless $query;
if ( $passthru && defined $query->method() ) {
my $existing = '';
if ( $url =~ s/\?(.*)$// ) {
$existing = $1; # implicit untaint OK; recombined later
}
if ( $query->method() eq 'POST' ) {
# Redirecting from a post to a get
my $cache = $this->cacheQuery();
if ($cache) {
$url .= "?$cache";
}
}
else {
if ( $query->query_string() ) {
$url .= '?' . $query->query_string();
}
if ($existing) {
if ( $url =~ /\?/ ) {
$url .= ';';
}
else {
$url .= '?';
}
$url .= $existing;
}
}
}
# prevent phishing by only allowing redirect to configured host
# do this check as late as possible to catch _any_ last minute hacks
# TODO: this should really use URI
if ( !_isRedirectSafe($url) ) {
# goto oops if URL is trying to take us somewhere dangerous
$url = $this->getScriptUrl(
1, 'oops',
$this->{web} || $Foswiki::cfg{UsersWebName},
$this->{topic} || $Foswiki::cfg{HomeTopicName},
template => 'oopsaccessdenied',
def => 'topic_access',
param1 => 'redirect',
param2 => 'unsafe redirect to '
. $url
. ': host does not match {DefaultUrlHost} , and is not in {PermittedRedirectHostUrls}"'
. $Foswiki::cfg{DefaultUrlHost} . '"'
);
}
return
if ( $this->{plugins}
->dispatch( 'redirectCgiQueryHandler', $this->{response}, $url ) );
# SMELL: this is a bad breaking of encapsulation: the loginManager
# should just modify the url, then the redirect should only happen here.
return !$this->{users}->{loginManager}->redirectCgiQuery( $query, $url );
}
=begin TML
---++ ObjectMethod cacheQuery() -> $queryString
Caches the current query in the params cache, and returns a rewritten
query string for the cache to be picked up again on the other side of a
redirect.
We can't encode post params into a redirect, because they may exceed the
size of the GET request. So we cache the params, and reload them when the
redirect target is reached.
=cut
sub cacheQuery {
my $this = shift;
my $query = $this->{request};
return '' unless ( scalar( $query->param() ) );
# Don't double-cache
return '' if ( $query->param('foswiki_redirect_cache') );
require Digest::MD5;
my $md5 = new Digest::MD5();
$md5->add( $$, time(), rand(time) );
my $uid = $md5->hexdigest();
my $passthruFilename = "$Foswiki::cfg{WorkingDir}/tmp/passthru_$uid";
use Fcntl;
#passthrough file is only written to once, so if it already exists, suspect a security hack (O_EXCL)
sysopen( F, "$passthruFilename", O_RDWR | O_EXCL | O_CREAT, 0600 )
|| die
"Unable to open $Foswiki::cfg{WorkingDir}/tmp for write; check the setting of {WorkingDir} in configure, and check file permissions: $!";
$query->save( \*F );
close(F);
return 'foswiki_redirect_cache=' . $uid;
}
=begin TML
---++ StaticMethod isValidWikiWord( $name ) -> $boolean
Check for a valid WikiWord or WikiName
=cut
sub isValidWikiWord {
my $name = shift || '';
return ( $name =~ m/^$regex{wikiWordRegex}$/o );
}
=begin TML
---++ StaticMethod isValidTopicName( $name [, $nonww] ) -> $boolean
Check for a valid topic =$name=. If =$nonww=, then accept non wiki-words
(though they must still be composed of only valid, unfiltered characters)
=cut
# Note: must work on tainted names.
sub isValidTopicName {
my ($name, $nonww) = @_;
return 0 unless defined $name && $name ne '';
return 1 if ( $name =~ m/^$regex{topicNameRegex}$/o );
return 0 unless $nonww;
return 0 if $name =~ /$Foswiki::cfg{NameFilter}/;
return 1;
}
=begin TML
---++ StaticMethod isValidWebName( $name, $system ) -> $boolean
STATIC Check for a valid web name. If $system is true, then
system web names are considered valid (names starting with _)
otherwise only user web names are valid
If $Foswiki::cfg{EnableHierarchicalWebs} is off, it will also return false
when a nested web name is passed to it.
=cut
# Note: must work on tainted names.
sub isValidWebName {
my $name = shift || '';
my $sys = shift;
return 1 if ( $sys && $name =~ m/^$regex{defaultWebNameRegex}$/o );
return ( $name =~ m/^$regex{webNameRegex}$/o );
}
=begin TML
---++ StaticMethod isValidEmailAddress( $name ) -> $boolean
STATIC Check for a valid email address name.
=cut
# Note: must work on tainted names.
sub isValidEmailAddress {
my ($name) = @_;
return $name =~ /^$regex{emailAddrRegex}$/;
}
=begin TML
---++ ObjectMethod getSkin () -> $string