/
Func.pm
3640 lines (2728 loc) · 112 KB
/
Func.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
=begin TML
---+ package Foswiki::Func
_Interface for Foswiki extensions developers_
This module defines the main interfaces that extensions
can use to interact with the Foswiki engine and content.
Refer to =lib/Foswiki/Plugins/EmptyPlugin.pm= for a template Plugin
and starter documentation on how to write a Plugin.
Plugins should *only* call methods in packages documented in
System.DevelopingPlugins. If you use
functions in other Foswiki libraries you risk creating a security hole, and
you will probably need to change your plugin when you upgrade Foswiki.
%TOC%
API version $Date$ (revision $Rev$)
*Since:* _date_ indicates where functions or parameters have been added since
the baseline of the API (Foswiki 1.0.0). The _date_ indicates the
earliest date of a Foswiki release that will support that function or
parameter. See Foswiki:Download.ReleaseDates for version release dates.
*Deprecated* _date_ indicates where a function or parameters has been
[[http://en.wikipedia.org/wiki/Deprecation][deprecated]]. Deprecated
functions will still work, though they should
_not_ be called in new plugins and should be replaced in older plugins
as soon as possible. Deprecated parameters are simply ignored in Foswiki
releases after _date_.
*Until* _date_ indicates where a function or parameter has been removed.
The _date_ indicates the latest date at which Foswiki releases still supported
the function or parameter.
Note that the =Foswiki::Func= API should always be the first place extension
authors look for methods. Certain other lower-level APIs are also exposed
by the core, but those APIs should only be called if there is no alternative
available through =Foswiki::Func=. The APIs in question are documented in
System.DevelopingPlugins.
=cut
# THIS PACKAGE IS PART OF THE PUBLISHED API USED BY EXTENSION AUTHORS.
# DO NOT CHANGE THE EXISTING APIS (well thought out extensions are OK)
# AND ENSURE ALL POD DOCUMENTATION IS COMPLETE AND ACCURATE.
#
# Deprecated functions should not be removed, but should be moved to to the
# deprecated functions section.
package Foswiki::Func;
use strict;
use warnings;
use Scalar::Util ();
use Error qw( :try );
use Assert;
use Foswiki ();
use Foswiki::Plugins ();
use Foswiki::Meta ();
use Foswiki::AccessControlException ();
use Foswiki::Sandbox ();
# Given $web, $web and $topic, or $web $topic and $attachment, validate
# and untaint each of them and return. If any fails to validate it will
# be returned as undef.
sub _checkWTA {
my ( $web, $topic, $attachment ) = @_;
if ( defined $topic ) {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
( $web, $topic ) =
$Foswiki::Plugins::SESSION->normalizeWebTopicName( $web, $topic );
}
if ( Scalar::Util::tainted($web) ) {
$web = Foswiki::Sandbox::untaint( $web,
\&Foswiki::Sandbox::validateWebName );
}
return ($web) unless defined $web && defined $topic;
if ( Scalar::Util::tainted($topic) ) {
$topic = Foswiki::Sandbox::untaint( $topic,
\&Foswiki::Sandbox::validateTopicName );
}
return ( $web, $topic ) unless defined $topic && defined $attachment;
if ( Scalar::Util::tainted($attachment) ) {
$attachment = Foswiki::Sandbox::untaint( $attachment,
\&Foswiki::Sandbox::validateAttachmentName );
}
return ( $web, $topic, $attachment );
}
# Validate a web.topic.attachment and throw an exception if the
# validation fails
sub _validateWTA {
my ( $web, $topic, $attachment ) = @_;
my ( $w, $t, $a ) = _checkWTA( $web, $topic, $attachment );
die 'Invalid web' if ( defined $web && !defined $w );
die 'Invalid topic' if ( defined $topic && !defined $t );
die 'Invalid attachment' if ( defined $attachment && !defined $a );
return ( $w, $t, $a );
}
=begin TML
---++ Environment
=cut
=begin TML
---+++ getSkin( ) -> $skin
Get the skin path, set by the =SKIN= and =COVER= preferences variables or the =skin= and =cover= CGI parameters
Return: =$skin= Comma-separated list of skins, e.g. ='gnu,tartan'=. Empty string if none.
=cut
sub getSkin {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->getSkin();
}
=begin TML
---+++ getUrlHost( ) -> $host
Get protocol, domain and optional port of script URL
Return: =$host= URL host, e.g. ="http://example.com:80"=
=cut
sub getUrlHost {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->{urlHost};
}
=begin TML
---+++ getScriptUrl( $web, $topic, $script, ... ) -> $url
Compose fully qualified URL
* =$web= - Web name, e.g. ='Main'=
* =$topic= - Topic name, e.g. ='WebNotify'=
* =$script= - Script name, e.g. ='view'=
* =...= - an arbitrary number of name=>value parameter pairs that will be url-encoded and added to the url. The special parameter name '#' is reserved for specifying an anchor. e.g. <tt>getScriptUrl('x','y','view','#'=>'XXX',a=>1,b=>2)</tt> will give <tt>.../view/x/y?a=1&b=2#XXX</tt>
Return: =$url= URL, e.g. ="http://example.com:80/cgi-bin/view.pl/Main/WebNotify"=
=cut
sub getScriptUrl {
my $web = shift;
my $topic = shift;
my $script = shift;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->getScriptUrl( 1, $script, $web, $topic,
@_ );
}
=begin TML
---+++ getViewUrl( $web, $topic ) -> $url
Compose fully qualified view URL
* =$web= - Web name, e.g. ='Main'=. The current web is taken if empty
* =$topic= - Topic name, e.g. ='WebNotify'=
Return: =$url= URL, e.g. ="http://example.com:80/cgi-bin/view.pl/Main/WebNotify"=
=cut
sub getViewUrl {
my ( $web, $topic ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
$web ||= $Foswiki::Plugins::SESSION->{webName}
|| $Foswiki::cfg{UsersWebName};
return getScriptUrl( $web, $topic, 'view' );
}
=begin TML
---+++ getPubUrlPath( ) -> $path
Get pub URL path
Return: =$path= URL path of pub directory, e.g. ="/pub"=
=cut
sub getPubUrlPath {
return $Foswiki::cfg{PubUrlPath};
}
=begin TML
---+++ getExternalResource( $url ) -> $response
Get whatever is at the other end of a URL (using an HTTP GET request). Will
only work for encrypted protocols such as =https= if the =LWP= CPAN module is
installed.
Note that the =$url= may have an optional user and password, as specified by
the relevant RFC. Any proxy set in =configure= is honoured.
The =$response= is an object that is known to implement the following subset of
the methods of =LWP::Response=. It may in fact be an =LWP::Response= object,
but it may also not be if =LWP= is not available, so callers may only assume
the following subset of methods is available:
| =code()= |
| =message()= |
| =header($field)= |
| =content()= |
| =is_error()= |
| =is_redirect()= |
Note that if LWP is *not* available, this function:
1 can only really be trusted for HTTP/1.0 urls. If HTTP/1.1 or another
protocol is required, you are *strongly* recommended to =require LWP=.
1 Will not parse multipart content
In the event of the server returning an error, then =is_error()= will return
true, =code()= will return a valid HTTP status code
as specified in RFC 2616 and RFC 2518, and =message()= will return the
message that was received from
the server. In the event of a client-side error (e.g. an unparseable URL)
then =is_error()= will return true and =message()= will return an explanatory
message. =code()= will return 400 (BAD REQUEST).
Note: Callers can easily check the availability of other HTTP::Response methods
as follows:
<verbatim>
my $response = Foswiki::Func::getExternalResource($url);
if (!$response->is_error() && $response->isa('HTTP::Response')) {
... other methods of HTTP::Response may be called
} else {
... only the methods listed above may be called
}
</verbatim>
=cut
sub getExternalResource {
my ($url) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
ASSERT( defined $url ) if DEBUG;
return $Foswiki::Plugins::SESSION->net->getExternalResource($url);
}
=begin TML
---+++ getRequestObject( ) -> $query
Get the request object. This is a subclass of =Foswiki::Request=. The request
object can be used to get the parameters passed to the request, either
via CGI or on the command ine (depending on how the script was called).
A =Foswiki::Request= object is largely compatible with a CPAN:CGI object.
Most of the time, documentation for that class applies directly to
=Foswiki::Request= objects as well.
Note that this method replaces =getCgiQuery= (which is a synonym for this
method). Code that is expected to run with pre-1.1 versions of Foswiki
can continue to call =getCgiQuery= for as long as necessary.
*Since:* 31 Mar 2009
=cut
sub getRequestObject {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->{request};
}
=begin TML
---+++ getSessionKeys() -> @keys
Get a list of all the names of session variables. The list is unsorted.
Session keys are stored and retrieved using =setSessionValue= and
=getSessionValue=.
=cut
sub getSessionKeys {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $hash =
$Foswiki::Plugins::SESSION->getLoginManager()->getSessionValues();
return keys %{$hash};
}
=begin TML
---+++ getSessionValue( $key ) -> $value
Get a session value from the client session module
* =$key= - Session key
Return: =$value= Value associated with key; empty string if not set
=cut
sub getSessionValue {
# my( $key ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->getLoginManager()->getSessionValue(@_);
}
=begin TML
---+++ setSessionValue( $key, $value ) -> $boolean
Set a session value.
* =$key= - Session key
* =$value= - Value associated with key
Return: true if function succeeded
=cut
sub setSessionValue {
# my( $key, $value ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
$Foswiki::Plugins::SESSION->getLoginManager()->setSessionValue(@_);
}
=begin TML
---+++ clearSessionValue( $key ) -> $boolean
Clear a session value that was set using =setSessionValue=.
* =$key= - name of value stored in session to be cleared. Note that
you *cannot* clear =AUTHUSER=.
Return: true if the session value was cleared
=cut
sub clearSessionValue {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->getLoginManager()->clearSessionValue(@_);
}
=begin TML
---+++ getContext() -> \%hash
Get a hash of context identifiers representing the currently active
context.
The context is a set of identifiers that are set
during specific phases of processing. For example, each of
the standard scripts in the 'bin' directory each has a context
identifier - the view script has 'view', the edit script has 'edit'
etc. So you can easily tell what 'type' of script your Plugin is
being called within. The core context identifiers are listed
in the %SYSTEMWEB%.IfStatements topic. Please be careful not to
overwrite any of these identifiers!
Context identifiers can be used to communicate between Plugins, and between
Plugins and templates. For example, in FirstPlugin.pm, you might write:
<verbatim>
sub initPlugin {
Foswiki::Func::getContext()->{'MyID'} = 1;
...
</verbatim>
This can be used in !SecondPlugin.pm like this:
<verbatim>
sub initPlugin {
if( Foswiki::Func::getContext()->{'MyID'} ) {
...
}
...
</verbatim>
or in a template, like this:
<verbatim>
%TMPL:DEF{"ON"}% Not off %TMPL:END%
%TMPL:DEF{"OFF"}% Not on %TMPL:END%
%TMPL:P{context="MyID" then="ON" else="OFF"}%
</verbatim>
or in a topic:
<verbatim>
%IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%
</verbatim>
__Note__: *all* plugins have an *automatically generated* context identifier
if they are installed and initialised. For example, if the FirstPlugin is
working, the context ID 'FirstPlugin' will be set.
=cut
sub getContext {
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return $Foswiki::Plugins::SESSION->{context};
}
=begin TML
---+++ pushTopicContext($web, $topic)
* =$web= - new web
* =$topic= - new topic
Change the Foswiki context, adding the requested =$web.$topic= onto the
preferences stack. Any preferences found in =$web.$topic= will be used
in place of preferences previously set in the stack, provided that they
were not finalized in a lower level. Preferences set in the prior
=web.topic= are *not* cleared. =$web.$topic= replaces and adds to
preferences but does not remove preferences that it does not set.
Note that if the new topic is not readable by the logged in user due to
access control considerations, there will *not* be an exception. It is the
duty of the caller to check access permissions before changing the topic.
All other errors will throw an exception.
It is the duty of the caller to restore the original context by calling
=popTopicContext=.
Note that this call does *not* re-initialise plugins, so if you have used
global variables to remember the web and topic in =initPlugin=, then those
values will be unchanged.
=cut
sub pushTopicContext {
my $session = $Foswiki::Plugins::SESSION;
ASSERT($session) if DEBUG;
my ( $web, $topic ) = _validateWTA(@_);
$session->{prefs}->pushTopicContext( $web, $topic );
$session->{webName} = $web;
$session->{topicName} = $topic;
$session->{prefs}->setInternalPreferences(
BASEWEB => $web,
BASETOPIC => $topic,
INCLUDINGWEB => $web,
INCLUDINGTOPIC => $topic
);
}
=begin TML
---+++ popTopicContext()
Returns the Foswiki context to the state it was in before the
=pushTopicContext= was called.
=cut
sub popTopicContext {
my $session = $Foswiki::Plugins::SESSION;
ASSERT($session) if DEBUG;
( $session->{webName}, $session->{topicName} ) =
$session->{prefs}->popTopicContext();
}
=begin TML
---++ Registering extensions
Plugins work either by using handlers to manipulate the text being processed,
or by registering extensions, such as new macros, scripts, or meta-data types.
=cut
=begin TML=
---+++ registerTagHandler( $var, \&fn, $syntax )
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %<nop>VAR% and
%<nop>VAR{...}%. Registered variables are treated the same as internal macros,
and are expanded at the same time. This is a _lot_ more efficient than using the =commonTagsHandler=.
* =$var= - The name of the variable, i.e. the 'MYVAR' part of %<nop>MYVAR%.
The variable name *must* match /^[A-Z][A-Z0-9_]*$/ or it won't work.
* =\&fn= - Reference to the handler function.
* =$syntax= can be 'classic' (the default) or 'context-free'. (context-free may be removed in future)
'classic' syntax is appropriate where you want the variable to support classic syntax
i.e. to accept the standard =%<nop>MYVAR{ "unnamed" param1="value1" param2="value2" }%= syntax,
as well as an unquoted default parameter, such as =%<nop>MYVAR{unquoted parameter}%=.
If your variable will only use named parameters, you can use 'context-free' syntax,
which supports a more relaxed syntax. For example,
%MYVAR{param1=value1, value 2, param3="value 3", param4='value 5"}%
The variable handler function must be of the form:
<verbatim>
sub handler(\%session, \%params, $topic, $web, $topicObject)
</verbatim>
where:
* =\%session= - a reference to the session object (may be ignored)
* =\%params= - a reference to a Foswiki::Attrs object containing parameters. This can be used as a simple hash that maps parameter names to values, with _DEFAULT being the name for the default parameter.
* =$topic= - name of the topic in the query
* =$web= - name of the web in the query
* =$topicObject= - is the Foswiki::Meta object for the topic *Since* 2009-03-06
for example, to execute an arbitrary command on the server, you might do this:
<verbatim>
sub initPlugin{
Foswiki::Func::registerTagHandler('EXEC', \&boo);
}
sub boo {
my( $session, $params, $topic, $web, $topicObject ) = @_;
my $cmd = $params->{_DEFAULT};
return "NO COMMAND SPECIFIED" unless $cmd;
my $result = `$cmd 2>&1`;
return $params->{silent} ? '' : $result;
}
</verbatim>
would let you do this:
=%<nop>EXEC{"ps -Af" silent="on"}%=
Registered tags differ from tags implemented using the old approach (text substitution in =commonTagsHandler=) in the following ways:
* registered tags are evaluated at the same time as system tags, such as %SERVERTIME. =commonTagsHandler= is only called later, when all system tags have already been expanded (though they are expanded _again_ after =commonTagsHandler= returns).
* registered tag names can only contain alphanumerics and _ (underscore)
* registering a tag =FRED= defines both =%<nop>FRED{...}%= *and also* =%FRED%=.
* registered tag handlers *cannot* return another tag as their only result (e.g. =return '%<nop>SERVERTIME%';=). It won't work.
=cut
sub registerTagHandler {
my ( $tag, $function, $syntax ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
# $pluginContext is undefined if a contrib registers a tag handler.
my $pluginContext;
if ( caller =~ m/^Foswiki::Plugins::(\w+)/ ) {
$pluginContext = $1 . 'Enabled';
}
# Use an anonymous function so it gets inlined at compile time.
# Make sure we don't mangle the session reference.
Foswiki::registerTagHandler(
$tag,
sub {
my ( $session, $params, $topicObject ) = @_;
my $record = $Foswiki::Plugins::SESSION;
$Foswiki::Plugins::SESSION = $_[0];
# $pluginContext is defined for all plugins
# but never defined for contribs.
# This is convenient, because contribs cannot be disabled
# at run-time, either.
if ( defined $pluginContext ) {
# Registered tag handlers should only be called if the plugin
# is enabled. Disabled plugins can still have tag handlers
# registered in persistent environments (e.g. modperl)
# and also for rest handlers that disable plugins.
# See Item1871
return unless $session->inContext($pluginContext);
}
# Compatibility; expand $topicObject to the topic and web
my $result =
&$function( $session, $params, $topicObject->topic,
$topicObject->web, $topicObject );
$Foswiki::Plugins::SESSION = $record;
return $result;
},
$syntax
);
}
=begin TML=
---+++ registerRESTHandler( $alias, \&fn, %options )
Should only be called from initPlugin.
Adds a function to the dispatch table of the REST interface
* =$alias= - The name .
* =\&fn= - Reference to the function.
* =%options= - additional options affecting the handler
The handler function must be of the form:
<verbatim>
sub handler(\%session)
</verbatim>
where:
* =\%session= - a reference to the Foswiki session object (may be ignored)
From the REST interface, the name of the plugin must be used
as the subject of the invokation.
Additional options are set in the =%options= hash. These options are important
to ensuring that requests to your handler can't be used in cross-scripting
attacks, or used for phishing.
* =authenticate= - use this boolean option to require authentication for the
handler. If this is set, then an authenticated session must be in place
or the REST call will be rejected with a 401 (Unauthorized) status code.
By default, rest handlers do *not* require authentication.
* =validate= - use this boolean option to require validation of any requests
made to this handler. Validation is the process by which a secret key
is passed to the server so it can identify the origin of the request.
By default, requests made to REST handlers are not validated.
* =http_allow= use this option to specify that the HTTP methods that can
be used to invoke the handler. For example, =http_allow=>'POST,GET'= will
constrain the handler to be invoked using POST and GET, but not other
HTTP methods, such as DELETE. Normally you will use http_allow=>'POST'.
Together with authentication this is an important security tool.
Handlers that can be invoked using GET are vulnerable to being called
in the =src= parameter of =img= tags, a common method for cross-site
request forgery (CSRF) attacks. This option is set automatically if
=authenticate= is specified.
---++++ Example
The EmptyPlugin has the following call in the initPlugin handler:
<verbatim>
Foswiki::Func::registerRESTHandler('example', \&restExample,
http_allow=>'GET,POST');
</verbatim>
This adds the =restExample= function to the REST dispatch table
for the EmptyPlugin under the 'example' alias, and allows it
to be invoked using the URL
=http://server:port/bin/rest/EmptyPlugin/example=
note that the URL
=http://server:port/bin/rest/EmptyPlugin/restExample=
(ie, with the name of the function instead of the alias) will not work.
---++++ Calling REST handlers from the command-line
The =rest= script allows handlers to be invoked from the command line. The
script is invoked passing the parameters as described in CommandAndCGIScripts.
If the handler requires authentication ( =authenticate=>1= ) then this can
be passed in the username and =password= parameters.
For example,
=perl -wT rest /EmptyPlugin/example -username HughPugh -password trumpton=
=cut
sub registerRESTHandler {
my ( $alias, $function, %options ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $plugin = caller;
$plugin =~ s/.*:://; # strip off Foswiki::Plugins:: prefix
# Use an anonymous function so it gets inlined at compile time.
# Make sure we don't mangle the session reference.
require Foswiki::UI::Rest;
Foswiki::UI::Rest::registerRESTHandler(
$plugin, $alias,
sub {
my $record = $Foswiki::Plugins::SESSION;
$Foswiki::Plugins::SESSION = $_[0];
my $result = &$function(@_);
$Foswiki::Plugins::SESSION = $record;
return $result;
},
%options
);
}
=begin TML
---+++ registerMETA($macro, $spec)
Deprecated: please use Foswiki::Meta::registerMETA instead.
=cut
sub registerMETA {
#my ( $macro, %spec ) = @_;
Foswiki::Meta::registerMETA( @_ )
}
=begin TML
---++ Preferences
=cut
=begin TML
---+++ getPreferencesValue( $key, $web ) -> $value
Get a preferences value for the currently requested context, from the currently request topic, its web and the site.
* =$key= - Preference name
* =$web= - Name of web, optional. if defined, we shortcircuit to the WebPreferences (and its Sitewide defaults)
Return: =$value= Preferences value; empty string if not set
* Example for preferences setting:
* WebPreferences topic has: =* Set WEBBGCOLOR = #FFFFC0=
* =my $webColor = Foswiki::Func::getPreferencesValue( 'WEBBGCOLOR', 'Sandbox' );=
* Example for MyPlugin setting:
* if the %SYSTEMWEB%.MyPlugin topic has: =* Set COLOR = red=
* Use ="MYPLUGIN_COLOR"= for =$key=
* =my $color = Foswiki::Func::getPreferencesValue( "MYPLUGIN_COLOR" );=
*NOTE:* If =$NO_PREFS_IN_TOPIC= is enabled in the plugin, then
preferences set in the plugin topic will be ignored.
=cut
sub getPreferencesValue {
my ( $key, $web ) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
if ($web) {
$web = _checkWTA($web);
return undef unless defined $web;
# Web preference
my $webObject = Foswiki::Meta->new( $Foswiki::Plugins::SESSION, $web );
return $webObject->getPreference($key);
}
else {
# Global preference
return $Foswiki::Plugins::SESSION->{prefs}->getPreference($key);
}
}
=begin TML
---+++ getPluginPreferencesValue( $key ) -> $value
Get a preferences value from your Plugin
* =$key= - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return: =$value= Preferences value; empty string if not set
__Note__: This function will will *only* work when called from the Plugin.pm file itself. it *will not work* if called from a sub-package (e.g. Foswiki::Plugins::MyPlugin::MyModule)
*NOTE:* If =$NO_PREFS_IN_TOPIC= is enabled in the plugin, then
preferences set in the plugin topic will be ignored.
=cut
sub getPluginPreferencesValue {
my ($key) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $package = caller;
$package =~ s/.*:://; # strip off Foswiki::Plugins:: prefix
return $Foswiki::Plugins::SESSION->{prefs}
->getPreference("\U$package\E_$key");
}
=begin TML
---+++ getPreferencesFlag( $key, $web ) -> $value
Get a preferences flag from Foswiki or from a Plugin
* =$key= - Preferences key
* =$web= - Name of web, optional. Current web if not specified; does not apply to settings of Plugin topics
Return: =$value= Preferences flag ='1'= (if set), or ="0"= (for preferences values ="off"=, ="no"= and ="0"=)
* Example for Plugin setting:
* MyPlugin topic has: =* Set SHOWHELP = off=
* Use ="MYPLUGIN_SHOWHELP"= for =$key=
* =my $showHelp = Foswiki::Func::getPreferencesFlag( "MYPLUGIN_SHOWHELP" );=
*NOTE:* If =$NO_PREFS_IN_TOPIC= is enabled in the plugin, then
preferences set in the plugin topic will be ignored.
=cut
sub getPreferencesFlag {
# my( $key, $web ) = @_;
my $t = getPreferencesValue(@_);
return Foswiki::isTrue($t);
}
=begin TML
---+++ getPluginPreferencesFlag( $key ) -> $boolean
Get a preferences flag from your Plugin
* =$key= - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return: false for preferences values ="off"=, ="no"= and ="0"=, or values not set at all. True otherwise.
__Note__: This function will will *only* work when called from the Plugin.pm file itself. it *will not work* if called from a sub-package (e.g. Foswiki::Plugins::MyPlugin::MyModule)
*NOTE:* If =$NO_PREFS_IN_TOPIC= is enabled in the plugin, then
preferences set in the plugin topic will be ignored.
=cut
sub getPluginPreferencesFlag {
my ($key) = @_;
my $package = caller;
$package =~ s/.*:://; # strip off Foswiki::Plugins:: prefix
return getPreferencesFlag("\U$package\E_$key");
}
=begin TML
---+++ setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and =%$name%= will expand to the preference when used in
future variable expansions.
The preference only persists for the rest of this request. Finalised
preferences cannot be redefined using this function.
=cut
sub setPreferencesValue {
my ( $name, $value ) = @_;
return $Foswiki::Plugins::SESSION->{prefs}
->setSessionPreferences( $name => $value );
}
=begin TML
---++ User Handling and Access Control
---+++ getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as =DefaultUserLogin=
Return: =$loginName= Default user name, e.g. ='guest'=
=cut
sub getDefaultUserName {
return $Foswiki::cfg{DefaultUserLogin};
}
=begin TML
---+++ getCanonicalUserID( $user ) -> $cUID
* =$user= can be a login, wikiname or web.wikiname
Return the cUID of the specified user. A cUID is a unique identifier which
is assigned by Foswiki for each user.
BEWARE: While the default TopicUserMapping uses a cUID that looks like a user's
LoginName, some characters are modified to make them compatible with rcs.
Other usermappings may use other conventions - the !JoomlaUserMapping
for example, has cUIDs like 'JoomlaeUserMapping_1234'.
If $user is undefined, it assumes the currently logged-in user.
Return: =$cUID=, an internal unique and portable escaped identifier for
registered users. This may be autogenerated for an authenticated but
unregistered user.
=cut
sub getCanonicalUserID {
my $user = shift;
return $Foswiki::Plugins::SESSION->{user} unless ($user);
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $cUID;
if ($user) {
$cUID = $Foswiki::Plugins::SESSION->{users}->getCanonicalUserID($user);
if ( !$cUID ) {
# Not a login name or a wiki name. Is it a valid cUID?
my $ln = $Foswiki::Plugins::SESSION->{users}->getLoginName($user);
$cUID = $user if defined $ln && $ln ne 'unknown';
}
}
else {
$cUID = $Foswiki::Plugins::SESSION->{user};
}
return $cUID;
}
=begin TML
---+++ getWikiName( $user ) -> $wikiName
return the WikiName of the specified user
if $user is undefined Get Wiki name of logged in user
* $user can be a cUID, login, wikiname or web.wikiname
Return: =$wikiName= Wiki Name, e.g. ='JohnDoe'=
=cut
sub getWikiName {
my $user = shift;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $cUID = getCanonicalUserID($user);
unless ( defined $cUID ) {
my ( $w, $u ) =
normalizeWebTopicName( $Foswiki::cfg{UsersWebName}, $user );
return $u;
}
return $Foswiki::Plugins::SESSION->{users}->getWikiName($cUID);
}
=begin TML
---+++ getWikiUserName( $user ) -> $wikiName
return the userWeb.WikiName of the specified user
if $user is undefined Get Wiki name of logged in user
* $user can be a cUID, login, wikiname or web.wikiname
Return: =$wikiName= Wiki Name, e.g. ="Main.JohnDoe"=
=cut
sub getWikiUserName {
my $user = shift;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $cUID = getCanonicalUserID($user);
unless ( defined $cUID ) {
my ( $w, $u ) =
normalizeWebTopicName( $Foswiki::cfg{UsersWebName}, $user );
return "$w.$u";
}
return $Foswiki::Plugins::SESSION->{users}->webDotWikiName($cUID);
}
=begin TML
---+++ wikiToUserName( $id ) -> $loginName
Translate a Wiki name to a login name.
* =$id= - Wiki name, e.g. ='Main.JohnDoe'= or ='JohnDoe'=.
$id may also be a login name. This will normally
be transparent, but should be borne in mind if you have login names
that are also legal wiki names.
Return: =$loginName= Login name of user, e.g. ='jdoe'=, or undef if not
matched.
Note that it is possible for several login names to map to the same wikiname.
This function will only return the *first* login name that maps to the
wikiname.
returns undef if the WikiName is not found.
=cut
sub wikiToUserName {
my ($wiki) = @_;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
return '' unless $wiki;
my $cUID = getCanonicalUserID($wiki);
if ($cUID) {
my $login = $Foswiki::Plugins::SESSION->{users}->getLoginName($cUID);
return if !$login || $login eq 'unknown';
return $login;
}
return;
}
=begin TML
---+++ userToWikiName( $loginName, $dontAddWeb ) -> $wikiName
Translate a login name to a Wiki name
* =$loginName= - Login name, e.g. ='jdoe'=. This may
also be a wiki name. This will normally be transparent, but may be
relevant if you have login names that are also valid wiki names.
* =$dontAddWeb= - Do not add web prefix if ="1"=
Return: =$wikiName= Wiki name of user, e.g. ='Main.JohnDoe'= or ='JohnDoe'=
userToWikiName will always return a name. If the user does not
exist in the mapping, the $loginName parameter is returned. (backward compatibility)
=cut
sub userToWikiName {
my ( $login, $dontAddWeb ) = @_;
return '' unless $login;
ASSERT($Foswiki::Plugins::SESSION) if DEBUG;
my $users = $Foswiki::Plugins::SESSION->{users};
my $user = getCanonicalUserID($login);
return (
$dontAddWeb
? $login
: ( $Foswiki::cfg{UsersWebName} . '.' . $login )
) unless $user and $users->userExists($user);
return $users->getWikiName($user) if $dontAddWeb;
return $users->webDotWikiName($user);
}
=begin TML
---+++ emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
* =$email= - email address to look up
* =$dontAddWeb= - Do not add web prefix if ="1"=
Find the wikinames of all users who have the given email address as their
registered address. Since several users could register with the same email
address, this returns a list of wikinames rather than a single wikiname.