<<O>> Difference Topic TWikiFuncDotPm (19 - 2018-07-16 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getExternalResource( $url, \@headers, \%params ) -> $response
Get whatever is at the other end of a URL (using an HTTP GET request). Will
only work for encrypted protocols such as
Note that the Optional parameters may be supplied:
Below is the list of available
LWP .
Example: my $response = getExternalResource($url, ['Cache-Control' => 'max-age=0'], {timeout => 10});
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { $text = $response->content(); # ... other methods of HTTP::Response may be called } else { # ... only the methods listed above may be called } Since: TWiki::Plugins::VERSION 1.2 Note: The optional parameters \@headers and \%params were added in TWiki::Plugins::VERSION 6.00
postExternalResource( $url, $text, \@headers, \%params ) -> $response
This method is essentially the same as
The
See Since: TWiki::Plugins::VERSION 6.00
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ); # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK.
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a %TMPL:P{$def}%, only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
$viaCache
- forcibly cache a redirect CGI query. It cuts off all the params in a GET url and replace with a "?$cache=..." param. "$viaCache" is meaningful only if "$passthru" is true.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript and custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on. Those blocks will be loaded first.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
$web
- name of web, optional
$topic
- name of topic, optional
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandCommonVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Should only be called from initPlugin.
Adds a function to modify all the HTTP requests to any external resources.
\&fn
- Reference to the function.
The handler function must be of the form:
sub handler(\%session, $url) -> (\@headers, \%params)where:
\%session
- a reference to the TWiki session object (may be ignored)
$url
- a URL being requested
The returned \@headers
and \%params
are added to the request in the same
manner as getExternalResource
, except that \%params
will not override any
entries that have been set earlier.
All the params explicitly given by the caller of getExternalResource
or
postExternalResource
will have the highest precedence.
Example:
sub initPlugin { TWiki::Func::registerExternalHTTPHandler( \&handleExternalHTTPRequest ); } sub handleExternalHTTPRequest { my ($session, $url) = @_; my @headers; my %params; # Add any necessary @headers and %params push @headers, 'X-Example-Header' => 'Value'; $params{timeout} = 5; # Return refs to both return (\@headers, \%params); }
Since: TWiki::Plugins::VERSION 6.00
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$aquot |
Apostrophe quote (' ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
$lt |
Less than sign (< ) |
$gt |
Greater than sign (> ) |
Note that $quot, $aquot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
The following functions are for ReadOnlyAndMirrorWebs.
Returns the current site name if it's defined. Otherwise returns the null string.
Returns the content mode of the specified $web. Please read ReadOnlyAndMirrorWebs about content mode.
Since: TWiki::Plugins::VERSION 6.00
Checks if the web is wriable on this site - if it's master or local. Returns true if it's writable. Returns false otherwise.
Since: TWiki::Plugins::VERSION 6.00
The following functions are for UsingMultipleDisks.
Returns IDs of disks used by TWiki. An disk ID is "" (a null string) or a decimal number without leading 0.
Since: TWiki::Plugins::VERSION 6.00
Returns the relevant paths and the disk ID of the specified web on the specified site.
Since: TWiki::Plugins::VERSION 6.00
Returns the name of the trash web to which topics of the $web
web are moved.
Or returns the name of the trash web of the specified disk.
Each disk (file system) TWiki uses needs to have a trash web since a topic deletion may entail an attachment directory move, which is possible only within the same disk/file system.
Since: TWiki::Plugins::VERSION 6.00
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (Web.SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string between each word component. Word component boundaries are transitions from lowercase to uppercase or numeric, from numeric to uppercase or lowercase, and from uppercase to numeric characters.
Parameter $sep defines the separator between the word components, the default is a space.
Example: "ABC2015ProjectCharter" results in "ABC 2015 Project Charter"
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName, login name or cUID of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( 'myevent', $extra, $web, $topic ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '2014-12-31 - 19:30'
. Can be '$iso'
(e.g. '2014-12-31T19:30Z'
), '$rcs'
(e.g. '2014/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'The, 2014-07-23 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: If you used the removed formatGmTime, add a third parameter 'gmtime'
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string.
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
Note: Function TWiki::Func::extractParameters is more efficient for extracting several parameters
Entity encode text.
$text
- Text to encode, may be empty
$extra
- Additional characters to include in the set of encoded characters, optional
$text
Entity encoded text
Since: TWiki::Plugins::VERSION 6.00
Escape special characters to HTML numeric entities. This is not a generic encoding, it is tuned specifically for use in TWiki.
HTML4.0 spec: "Certain characters in HTML are reserved for use as markup and must be escaped to appear literally. The "<" character may be represented with an entity, <. Similarly, ">" is escaped as >, and "&" is escaped as &. If an attribute value contains a double quotation mark and is delimited by double quotation marks, then the quote should be escaped as ".
Other entities exist for special characters that cannot easily be entered with some keyboards..."
This method encodes HTML special and any non-printable ASCII characters (except for \n and \r) using numeric entities.
FURTHER this method also encodes characters that are special in TWiki meta-language.
$extras is an optional param that may be used to include additional characters in the set of encoded characters. It should be a string containing the additional chars.
Decode all numeric entities (e.g. {). Does not decode named entities such as & (use HTML::Entities for that)
$text
- Text to decode, may be empty
$text
Entity decoded text
Since: TWiki::Plugins::VERSION 6.00
URL encode text, mainly used to encode URL parameters.
$text
- Text to encode, may be empty
$text
URL encoded text
Since: TWiki::Plugins::VERSION 6.00
Encoding is done by converting characters that are illegal in URLs to their %NN equivalents. This method is used for encoding strings that must be embedded verbatim in URLs; it cannot be applied to URLs themselves, as it escapes reserved characters such as = and ?.
RFC 1738, Dec. '94:
...Only alphanumerics [0-9a-zA-Z], the special characters $-_.+!*'(), and reserved characters used for their reserved purposes may be used unencoded within a URL.
Reserved characters are $&+,/:;=?@ - these are also encoded by this method.
This URL-encoding handles all character encodings including ISO-8859-*, KOI8-R, EUC-* and UTF-8.
This may not handle EBCDIC properly, as it generates an EBCDIC URL-encoded URL, but mainframe web servers seem to translate this outbound before it hits browser - see CGI::Util::escape for another approach.
URL decode text, mainly used to decode URL parameters.
$text
- Text to decode, may be empty
$text
URL decoded text
Since: TWiki::Plugins::VERSION 6.00
You may want to have an external program write to the debug file. This function returns the path to it. An external program may corrupt the debug file, but that's no big deal -- it's a debug file.
The return value is $TWiki::cfg{DebugFileName}
with %DATE%
and other "variables" resolved. $TWiki::cfg{DebugFileName}
is an
absolute path in most cases. If it's not, then the current directory
is prepended in the return value.
Since: TWiki::Plugins::VERSION 6.10
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
viewRedirectHandler( $session, $web, $topic )
isAnAdmin( $user, $topic, $web ) -> $boolean
-- added $topic
and $web
expandVariablesOnTopicCreation( $text, $web, $topic ) -> $text
-- added $web
and $topic
postExternalResource( $url, $text, \@headers, \%params ) -> $response
registerExternalHTTPHandler( \&fn )
getContentMode( $web ) -> $contentMode
webWritable( $web ) -> $boolean
getDiskList() -> @diskIDs
getDiskInfo($web, $siteName) -> ($dataDir, $pubDir, $diskID)
trashWebName(web => $web | disk => $diskID) -> $trashWebName
entityEncode( $text, $extra ) -> $text
entityDecode( $text ) -> $text
urlEncode( $text ) -> $text
urlDecode( $text ) -> $text
viewFileRedirectHandler( $session, $web, $topic )
topicTitleHandler( $session, $web, $topic, $titleRef )
getDebugFilePath() -> $path
<<O>> Difference Topic TWikiFuncDotPm (18 - 2015-11-29 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getExternalResource( $url, \@headers, \%params ) -> $response
Get whatever is at the other end of a URL (using an HTTP GET request). Will
only work for encrypted protocols such as
Note that the Optional parameters may be supplied:
Below is the list of available
LWP .
Example: my $response = getExternalResource($url, ['Cache-Control' => 'max-age=0'], {timeout => 10});
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { $text = $response->content(); # ... other methods of HTTP::Response may be called } else { # ... only the methods listed above may be called } Since: TWiki::Plugins::VERSION 1.2 Note: The optional parameters \@headers and \%params were added in TWiki::Plugins::VERSION 6.00
postExternalResource( $url, $text, \@headers, \%params ) -> $response
This method is essentially the same as
The
See Since: TWiki::Plugins::VERSION 6.00
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | return the WikiName of the specified user if $user is undefined Get Wiki name of logged in user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Return the WikiName of the specified user. If $user is undefined get Wiki name of logged-in user. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $user ) -> $wikiName | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | return the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Return the userWeb.WikiName of the specified user. If $user is undefined get Wiki name of logged-in user. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since TWiki 4.2.1, $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: 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. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | returns undef if the WikiName is not found. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Returns undef if the WikiName is not found. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | To get the login name of the currently logged in user use:
my $user = TWiki::Func::wikiToUserName( TWiki::Func::getWikiName() ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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.
Since: TWiki::Plugins::VERSION 1.2
@em | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns the registered email addresses of the named user. If $user is
undef, returns the registered email addresses for the logged-in user.
Since TWiki 4.2.1, $user may also be a login name, or the name of a group. Since: TWiki::Plugins::VERSION 1.2
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isAnAdmin( $user, $topic, $web ) -> $booleanFind out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed.
Since: TWiki::Plugins::VERSION 1.2 Note: The parameters $topic and $web were added in TWiki::Plugins::VERSION 6.00
isGroupMember( $group, $id ) -> $booleanFind out if $id is in the named group. e.g. if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If $user is undef , it defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
eachUser() -> $iteratorGet an iterator over the list of all the registered users not including groups. The iterator will return each wiki name in turn (e.g. 'FredBloggs').Use it as follows: my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
eachMembership($id) -> $iterator
Since: TWiki::Plugins::VERSION 1.2
eachGroup() -> $iteratorGet an iterator over all groups.Use it as follows: my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
isGroup( $group ) -> $boolean
Checks if
eachGroupMember($group) -> $iteratorGet an iterator over all the members of the named group. Returns undef if $group is not a valid group.Use it as follows: my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
checkAccessPermission( $type, $id, $text, $topic, $web, $meta ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Note the weird parameter order is due to compatibility constraints with earlier TWiki releases. Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic , then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true .
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ); # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK.
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a %TMPL:P{$def}%, only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
$viaCache
- forcibly cache a redirect CGI query. It cuts off all the params in a GET url and replace with a "?$cache=..." param. "$viaCache" is meaningful only if "$passthru" is true.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript and custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on. Those blocks will be loaded first.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
$web
- name of web, optional
$topic
- name of topic, optional
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandCommonVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Should only be called from initPlugin.
Adds a function to modify all the HTTP requests to any external resources.
\&fn
- Reference to the function.
The handler function must be of the form:
sub handler(\%session, $url) -> (\@headers, \%params)where:
\%session
- a reference to the TWiki session object (may be ignored)
$url
- a URL being requested
The returned \@headers
and \%params
are added to the request in the same
manner as getExternalResource
, except that \%params
will not override any
entries that have been set earlier.
All the params explicitly given by the caller of getExternalResource
or
postExternalResource
will have the highest precedence.
Example:
sub initPlugin { TWiki::Func::registerExternalHTTPHandler( \&handleExternalHTTPRequest ); } sub handleExternalHTTPRequest { my ($session, $url) = @_; my @headers; my %params; # Add any necessary @headers and %params push @headers, 'X-Example-Header' => 'Value'; $params{timeout} = 5; # Return refs to both return (\@headers, \%params); }
Since: TWiki::Plugins::VERSION 6.00
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$aquot |
Apostrophe quote (' ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
$lt |
Less than sign (< ) |
$gt |
Greater than sign (> ) |
Note that $quot, $aquot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
The following functions are for ReadOnlyAndMirrorWebs.
Returns the current site name if it's defined. Otherwise returns the null string.
Returns the content mode of the specified $web. Please read ReadOnlyAndMirrorWebs about content mode.
Since: TWiki::Plugins::VERSION 6.00
Checks if the web is wriable on this site - if it's master or local. Returns true if it's writable. Returns false otherwise.
Since: TWiki::Plugins::VERSION 6.00
The following functions are for UsingMultipleDisks.
Returns IDs of disks used by TWiki. An disk ID is "" (a null string) or a decimal number without leading 0.
Since: TWiki::Plugins::VERSION 6.00
Returns the relevant paths and the disk ID of the specified web on the specified site.
Since: TWiki::Plugins::VERSION 6.00
Returns the name of the trash web to which topics of the $web
web are moved.
Or returns the name of the trash web of the specified disk.
Each disk (file system) TWiki uses needs to have a trash web since a topic deletion may entail an attachment directory move, which is possible only within the same disk/file system.
Since: TWiki::Plugins::VERSION 6.00
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (Web.SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Example: "ABC2015ProjectCharter" results in "ABC 2015 Project Charter"
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName, login name or cUID of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( 'myevent', $extra, $web, $topic ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '2014-12-31 - 19:30'
. Can be '$iso'
(e.g. '2014-12-31T19:30Z'
), '$rcs'
(e.g. '2014/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'The, 2014-07-23 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: If you used the removed formatGmTime, add a third parameter 'gmtime'
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string.
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
Note: Function TWiki::Func::extractParameters is more efficient for extracting several parameters
Entity encode text.
$text
- Text to encode, may be empty
$extra
- Additional characters to include in the set of encoded characters, optional
$text
Entity encoded text
Since: TWiki::Plugins::VERSION 6.00
Escape special characters to HTML numeric entities. This is not a generic encoding, it is tuned specifically for use in TWiki.
HTML4.0 spec: "Certain characters in HTML are reserved for use as markup and must be escaped to appear literally. The "<" character may be represented with an entity, <. Similarly, ">" is escaped as >, and "&" is escaped as &. If an attribute value contains a double quotation mark and is delimited by double quotation marks, then the quote should be escaped as ".
Other entities exist for special characters that cannot easily be entered with some keyboards..."
This method encodes HTML special and any non-printable ASCII characters (except for \n and \r) using numeric entities.
FURTHER this method also encodes characters that are special in TWiki meta-language.
$extras is an optional param that may be used to include additional characters in the set of encoded characters. It should be a string containing the additional chars.
Decode all numeric entities (e.g. {). Does not decode named entities such as & (use HTML::Entities for that)
$text
- Text to decode, may be empty
$text
Entity decoded text
Since: TWiki::Plugins::VERSION 6.00
URL encode text, mainly used to encode URL parameters.
$text
- Text to encode, may be empty
$text
URL encoded text
Since: TWiki::Plugins::VERSION 6.00
Encoding is done by converting characters that are illegal in URLs to their %NN equivalents. This method is used for encoding strings that must be embedded verbatim in URLs; it cannot be applied to URLs themselves, as it escapes reserved characters such as = and ?.
RFC 1738, Dec. '94:
...Only alphanumerics [0-9a-zA-Z], the special characters $-_.+!*'(), and reserved characters used for their reserved purposes may be used unencoded within a URL.
Reserved characters are $&+,/:;=?@ - these are also encoded by this method.
This URL-encoding handles all character encodings including ISO-8859-*, KOI8-R, EUC-* and UTF-8.
This may not handle EBCDIC properly, as it generates an EBCDIC URL-encoded URL, but mainframe web servers seem to translate this outbound before it hits browser - see CGI::Util::escape for another approach.
URL decode text, mainly used to decode URL parameters.
$text
- Text to decode, may be empty
$text
URL decoded text
Since: TWiki::Plugins::VERSION 6.00
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
viewRedirectHandler( $session, $web, $topic )
isAnAdmin( $user, $topic, $web ) -> $boolean
-- added $topic
and $web
expandVariablesOnTopicCreation( $text, $web, $topic ) -> $text
-- added $web
and $topic
postExternalResource( $url, $text, \@headers, \%params ) -> $response
registerExternalHTTPHandler( \&fn )
getContentMode( $web ) -> $contentMode
webWritable( $web ) -> $boolean
getDiskList() -> @diskIDs
getDiskInfo($web, $siteName) -> ($dataDir, $pubDir, $diskID)
trashWebName(web => $web | disk => $diskID) -> $trashWebName
entityEncode( $text, $extra ) -> $text
entityDecode( $text ) -> $text
urlEncode( $text ) -> $text
urlDecode( $text ) -> $text
viewFileRedirectHandler( $session, $web, $topic )
topicTitleHandler( $session, $web, $topic, $titleRef )
<<O>> Difference Topic TWikiFuncDotPm (17 - 2014-10-05 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getExternalResource( $url, \@headers, \%params ) -> $response
Get whatever is at the other end of a URL (using an HTTP GET request). Will
only work for encrypted protocols such as
Note that the Optional parameters may be supplied:
Below is the list of available
LWP .
Example: my $response = getExternalResource($url, ['Cache-Control' => 'max-age=0'], {timeout => 10});
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { $text = $response->content(); # ... other methods of HTTP::Response may be called } else { # ... only the methods listed above may be called } Since: TWiki::Plugins::VERSION 1.2 Note: The optional parameters \@headers and \%params were added in TWiki::Plugins::VERSION 6.00
postExternalResource( $url, $text, \@headers, \%params ) -> $response
This method is essentially the same as
The
See Since: TWiki::Plugins::VERSION 6.00
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | working, the context ID 'FirstPlugin' will be set. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | working, the context ID 'FirstPluginEnabled' will be set. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.1
pushTopicContext($web, $topic)
$web.$topic
from now on. All the preferences will be reset to those of the new topic.
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.
It is the duty of the caller to restore the original context by calling
Note that this call does not re-initialise plugins, so if you have used
global variables to remember the web and topic in Since: TWiki::Plugins::VERSION 1.2
popTopicContext()
Returns the TWiki context to the state it was in before the
Since: TWiki::Plugins::VERSION 1.2
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki-4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki-4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki-4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki-4.1, if
setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function. Returns 1 if the preference was defined, and 0 otherwise.
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access ControlgetDefaultUserName( ) -> $loginNameGet default user name as defined in the configuration asDefaultUserLogin
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getCanonicalUserID( $user ) -> $cUID
If $user is undefined, it assumes the currently logged-in user.
Return: Since: TWiki::Plugins::VERSION 1.2
getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
Return: 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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
$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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2
@em |
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic:
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK.
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a %TMPL:P{$def}%, only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
$viaCache
- forcibly cache a redirect CGI query. It cuts off all the params in a GET url and replace with a "?$cache=..." param. "$viaCache" is meaningful only if "$passthru" is true.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript and custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on. Those blocks will be loaded first.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
$web
- name of web, optional
$topic
- name of topic, optional
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Should only be called from initPlugin.
Adds a function to modify all the HTTP requests to any external resources.
\&fn
- Reference to the function.
The handler function must be of the form:
sub handler(\%session, $url) -> (\@headers, \%params)where:
\%session
- a reference to the TWiki session object (may be ignored)
$url
- a URL being requested
The returned \@headers
and \%params
are added to the request in the same
manner as getExternalResource
, except that \%params
will not override any
entries that have been set earlier.
All the params explicitly given by the caller of getExternalResource
or
postExternalResource
will have the highest precedence.
Example:
sub initPlugin { TWiki::Func::registerExternalHTTPHandler( \&handleExternalHTTPRequest ); } sub handleExternalHTTPRequest { my ($session, $url) = @_; my @headers; my %params; # Add any necessary @headers and %params push @headers, 'X-Example-Header' => 'Value'; $params{timeout} = 5; # Return refs to both return (\@headers, \%params); }
Since: TWiki::Plugins::VERSION 6.00
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$aquot |
Apostrophe quote (' ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
$lt |
Less than sign (< ) |
$gt |
Greater than sign (> ) |
Note that $quot, $aquot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
The following functions are for ReadOnlyAndMirrorWebs.
Returns the current site name if it's defined. Otherwise returns the null string.
Returns the content mode of the specified $web. Please read ReadOnlyAndMirrorWebs about content mode.
Since: TWiki::Plugins::VERSION 6.00
Checks if the web is wriable on this site - if it's master or local. Returns true if it's writable. Returns false otherwise.
Since: TWiki::Plugins::VERSION 6.00
The following functions are for UsingMultipleDisks.
Returns IDs of disks used by TWiki. An disk ID is "" (a null string) or a decimal number without leading 0.
Since: TWiki::Plugins::VERSION 6.00
Returns the relevant paths and the disk ID of the specified web on the specified site.
Since: TWiki::Plugins::VERSION 6.00
Returns the name of the trash web to which topics of the $web
web are moved.
Or returns the name of the trash web of the specified disk.
Each disk (file system) TWiki uses needs to have a trash web since a topic deletion may entail an attachment directory move, which is possible only within the same disk/file system.
Since: TWiki::Plugins::VERSION 6.00
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (Web.SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName, login name or cUID of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( 'myevent', $extra, $web, $topic ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '2013-12-31 - 19:30'
. Can be '$iso'
(e.g. '2013-12-31T19:30Z'
), '$rcs'
(e.g. '2013/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'The, 2013-07-23 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$format
- Format type, optional. Default e.g. '2014-12-31 - 19:30'
. Can be '$iso'
(e.g. '2014-12-31T19:30Z'
), '$rcs'
(e.g. '2014/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'The, 2014-07-23 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: If you used the removed formatGmTime, add a third parameter 'gmtime'
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string.
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
Note: Function TWiki::Func::extractParameters is more efficient for extracting several parameters
Entity encode text.
$text
- Text to encode, may be empty
$extra
- Additional characters to include in the set of encoded characters, optional
$text
Entity encoded text
Since: TWiki::Plugins::VERSION 6.00
Escape special characters to HTML numeric entities. This is not a generic encoding, it is tuned specifically for use in TWiki.
HTML4.0 spec: "Certain characters in HTML are reserved for use as markup and must be escaped to appear literally. The "<" character may be represented with an entity, <. Similarly, ">" is escaped as >, and "&" is escaped as &. If an attribute value contains a double quotation mark and is delimited by double quotation marks, then the quote should be escaped as ".
Other entities exist for special characters that cannot easily be entered with some keyboards..."
This method encodes HTML special and any non-printable ASCII characters (except for \n and \r) using numeric entities.
FURTHER this method also encodes characters that are special in TWiki meta-language.
$extras is an optional param that may be used to include additional characters in the set of encoded characters. It should be a string containing the additional chars.
Decode all numeric entities (e.g. {). Does not decode named entities such as & (use HTML::Entities for that)
$text
- Text to decode, may be empty
$text
Entity decoded text
Since: TWiki::Plugins::VERSION 6.00
URL encode text, mainly used to encode URL parameters.
$text
- Text to encode, may be empty
$text
URL encoded text
Since: TWiki::Plugins::VERSION 6.00
Encoding is done by converting characters that are illegal in URLs to their %NN equivalents. This method is used for encoding strings that must be embedded verbatim in URLs; it cannot be applied to URLs themselves, as it escapes reserved characters such as = and ?.
RFC 1738, Dec. '94:
...Only alphanumerics [0-9a-zA-Z], the special characters $-_.+!*'(), and reserved characters used for their reserved purposes may be used unencoded within a URL.
Reserved characters are $&+,/:;=?@ - these are also encoded by this method.
This URL-encoding handles all character encodings including ISO-8859-*, KOI8-R, EUC-* and UTF-8.
This may not handle EBCDIC properly, as it generates an EBCDIC URL-encoded URL, but mainframe web servers seem to translate this outbound before it hits browser - see CGI::Util::escape for another approach.
URL decode text, mainly used to decode URL parameters.
$text
- Text to decode, may be empty
$text
URL decoded text
Since: TWiki::Plugins::VERSION 6.00
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
isAnAdmin( $user, $topic, $web ) -> $boolean
-- added $topic
and $web
expandVariablesOnTopicCreation( $text, $web, $topic ) -> $text
-- added $web
and $topic
postExternalResource( $url, $text, \@headers, \%params ) -> $response
registerExternalHTTPHandler( \&fn )
getContentMode( $web ) -> $contentMode
webWritable( $web ) -> $boolean
getDiskList() -> @diskIDs
getDiskInfo($web, $siteName) -> ($dataDir, $pubDir, $diskID)
trashWebName(web => $web | disk => $diskID) -> $trashWebName
entityEncode( $text, $extra ) -> $text
entityDecode( $text ) -> $text
urlEncode( $text ) -> $text
urlDecode( $text ) -> $text
<<O>> Difference Topic TWikiFuncDotPm (16 - 2013-10-14 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Notes on use of $TWiki::Plugins::VERSION (from 1.2 forwards): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Notes on use of $TWiki::Plugins::VERSION 6.00 and later: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | example, new interfaces giving access to previously hidden core functions.
In addition, deprecation of functions in the interface trigger a minor
version increment. Note that deprecated functions are not removed, they
are merely frozen, and plugin authors are recommended to stop using them.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | @hea | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | getExternalResource( $url, \@headers, \%params ) -> $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 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Optional headers may be supplied of form 'name1', 'value1', 'name2', 'value2'. Do not add a User-Agent header, it will be added. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Optional parameters may be supplied:
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 'value1', 'name2', 'value2'.
User-Agent header is set to "TWiki::Net/### libwww-perl/#.##" by default,
where ### is the revision number of TWiki::Net and #.## is the version
of LWP.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Below is the list of available %params . See CPAN:LWP::UserAgent![]()
LWP .
Example: my $response = getExternalResource($url, ['Cache-Control' => 'max-age=0'], {timeout => 10}); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
The $response is an object that is known to implement the following subset of | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | the methods of LWP::Response . It may in fact be an LWP::Response object, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | the methods of HTTP::Response . It may in fact be an HTTP::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:
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { $text = $response->content(); # ... other methods of HTTP::Response may be called } else { # ... only the methods listed above may be called } Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note: The optional parameters \@headers and \%params were added in TWiki::Plugins::VERSION 6.00 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
postExternalResource( $url, $text, \@headers, \%params ) -> $response
This method is essentially the same as
The
See Since: TWiki::Plugins::VERSION 6.00 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
NOTE: As of TWiki-4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki-4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
NOTE: As of TWiki-4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki-4.1, if
setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function. Returns 1 if the preference was defined, and 0 otherwise.
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access ControlgetDefaultUserName( ) -> $loginNameGet default user name as defined in the configuration asDefaultUserLogin
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getCanonicalUserID( $user ) -> $cUID
If $user is undefined, it assumes the currently logged-in user.
Return: Since: TWiki::Plugins::VERSION 1.2
getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
Return: 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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
$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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2
@em | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Test if logged in user is a guest (TWikiGuest) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Test if logged in user is a guest (TWikiGuest) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | isAnAdmin( $id ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isAnAdmin( $user, $topic, $web ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Find out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note: The parameters $topic and $web were added in TWiki::Plugins::VERSION 6.00 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
isGroupMember( $group, $id ) -> $booleanFind out if $id is in the named group. e.g. if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If $user is undef , it defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
eachUser() -> $iteratorGet an iterator over the list of all the registered users not including groups. The iterator will return each wiki name in turn (e.g. 'FredBloggs').Use it as follows: my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
eachMembership($id) -> $iterator
Since: TWiki::Plugins::VERSION 1.2
eachGroup() -> $iteratorGet an iterator over all groups.Use it as follows: my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
isGroup( $group ) -> $boolean
Checks if
eachGroupMember($group) -> $iteratorGet an iterator over all the members of the named group. Returns undef if $group is not a valid group.Use it as follows: my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
checkAccessPermission( $type, $id, $text, $topic, $web, $meta ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Note the weird parameter order is due to compatibility constraints with earlier TWiki releases. Tip if you want, you can use this method to check your own access control types. For example, if you: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
in ThatWeb.ThisTopic , then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true .
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
@topics
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ) # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK.
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
$viaCache
- forcibly cache a redirect CGI query. It cuts off all the params in a GET url and replace with a "?$cache=..." param. "$viaCache" is meaningful only if "$passthru" is true.
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on.
requires
optional, comma-separated list of id's of other head blocks this one depends on. Those blocks will be loaded first.
$header
will be expanded before being inserted into the
section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
$text
- the text to process
$web
- name of web, optional
$topic
- name of topic, optional
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Should only be called from initPlugin.
Adds a function to modify all the HTTP requests to any external resources.
\&fn
- Reference to the function.
The handler function must be of the form:
sub handler(\%session, $url) -> (\@headers, \%params)where:
\%session
- a reference to the TWiki session object (may be ignored)
$url
- a URL being requested
The returned \@headers
and \%params
are added to the request in the same
manner as getExternalResource
, except that \%params
will not override any
entries that have been set earlier.
All the params explicitly given by the caller of getExternalResource
or
postExternalResource
will have the highest precedence.
Example:
sub initPlugin { TWiki::Func::registerExternalHTTPHandler( \&handleExternalHTTPRequest ); } sub handleExternalHTTPRequest { my ($session, $url) = @_; my @headers; my %params; # Add any necessary @headers and %params push @headers, 'X-Example-Header' => 'Value'; $params{timeout} = 5; # Return refs to both return (\@headers, \%params); }
Since: TWiki::Plugins::VERSION 6.00
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$aquot |
Apostrophe quote (' ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
$lt |
Less than sign (< ) |
$gt |
Greater than sign (> ) |
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
The following functions are for ReadOnlyAndMirrorWebs.
Returns the current site name if it's defined. Otherwise returns the null string.
Returns the content mode of the specified $web. Please read ReadOnlyAndMirrorWebs about content mode.
Since: TWiki::Plugins::VERSION 6.00
Checks if the web is wriable on this site - if it's master or local. Returns true if it's writable. Returns false otherwise.
Since: TWiki::Plugins::VERSION 6.00
The following functions are for UsingMultipleDisks.
Returns IDs of disks used by TWiki. An disk ID is "" (a null string) or a decimal number without leading 0.
Since: TWiki::Plugins::VERSION 6.00
Returns the relevant paths and the disk ID of the specified web on the specified site.
Since: TWiki::Plugins::VERSION 6.00
Returns the name of the trash web to which topics of the $web
web are moved.
Or returns the name of the trash web of the specified disk.
Each disk (file system) TWiki uses needs to have a trash web since a topic deletion may entail an attachment directory move, which is possible only within the same disk/file system.
Since: TWiki::Plugins::VERSION 6.00
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
configure
.configure
.Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName of user, optional. Name of logged-in user is taken if not specified.
$user
- WikiName, login name or cUID of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$format
- Format type, optional. Default e.g. '2013-12-31 - 19:30'
. Can be '$iso'
(e.g. '2013-12-31T19:30Z'
), '$rcs'
(e.g. '2013/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'The, 2013-07-23 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time stringNote: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
Entity encode text.
$text
- Text to encode, may be empty
$extra
- Additional characters to include in the set of encoded characters, optional
$text
Entity encoded text
Since: TWiki::Plugins::VERSION 6.00
Escape special characters to HTML numeric entities. This is not a generic encoding, it is tuned specifically for use in TWiki.
HTML4.0 spec: "Certain characters in HTML are reserved for use as markup and must be escaped to appear literally. The "<" character may be represented with an entity, <. Similarly, ">" is escaped as >, and "&" is escaped as &. If an attribute value contains a double quotation mark and is delimited by double quotation marks, then the quote should be escaped as ".
Other entities exist for special characters that cannot easily be entered with some keyboards..."
This method encodes HTML special and any non-printable ASCII characters (except for \n and \r) using numeric entities.
FURTHER this method also encodes characters that are special in TWiki meta-language.
$extras is an optional param that may be used to include additional characters in the set of encoded characters. It should be a string containing the additional chars.
Decode all numeric entities (e.g. {). Does not decode named entities such as & (use HTML::Entities for that)
$text
- Text to decode, may be empty
$text
Entity decoded text
Since: TWiki::Plugins::VERSION 6.00
URL encode text, mainly used to encode URL parameters.
$text
- Text to encode, may be empty
$text
URL encoded text
Since: TWiki::Plugins::VERSION 6.00
Encoding is done by converting characters that are illegal in URLs to their %NN equivalents. This method is used for encoding strings that must be embedded verbatim in URLs; it cannot be applied to URLs themselves, as it escapes reserved characters such as = and ?.
RFC 1738, Dec. '94:
...Only alphanumerics [0-9a-zA-Z], the special characters $-_.+!*'(), and reserved characters used for their reserved purposes may be used unencoded within a URL.
Reserved characters are $&+,/:;=?@ - these are also encoded by this method.
This URL-encoding handles all character encodings including ISO-8859-*, KOI8-R, EUC-* and UTF-8.
This may not handle EBCDIC properly, as it generates an EBCDIC URL-encoded URL, but mainframe web servers seem to translate this outbound before it hits browser - see CGI::Util::escape for another approach.
URL decode text, mainly used to decode URL parameters.
$text
- Text to decode, may be empty
$text
URL decoded text
Since: TWiki::Plugins::VERSION 6.00
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
isAnAdmin( $user, $topic, $web ) -> $boolean
-- added $topic
and $web
expandVariablesOnTopicCreation( $text, $web, $topic ) -> $text
-- added $web
and $topic
postExternalResource( $url, $text, \@headers, \%params ) -> $response
registerExternalHTTPHandler( \&fn )
getContentMode( $web ) -> $contentMode
webWritable( $web ) -> $boolean
getDiskList() -> @diskIDs
getDiskInfo($web, $siteName) -> ($dataDir, $pubDir, $diskID)
trashWebName(web => $web | disk => $diskID) -> $trashWebName
entityEncode( $text, $extra ) -> $text
entityDecode( $text ) -> $text
urlEncode( $text ) -> $text
urlDecode( $text ) -> $text
<<O>> Difference Topic TWikiFuncDotPm (15 - 2013-02-16 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
@hea
|
code() |
message() |
header($field) |
content() |
is_error() |
is_redirect() |
Note that if LWP is not available, this function:
require LWP
.
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:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { $text = $response->content(); # ... other methods of HTTP::Response may be called } else { # ... only the methods listed above may be called }
Since: TWiki::Plugins::VERSION 1.2
Get CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: $query
CGI query object; or 0 if script is called as a shell script
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Session keys are stored and retrieved using setSessionValue
and
getSessionValue
.
Since: TWiki::Plugins::VERSION 1.2
Get a session value from the client session module
$key
- Session key
$value
Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
Set a session value.
$key
- Session key
$value
- Value associated with key
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
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
.
Since: TWiki::Plugins::VERSION 1.1
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 TWiki 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 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:
sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this:
sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this:
%TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic:
%IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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.
Since: TWiki::Plugins::VERSION 1.1
$web
- new web
$topic
- new topic
$web.$topic
from now on. All the preferences will be reset to those of the new topic.
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.
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.
Since: TWiki::Plugins::VERSION 1.2
Returns the TWiki context to the state it was in before the
pushTopicContext
was called.
Since: TWiki::Plugins::VERSION 1.2
Get a preferences value from TWiki 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
$value
Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
* Set COLOR = red
"MYPLUGIN_COLOR"
for $key
my $color = TWiki::Func::getPreferencesValue( "MYPLUGIN_COLOR" );
* Set WEBBGCOLOR = #FFFFC0
my $webColor = TWiki::Func::getPreferencesValue( 'WEBBGCOLOR', 'Sandbox' );
$NO_PREFS_IN_TOPIC
is enabled in the plugin, then$NO_PREFS_IN_TOPIC
is enabled in the plugin, then
Get a preferences value from your Plugin
$key
- Plugin Preferences key w/o PLUGINNAME_ prefix.
$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. TWiki::Plugins::MyPlugin::MyModule)
Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
$NO_PREFS_IN_TOPIC
is enabled in the plugin, then$NO_PREFS_IN_TOPIC
is enabled in the plugin, then
Get a preferences flag from TWiki 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
$value
Preferences flag '1'
(if set), or "0"
(for preferences values "off"
, "no"
and "0"
)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
* Set SHOWHELP = off
"MYPLUGIN_SHOWHELP"
for $key
my $showHelp = TWiki::Func::getPreferencesFlag( "MYPLUGIN_SHOWHELP" );
$NO_PREFS_IN_TOPIC
is enabled in the plugin, then$NO_PREFS_IN_TOPIC
is enabled in the plugin, then
Get a preferences flag from your Plugin
$key
- Plugin Preferences key w/o PLUGINNAME_ prefix.
"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. TWiki::Plugins::MyPlugin::MyModule)
Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
$NO_PREFS_IN_TOPIC
is enabled in the plugin, then$NO_PREFS_IN_TOPIC
is enabled in the plugin, then
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.
Returns 1 if the preference was defined, and 0 otherwise.
Get toolname as defined in TWiki.cfg
Return: $name
Name of tool, e.g. 'TWiki'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Get name of Main web as defined in TWiki.cfg
Return: $name
Name, e.g. 'Main'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Get name of TWiki documentation web as defined in TWiki.cfg
Return: $name
Name, e.g. 'TWiki'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DefaultUserLogin
Return: $loginName
Default user name, e.g. 'guest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$user
can be a login, wikiname or web.wikiname
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.
Since: TWiki::Plugins::VERSION 1.2
return the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: $wikiName
Wiki Name, e.g. 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
return the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: $wikiName
Wiki Name, e.g. "Main.JohnDoe"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$id
- Wiki name, e.g. 'Main.JohnDoe'
or 'JohnDoe'
. Since TWiki 4.2.1, $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.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$loginName
- Login name, e.g. 'jdoe'
. Since TWiki 4.2.1 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"
$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)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$email
- email address to look up
$dontAddWeb
- Do not add web prefix if "1"
Since: TWiki::Plugins::VERSION 1.2
$user
- wikiname of user to look up
Since TWiki 4.2.1, $user may also be a login name, or the name of a group.
Since: TWiki::Plugins::VERSION 1.2
Test if logged in user is a guest (TWikiGuest)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Find out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed.
Since: TWiki::Plugins::VERSION 1.2
Find out if $id is in the named group. e.g.
if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If
$user
is undef
, it defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
Use it as follows:
my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname }
WARNING on large sites, this could be a long list!
Since: TWiki::Plugins::VERSION 1.2
$id
- WikiName or login name of the user. If $id
is undef
, defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
Use it as follows:
my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup }
WARNING on large sites, this could be a long list!
Since: TWiki::Plugins::VERSION 1.2
Checks if $group
is the name of a group known to TWiki.
Use it as follows:
my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' }
WARNING on large sites, this could be a long list!
Since: TWiki::Plugins::VERSION 1.2
Check access permission for a topic based on the TWiki.TWikiAccessControl rules
$type
- Access type, required, e.g. 'VIEW'
, 'CHANGE'
.
$id
- WikiName of remote user, required, e.g. "PeterThoeny"
. From TWiki 4.2.1, $id may also be a login name. If $id
is '', 0 or undef
then access is always permitted.
$text
- Topic text, optional. If 'perl false' (undef, 0 or ''), topic $web.$topic
is consulted. $text
may optionally contain embedded %META:PREFERENCE
tags. Provide this parameter if: $meta
parameter.
$topic
- Topic name, required, e.g. 'PrivateStuff'
$web
- Web name, required, e.g. 'Sandbox'
$meta
- Meta-data object, as returned by readTopic
. Optional. If undef
, but $text
is defined, then access controls will be parsed from $text
. If defined, then metadata embedded in $text
will be ignored. This parameter is always ignored if $text
is undefined. Settings in $meta
override Set
settings in $text.
Note the weird parameter order is due to compatibility constraints with earlier TWiki releases.
Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic
, then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef)
will return true
.
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
$filter
- spec of web types to recover
$filter
may also contain the word 'public' which will further filter
out webs that have NOSEARCHALL set on them.
'allowed' filters out webs the current user can't read.
For example, the deprecated getPublicWebList function can be duplicated as follows:
my @webs = TWiki::Func::getListOfWebs( "user,public" );
Since: TWiki::Plugins::VERSION 1.1
Test if web exists
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
Check for a valid web name.
$name
- web name
$templateWeb
- flag, optional. If true, then template web names (starting with _) are considered valid, otherwise only user web names are valid.
If $TWiki::cfg{EnableHierarchicalWebs} is off, it will also return false when a nested web name is passed to it.
Since: TWiki::Plugins::VERSION 1.4
$newWeb
is the name of the new web.
$baseWeb
is the name of an existing web (a template web). If the base web is a system web, all topics in it will be copied into the new web. If it is a normal web, only topics starting with 'Web' will be copied. If no base web is specified, an empty web (with no topics) will be created. If it is specified but does not exist, an error will be thrown.
$opts
is a ref to a hash that contains settings to be modified in
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::createWeb( "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
Move (rename) a web.
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::moveWeb( "Oldweb", "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
To delete a web, move it to a subweb of Trash
TWiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" );
Since: TWiki::Plugins::VERSION 1.1
Get an iterator over the list of all the changes in the given web between
$time
and now. $time is a time in seconds since 1st Jan 1970, and is not
guaranteed to return any changes that occurred before (now -
{Store}{RememberChangesFor}). {Store}{RememberChangesFor}) is a
setting in configure
. Changes are returned in most-recent-first
order.
Use it as follows:
my $iterator = TWiki::Func::eachChangeSince( $web, time() - 7 * 24 * 60 * 60); # the last 7 days while ($iterator->hasNext()) { my $change = $iterator->next(); # $change is a perl hash that contains the following fields: # topic => topic name # user => wikiname - wikiname of user who made the change # time => time of the change # revision => revision number *after* the change # more => more info about the change (e.g. 'minor') }
Get list of all topics in a web
$web
- Web name, required, e.g. 'Sandbox'
@topics
Topic list, e.g. ( 'WebChanges', 'WebHome', 'WebIndex', 'WebNotify' )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if topic exists.
$web
- Web name, optional, e.g. 'Main'
.
$topic
- Topic name, required, e.g. 'TokyoOffice'
, or "Main.TokyoOffice"
$web and $topic are parsed as described in the documentation for normalizeWebTopicName
.
Specifically, the Main is used if $web is not specified and $topic has no web specifier.
To get an expected behaviour it is recommened to specify the current web for $web; don't leave it empty.
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
Check for a valid topic name. Names considerd valid for autolinking are WikiWords (such as 'SanFrancisco') and acronym (such as 'SWMBO').
$name
- topic name
Since: TWiki::Plugins::VERSION 1.4
Check if a lease has been taken by some other user.
$web
Web name, e.g. "Main"
, or empty
$topic
Topic name, e.g. "MyTopic"
, or "Main.MyTopic"
( $oopsUrl, $loginName, $unlockTime )
- The $oopsUrl
for calling redirectCgiQuery(), user's $loginName
, and estimated $unlockTime
in minutes, or ( '', '', 0 ) if no lease exists. $script
The script to invoke when continuing with the edit
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
$web
Web name, e.g. "Main"
, or empty
$topic
Topic name, e.g. "MyTopic"
, or "Main.MyTopic"
$lock
1 to lease the topic, 0 to clear an existing lease
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The edit
script
always takes out a lease.
It is impossible to fully lock a topic. Concurrent changes will be merged.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
$web
- web for the topic
$topic
- topic name
$meta
- reference to TWiki::Meta object
$text
- text of the topic (without embedded meta-data!!!
\%options
- ref to hash of save options \%options
may include: dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ) # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( $web, $topic, 'myevent', $extra ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
<<O>> Difference Topic TWikiFuncDotPm (14 - 2012-10-07 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | getExternalResource( $url ) -> $response | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | @hea | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | the relevant RFC. Any proxy set in configure is honoured. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | the relevant RFC. Any proxy set in configure is honored. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Optional headers may be supplied of form 'name1', 'value1', 'name2', 'value2'. Do not add a User-Agent header, it will be added. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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:
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::Func::getExternalResource($url); if (!$response->is_error() && $response->isa('HTTP::Response')) { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | ... other methods of HTTP::Response may be called | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | $text = $response->content(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | # ... other methods of HTTP::Response may be called | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} else { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | ... only the methods listed above may be called | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | # ... only the methods listed above may be called | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}
Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ) # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( $web, $topic, 'myevent', $extra ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type ( 'ALLOW', 'DENY' ) { foreach my $action ( 'CHANGE', 'VIEW' ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
<<O>> Difference Topic TWikiFuncDotPm (13 - 2012-01-15 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Example:
# read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ) # example to change topic text: $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermission
to ensure the current user has read access to the
topic.
See usage example at TWiki::Func::saveTopic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g. logo.gif
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have $query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
$meta
- topic meta-data to use while expanding, can be undef (Since TWiki::Plugins::VERSION 1.4)
$textRef
- reference to unexpanded topic text, can be undef (Since TWiki::Plugins::VERSION 1.4)
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (default true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Write the log for an event to the logfile.
$action
- name of the event, such as 'blacklist'
.
$extra
- arbitrary extra information to add to the event.
$web
- web name, optional. Base web is taken if empty. Ignored if web is specified in $topic
.
$topic
- topic name, optional. Can be Topic
or Web.Topic
. Base topic is taken if empty.
$user
- WikiName of user, optional. Name of logged-in user is taken if not specified.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling TWiki::Func::writeLog( 'blacklist', 'Magic number is missing' )
will add a log entry like this:
| 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use $TWiki::cfg{LogFileName}
or call the internal TWiki
function directly should be fixed to use writeLog
.
To maintain compatibility with older TWiki releases, you can write conditional code as follows:
if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( $web, $topic, 'myevent', $extra ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); }
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
registerTagHandler
has two new parameters $meta
and $textRef
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error, $meta)
-- added $meta
beforeAttachmentSaveHandler(\%attrHash, $topic, $web, $meta)
= added =$meta
writeLog( $action, $extra, $web, $topic, $user )
<<O>> Difference Topic TWikiFuncDotPm (12 - 2011-08-21 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
A full history of the changes to this API can be found at the end of this topic.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isValidWebName( $name, $templateWeb ) -> $booleanCheck for a valid web name.
If $TWiki::cfg{EnableHierarchicalWebs} is off, it will also return false when a nested web name is passed to it. Since: TWiki::Plugins::VERSION 1.4 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
createWeb( $newWeb, $baseWeb, $opts )
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::createWeb( "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1
moveWeb( $oldName, $newName )Move (rename) a web.
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::moveWeb( "Oldweb", "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
To delete a web, move it to a subweb of TWiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" ); Since: TWiki::Plugins::VERSION 1.1
eachChangeSince($web, $time) -> $iterator
Get an iterator over the list of all the changes in the given web between
Use it as follows: my $iterator = TWiki::Func::eachChangeSince( $web, time() - 7 * 24 * 60 * 60); # the last 7 days while ($iterator->hasNext()) { my $change = $iterator->next(); # $change is a perl hash that contains the following fields: # topic => topic name # user => wikiname - wikiname of user who made the change # time => time of the change # revision => revision number *after* the change # more => more info about the change (e.g. 'minor') }
@topics
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Test if topic exists | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Test if topic exists. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$web and $topic are parsed as described in the documentation for Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isValidTopicName( $name ) -> $booleanCheck for a valid topic name. Names considerd valid for autolinking are WikiWords (such as 'SanFrancisco') and acronym (such as 'SWMBO').
Since: TWiki::Plugins::VERSION 1.4 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
checkTopicEditLock( $web, $topic, $script ) -> ( $oopsUrl, $loginName, $unlockTime )Check if a lease has been taken by some other user.
( $oopsUrl, $loginName, $unlockTime ) - The $oopsUrl for calling redirectCgiQuery(), user's $loginName , and estimated $unlockTime in minutes, or ( '', '', 0 ) if no lease exists.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
setTopicEditLock( $web, $topic, $lock )
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The It is impossible to fully lock a topic. Concurrent changes will be merged. Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
saveTopic( $web, $topic, $meta, $text, $options ) -> $error
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | For example, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Example: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { forcenewrevision => 1 } ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | # read topic: my( $topicMeta, $topicText ) = TWiki::Func::readTopic( $web, $topic ) # example to change topic text: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | $topicText =~ s/APPLE/ORANGE/g; # example to change TWiki form field: my $field = $topicMeta->get( 'FIELD', 'Title' ); if( $field ) { $field->{value} = $newTitle; $topicMeta->putKeyed( 'FIELD', $field ); } # save updated topic: TWiki::Func::saveTopic( $web, $topic, $topicMeta, $topicText, { forcenewrevision => 1 } ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Note: Plugins handlers ( e.g.
saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrlSave topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$oopsUrl Empty string if OK; the $oopsUrl for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
moveTopic( $web, $topic, $newWeb, $newTopic )
The destination topic must not already exist. Rename a topic to the $TWiki::cfg{TrashWebName} to delete it. Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
getRevisionInfo($web, $topic, $rev, $attachment ) -> ( $date, $user, $rev, $comment )Get revision info of a topic or attachment
( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
NOTE: if you are trying to get revision info for a topic, use
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getRevisionAtTime( $web, $topic, $time ) -> $revGet the revision number of a topic at a specific time.
Since: TWiki::Plugins::VERSION 1.1
readTopic( $web, $topic, $rev ) -> ( $meta, $text )Read topic text and meta data, regardless of access permissions.
( $meta, $text ) Meta data object and topic text
This method ignores topic access permissions. You should be careful to use
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | See usage example at TWiki::Func::saveTopic. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $textRead topic text, including meta data
$text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
attachmentExists( $web, $topic, $attachment ) -> $booleanTest if attachment exists
normalizeWebTopicName .
Since: TWiki::Plugins::VERSION 1.1
readAttachment( $web, $topic, $name, $rev ) -> $data
readTopic . If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; } Since: TWiki::Plugins::VERSION 1.1
saveAttachment( $web, $topic, $attachment, $opts )
$opts may include:
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1
moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
The destination topic must already exist, but the destination attachment must not exist. Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple }; Since: TWiki::Plugins::VERSION 1.1
Assembling Pages
readTemplate( $name, $skin ) -> $textRead a template or skin. Embedded template directives get expanded
$text Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
loadTemplate ( $name, $skin, $web ) -> $text
Since: TWiki::Plugins::VERSION 1.1 Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition. How TWiki searches for templates is described in TWikiTemplates. If template text is found, extracts include statements and fully expands them.
expandTemplate( $def ) -> $stringDo a , only expanding the template (not expanding any variables other than %TMPL)
Since: TWiki::Plugins::VERSION 1.1 A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
writeHeader( )Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
redirectCgiQuery( $query, $url, $passthru )Redirect to URL
Return: none Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The
Note that if my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1); $passthru does nothing if $url does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
addToHEAD( $id, $header, $requires )
Adds
All TWiki variables present in
Note that this is not the same as the HTTP header, which is modified through the Plugins Since: TWiki::Plugins::VERSION 1.1 example: TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />');
expandCommonVariables( $text, $topic, $web, $meta ) -> $text
Expand all common
$text Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) See also: expandVariablesOnTopicCreation
renderText( $text, $web ) -> $textRender text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by
$text XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
sendEmail ( $text, $retries ) -> $error
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body. Since: TWiki::Plugins::VERSION 1.1
wikiToEmail( $wikiName ) -> $email
Since: TWiki::Plugins::VERSION 1.1 Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several. Since TWiki 4.2.1, $wikiName may also be a login name.
Creating New Topics
expandVariablesOnTopicCreation ( $text ) -> $textExpand the limited set of variables that are always expanded during topic creation
Since: TWiki::Plugins::VERSION 1.1 Expands only the variables expected in templates that must be statically expanded in new content. The expanded variables are:
See also: expandVariables
Special HandlersSpecial handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
registerTagHandler( $var, \&fn, $syntax )Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, and are expanded at the same time. This is a lot more efficient than using the
Since: TWiki::Plugins::VERSION 1.1 The variable handler function must be of the form: sub handler(\%session, \%params, $topic, $web)where:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
for example, to execute an arbitrary command on the server, you might do this:
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in
registerRESTHandler( $alias, \&fn, )Should only be called from initPlugin. Adds a function to the dispatch table of the REST interface
Since: TWiki::Plugins::VERSION 1.1 The handler function must be of the form: sub handler(\%session)where:
From the REST interface, the name of the plugin must be used as the subject of the invokation. Example The EmptyPlugin has the following call in the initPlugin handler: TWiki::Func::registerRESTHandler('example', \&restExample);
This adds the
note that the URL
(ie, with the name of the function instead of the alias) will not work.
decodeFormatTokens($str) -> $unencodedString
TWiki has an informal standard set of tokens used in
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned! Since: TWiki::Plugins::VERSION 1.2
Searching
searchInWebContent($searchString, $web, \@topics, \%options ) -> \%mapSearch for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
\%options hash may contain the following options:
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'. To iterate over the returned topics use: my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc Since: TWiki::Plugins::VERSION 1.1
Plugin-specific File Handling
getWorkArea( $pluginName ) -> $directorypathGets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it. The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible. The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy. Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
readFile( $filename ) -> $textRead file, low level. Used for Plugin workarea.
$text Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
saveFile( $filename, $text )Save file, low level. Used for Plugin workarea.
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
General Utilities
getRegularExpression( $name ) -> $exprRetrieves a TWiki predefined regular expression or character class.
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004) Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions. In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example: my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example: my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
normalizeWebTopicName($web, $topic) -> ($web, $topic)Parse a web and topic name, supplying defaults as appropriate.
Since: TWiki::Plugins::VERSION 1.1
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
sanitizeAttachmentName($fname) -> ($fileName, $origName)Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation. Sanitation includes filtering illegal characters and mapping client file names to legal server names. Since: TWiki::Plugins::VERSION 1.2
buildWikiWord( $text ) -> $textConverts arbitrary text to a WikiWord.
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
spaceOutWikiWord( $word, $sep ) -> $textSpaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space. Since: TWiki::Plugins::VERSION 1.2
writeWarning( $text )Log Warning that may require admin intervention to data/warning.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
writeDebug( $text )Log debug message to data/debug.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | writeLog( $action, $extra, $web, $topic, $user )Write the log for an event to the logfile.
Since: TWiki::Plugins::VERSION 1.4
Example: Calling | 2011-01-19 - 01:13 | guest | blacklist | TWiki.TWikiRegistration | Magic number is missing | 1.2.3.4 |
Note: Older plugins that use To maintain compatibility with older TWiki releases, you can write conditional code as follows: if( defined &TWiki::Func::writeLog ) { # use writeLog TWiki::Func::writeLog( $web, $topic, 'myevent', $extra ); } else { # deprecated code if plugin is used in older TWiki releases $TWiki::Plugins::VERSION > 1.1 ? $TWiki::Plugins::SESSION->writeLog( 'myevent', "$web.$topic", $extra ) : TWiki::Store::writeLog( 'myevent', "$web.$topic", $extra ); } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
formatTime( $time, $format, $timezone ) -> $textFormat the time in seconds into the desired time string
$text Formatted time string
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
isTrue( $value, $default ) -> $boolean
Returns 1 if
If the value is undef, then | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Since: $TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
isValidWikiWord ( $text ) -> $booleanCheck for a valid WikiWord or WikiName
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
extractParameters($attr ) -> %paramsExtract all parameters from a variable string and returns a hash of parameters
%params Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
extractNameValuePair( $attr, $name ) -> $valueExtract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$value Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Deprecated functionsFrom time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed. Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of TWiki::Plugins before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible. getScriptUrlPath( ) -> $pathGet script URL path
DEPRECATED since 1.1 - use
Return: WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the oopstoestuckerror template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
@webs
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
TWiki-4.0.0 (Dakar Release)$TWiki::Plugins::VERSION 1.1EmptyPlugin.pm
Func.pm
TWiki-4.0.1 (Dakar Patch Release)$TWiki::Plugins::VERSION 1.1EmptyPlugin.pm
Func.pm
TWiki-4.1 (Edinburgh Release)$TWiki::Plugins::VERSION 1.11EmptyPlugin.pm
Func.pmNo changes
TWiki-4.2 (Freetown Release)$TWiki::Plugins::VERSION 1.2EmptyPlugin.pm
Func.pm
TWiki-4.3 (Georgetown Release)$TWiki::Plugins::VERSION 1.2EmptyPlugin.pmNo changesFunc.pmNo changes
TWiki-5.0 (Helsinki Release)$TWiki::Plugins::VERSION 1.3EmptyPlugin.pmNo changesFunc.pm
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
TWiki-5.1 (Istanbul Release)$TWiki::Plugins::VERSION 1.4EmptyPlugin.pm
Func.pm
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
<<O>> Difference Topic TWikiFuncDotPm (11 - 2011-05-04 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that TWiki plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and documentation on how to write a plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new plugins and should be replaced in older plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
A full history of the changes to this API can be found at the end of this
topic.
On this page:
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Environment | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
setSessionValue( $key, $value ) -> $booleanSet a session value.
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
clearSessionValue( $key ) -> $boolean
Clear a session value that was set using
Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getContext() -> \%hashGet a hash of context identifiers representing the currently active context. The context is a set of identifiers that are set during specific phases of TWiki 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 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
pushTopicContext($web, $topic)
$web.$topic
from now on. All the preferences will be reset to those of the new topic.
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.
It is the duty of the caller to restore the original context by calling
Note that this call does not re-initialise plugins, so if you have used
global variables to remember the web and topic in Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
popTopicContext()
Returns the TWiki context to the state it was in before the
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Preferences | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function. Returns 1 if the preference was defined, and 0 otherwise. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
User Handling and Access Control | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getDefaultUserName( ) -> $loginNameGet default user name as defined in the configuration asDefaultUserLogin
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getCanonicalUserID( $user ) -> $cUID
If $user is undefined, it assumes the currently logged-in user.
Return: Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
Return: 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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
$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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
@em | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isAnAdmin( $id ) -> $booleanFind out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed.
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isGroupMember( $group, $id ) -> $booleanFind out if $id is in the named group. e.g. if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If $user is undef , it defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
eachUser() -> $iteratorGet an iterator over the list of all the registered users not including groups. The iterator will return each wiki name in turn (e.g. 'FredBloggs').Use it as follows: my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
eachMembership($id) -> $iterator
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
eachGroup() -> $iteratorGet an iterator over all groups.Use it as follows: my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isGroup( $group ) -> $boolean
Checks if | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
eachGroupMember($group) -> $iteratorGet an iterator over all the members of the named group. Returns undef if $group is not a valid group.Use it as follows: my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
checkAccessPermission( $type, $id, $text, $topic, $web, $meta ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Note the weird parameter order is due to compatibility constraints with earlier TWiki releases. Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic , then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true .
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Webs, Topics and Attachments | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
@web
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
webExists( $web ) -> $booleanTest if web exists
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
createWeb( $newWeb, $baseWeb, $opts )
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::createWeb( "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
moveWeb( $oldName, $newName )Move (rename) a web.
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::moveWeb( "Oldweb", "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
To delete a web, move it to a subweb of TWiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" ); Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
eachChangeSince($web, $time) -> $iterator
Get an iterator over the list of all the changes in the given web between
Use it as follows: my $iterator = TWiki::Func::eachChangeSince( $web, time() - 7 * 24 * 60 * 60); # the last 7 days while ($iterator->hasNext()) { my $change = $iterator->next(); # $change is a perl hash that contains the following fields: # topic => topic name # user => wikiname - wikiname of user who made the change # time => time of the change # revision => revision number *after* the change # more => more info about the change (e.g. 'minor') } | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
@topics
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
topicExists( $web, $topic ) -> $booleanTest if topic exists
$web and $topic are parsed as described in the documentation for Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
checkTopicEditLock( $web, $topic, $script ) -> ( $oopsUrl, $loginName, $unlockTime )Check if a lease has been taken by some other user.
( $oopsUrl, $loginName, $unlockTime ) - The $oopsUrl for calling redirectCgiQuery(), user's $loginName , and estimated $unlockTime in minutes, or ( '', '', 0 ) if no lease exists.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
setTopicEditLock( $web, $topic, $lock )
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The It is impossible to fully lock a topic. Concurrent changes will be merged. Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
saveTopic( $web, $topic, $meta, $text, $options ) -> $error
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) For example, my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrlSave topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$oopsUrl Empty string if OK; the $oopsUrl for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
moveTopic( $web, $topic, $newWeb, $newTopic )
The destination topic must not already exist. Rename a topic to the $TWiki::cfg{TrashWebName} to delete it. Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... }; | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getRevisionInfo($web, $topic, $rev, $attachment ) -> ( $date, $user, $rev, $comment )Get revision info of a topic or attachment
( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
NOTE: if you are trying to get revision info for a topic, use
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getRevisionAtTime( $web, $topic, $time ) -> $revGet the revision number of a topic at a specific time.
Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readTopic( $web, $topic, $rev ) -> ( $meta, $text )Read topic text and meta data, regardless of access permissions.
( $meta, $text ) Meta data object and topic text
This method ignores topic access permissions. You should be careful to use
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $textRead topic text, including meta data
$text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
attachmentExists( $web, $topic, $attachment ) -> $booleanTest if attachment exists
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
$web and $topic are parsed as described in the documentation for normalizeWebTopicName .
Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readAttachment( $web, $topic, $name, $rev ) -> $data
readTopic . If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; } Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
saveAttachment( $web, $topic, $attachment, $opts )
$opts may include:
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
The destination topic must already exist, but the destination attachment must not exist. Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple }; Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Assembling Pages | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readTemplate( $name, $skin ) -> $textRead a template or skin. Embedded template directives get expanded
$text Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
loadTemplate ( $name, $skin, $web ) -> $text
Since: TWiki::Plugins::VERSION 1.1 Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition. How TWiki searches for templates is described in TWikiTemplates. If template text is found, extracts include statements and fully expands them. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
expandTemplate( $def ) -> $stringDo a , only expanding the template (not expanding any variables other than %TMPL)
Since: TWiki::Plugins::VERSION 1.1 A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
writeHeader( )Print a basic content-type HTML header for text/html to standard out. No return value.
Note: In TWiki versions earlier than TWiki::Plugins::VERSION 1.3, this function used to have Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
redirectCgiQuery( $query, $url, $passthru )Redirect to URL
Return: none Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The
Note that if my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1); $passthru does nothing if $url does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
addToHEAD( $id, $header, $requires )
Adds
All TWiki variables present in
Note that this is not the same as the HTTP header, which is modified through the Plugins Since: TWiki::Plugins::VERSION 1.1 example: TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />'); | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
expandCommonVariables( $text, $topic, $web, $meta ) -> $text
Expand all common
$text Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) See also: expandVariablesOnTopicCreation | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
renderText( $text, $web ) -> $textRender text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by
$text XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
sendEmail ( $text, $retries ) -> $error
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body. Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
wikiToEmail( $wikiName ) -> $email
Since: TWiki::Plugins::VERSION 1.1 Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several. Since TWiki 4.2.1, $wikiName may also be a login name. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Creating New Topics | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
expandVariablesOnTopicCreation ( $text ) -> $textExpand the limited set of variables that are always expanded during topic creation
Since: TWiki::Plugins::VERSION 1.1 Expands only the variables expected in templates that must be statically expanded in new content. The expanded variables are:
See also: expandVariables | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Special handlers | ||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Special Handlers | ||||||||||||||||||||||||||||||||||||||||||
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
registerTagHandler( $var, \&fn, $syntax )Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, and are expanded at the same time. This is a lot more efficient than using the
Since: TWiki::Plugins::VERSION 1.1 The variable handler function must be of the form: sub handler(\%session, \%params, $topic, $web)where:
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this: %EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
registerRESTHandler( $alias, \&fn, )Should only be called from initPlugin. Adds a function to the dispatch table of the REST interface
Since: TWiki::Plugins::VERSION 1.1 The handler function must be of the form: sub handler(\%session)where:
From the REST interface, the name of the plugin must be used as the subject of the invokation. Example The EmptyPlugin has the following call in the initPlugin handler: TWiki::Func::registerRESTHandler('example', \&restExample);
This adds the
note that the URL
(ie, with the name of the function instead of the alias) will not work. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
decodeFormatTokens($str) -> $unencodedString
TWiki has an informal standard set of tokens used in
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Searching | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
searchInWebContent($searchString, $web, \@topics, \%options ) -> \%mapSearch for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
\%options hash may contain the following options:
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'. To iterate over the returned topics use: my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Plugin-specific file handling | ||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Plugin-specific File Handling | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getWorkArea( $pluginName ) -> $directorypathGets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it. The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible. The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy. Since: TWiki::Plugins::VERSION 1.1 (Dec 2005) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readFile( $filename ) -> $textRead file, low level. Used for Plugin workarea.
$text Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
saveFile( $filename, $text )Save file, low level. Used for Plugin workarea.
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
General Utilities | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getRegularExpression( $name ) -> $exprRetrieves a TWiki predefined regular expression or character class.
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004) Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions. In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example: my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example: my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
normalizeWebTopicName($web, $topic) -> ($web, $topic)Parse a web and topic name, supplying defaults as appropriate.
Since: TWiki::Plugins::VERSION 1.1
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | StaticMethod *sanitizeAttachmentName ($fname) -> ($fileName,$origName) | ||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | sanitizeAttachmentName($fname) -> ($fileName, $origName) | ||||||||||||||||||||||||||||||||||||||||||
Given a file namer, sanitise it according to the rules for transforming
attachment names. Returns
the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names. Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
buildWikiWord( $text ) -> $textConverts arbitrary text to a WikiWord.
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
spaceOutWikiWord( $word, $sep ) -> $textSpaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space. Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
writeWarning( $text )Log Warning that may require admin intervention to data/warning.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
writeDebug( $text )Log debug message to data/debug.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
formatTime( $time, $format, $timezone ) -> $textFormat the time in seconds into the desired time string
$text Formatted time string
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isTrue( $value, $default ) -> $boolean
Returns 1 if
If the value is undef, then Since: $TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
isValidWikiWord ( $text ) -> $booleanCheck for a valid WikiWord or WikiName
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
extractParameters($attr ) -> %paramsExtract all parameters from a variable string and returns a hash of parameters
%params Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
extractNameValuePair( $attr, $name ) -> $valueExtract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$value Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Deprecated functionsFrom time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed. Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of TWiki::Plugins before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getScriptUrlPath( ) -> $pathGet script URL path
DEPRECATED since 1.1 - use
Return: WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the oopstoestuckerror template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } } | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
@webs
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
formatGmTime( $time, $format ) -> $text
DEPRECATED since 1.1 - use Format the time to GM time
$text Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getDataDir( ) -> $dirDEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead Get data directory (topic file root)
Return: This function violates store encapsulation and is therefore deprecated. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPubDir( ) -> $dirDEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in
Return: This function violates store encapsulation and is therefore deprecated.
Use Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
checkDependencies( $moduleName, $dependenciesRef ) -> $error
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
TWiki API History
TWiki-2001-09-01 (Athens Release)$TWiki::Plugins::VERSION 1.000EmptyPlugin.pm
Func.pm
TWiki-2003-02-01 (Beijing Release)$TWiki::Plugins::VERSION 1.010EmptyPlugin.pm
Func.pm
TWiki-2004-09-02 (Cairo Release)$TWiki::Plugins::VERSION 1.025EmptyPlugin.pm
Func.pm
TWiki-4.0.0 (Dakar Release)$TWiki::Plugins::VERSION 1.1EmptyPlugin.pm
Func.pm
TWiki-4.0.1 (Dakar Patch Release)$TWiki::Plugins::VERSION 1.1EmptyPlugin.pm
Func.pm
TWiki-4.1 (Edinburgh Release)$TWiki::Plugins::VERSION 1.11EmptyPlugin.pm
Func.pmNo changes
TWiki-4.2 (Freetown Release)$TWiki::Plugins::VERSION 1.2EmptyPlugin.pm
Func.pm
TWiki-4.3 (Georgetown Release)$TWiki::Plugins::VERSION 1.2EmptyPlugin.pmNo changesFunc.pmNo changes
TWiki-5.0 (Helsinki Release)$TWiki::Plugins::VERSION 1.3EmptyPlugin.pmNo changesFunc.pm
|
<<O>> Difference Topic TWikiFuncDotPm (10 - 2010-05-29 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | This module defines official functions that Plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | This module defines official functions that TWiki plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
can use to interact with the TWiki engine and content. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | plugin and documentation on how to write a plugin. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | you will probably need to change your Plugin when you upgrade TWiki. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | you will probably need to change your plugin when you upgrade TWiki. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deprecated functions will still work in older code, though they should | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | not be called in new Plugins and should be replaced in older Plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | not be called in new plugins and should be replaced in older plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
Return: 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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
$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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2
@em | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | in ThatWeb.ThisTopic , then a call to checkAccessPermissions('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | in ThatWeb.ThisTopic , then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | guaranteed to return any changes that occurred before (now - | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | guaranteed to return any changes that occurred before (now - | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{Store}{RememberChangesFor}). {Store}{RememberChangesFor}) is a
setting in configure . Changes are returned in most-recent-first
order.
Use it as follows: my $iterator = TWiki::Func::eachChangeSince( $web, time() - 7 * 24 * 60 * 60); # the last 7 days while ($iterator->hasNext()) { my $change = $iterator->next(); # $change is a perl hash that contains the following fields: # topic => topic name # user => wikiname - wikiname of user who made the change # time => time of the change # revision => revision number *after* the change # more => more info about the change (e.g. 'minor') }
@topics
|
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermissions
to ensure the current user has read access to thecheckAccessPermission
to ensure the current user has read access to theSince: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
$query
- CGI query object. If not given, the default CGI query will be used (optional, in most cases you should not pass this parameter)
$contentLength
- Length of content (optional, in most cases you should not pass this parameter)
$query
and $contentLength
parameters. Both were marked "you should not pass this parameter".
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css. $id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
requires
optional, comma-separated list of id's of other head blocks this one depends on.
$header
will be expanded before being inserted into the
section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
Should only be called from initPlugin.
$alias
- The name .
\&fn
- Reference to the function.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
restExample
function to the REST dispatch table
for the EmptyPlugin under the 'example' alias, and allows it restExample
function to the REST dispatch table
for the EmptyPlugin under the 'example' alias, and allows it
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Converts arbitrary text to a WikiWord.
$pre
- Arbitrary Text
$text
Since: TWiki::Plugins::VERSION 1.3 (18 Jan 2010)
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: $TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
commonTagsHandler($text, $topic, $web)
endRenderingHandler($text)
outsidePREHandler($text)
insidePREHandler($text)
startRenderingHandler($text, $web)
checkAccessPermission($type, $login, $topicText, $topicName, $webName) -> $boolean
expandCommonVariables($text, $topic, $web) -> $text
extractNameValuePair($attrs, $name) -> $value
formatGmTime($time) -> $text
getCgiQuery() -> $query
getDataDir() -> $dir
getDefaultUserName() -> $loginName
getMainWebname() -> $name
getOopsUrl($web, $topic, $template, @theParams
) -> $url
getPreferencesFlag($key) -> $boolean
getPreferencesValue($key, $web) -> $value
getPublicWebList() -> @webs
getPubDir() -> $dir
getPubUrlPath() -> $path
getRevisionInfo($webName, $topic, $rev, $attachment) -> ($date, $user, $rev, $comment)
getScriptUrl($web, $topic, $script) -> $url
getScriptUrlPath() -> $path
getSessionValue($key) -> $value
getSkin() -> $skin
getTopicList($web) -> @topics
getTwikiWebname() -> $name
getUrlHost() -> $host
getViewUrl($web, $topic) -> $url
getWikiName() -> $wikiName
getWikiUserName($text) -> $wikiName
getWikiToolName() -> $name
internalLink($preamble, $web, $topic, $linkText, $anchor, $createLink) -> $text
isGuest() -> $boolean
permissionsSet($web) -> $boolean
readFile($filename) -> $text
readTemplate($name, $skin) -> $text
readTopic($webName, $topic) -> ($meta, $text)
redirectCgiQuery($query, $url)
renderText($text, $web) -> $text
saveFile($filename, $text)
setSessionValue($key, $value)
topicExists($web, $topic) -> $boolean
userToWikiName($user, $dontAddWeb) -> $wikiName
webExists($web) -> $boolean
wikiToUserName($wiki) -> $loginName
writeDebug($text)
writeHeader()
writeWarning($text)
afterEditHandler($text, $topic, $web)
beforeEditHandler($text, $topic, $web)
beforeSaveHandler($text, $topic, $web)
initializeUserHandler($loginName, $url, $pathInfo)
redirectCgiQueryHandler($query, $url)
registrationHandler($web, $wikiName, $loginName)
writeHeaderHandler($query)
checkTopicEditLock($web, $topic) ->($oopsUrl, $loginName, $unlockTime)
readTopicText($web, $topic, $rev, $ignorePermissions) -> $text
saveTopicText($web, $topic, $text, $ignorePermissions, $dontNotify) -> $oopsUrl
setTopicEditLock($web, $topic, $lock) -> $oopsUrl
afterCommonTagsHandler($text, $topic, $web)
afterSaveHandler($text, $topic, $web, $error)
beforeCommonTagsHandler($text, $topic, $web)
earlyInitPlugin()
afterAttachmentSaveHandler(\%attrHash, $topic, $web, $error)
beforeAttachmentSaveHandler(\%attrHash, $topic, $web)
checkDependencies($moduleName, $dependenciesRef) -> $error
extractParameters($attr) -> %params
formatTime($time, $format, $timezone) -> $text
getPluginPreferencesFlag($key) -> $boolean
getPluginPreferencesValue($key) -> $value
getRegularExpression($regexName) -> $pattern
mergeHandler($diff, $old, $new, \%info) -> $text
modifyHeaderHandler(\%headers, $query)
postRenderingHandler($text)
preRenderingHandler($text, \%map)
renderFormFieldForEditHandler($name, $type, $size, $value, $attributes, $possibleValues) -> $html
renderWikiWordHandler($linkText, $hasExplicitLinkLabel, $web, $topic) -> $linkText
endRenderingHandler($text)
startRenderingHandler($text, $web)
addToHEAD($id, $header)
attachmentExists($web, $topic, $attachment) -> $boolean
clearSessionValue($key) -> $boolean
checkDependencies($moduleName, $dependenciesRef) -> $error
createWeb($newWeb, $baseWeb, $opts)
expandTemplate($def ) -> $string
expandVariablesOnTopicCreation($text) -> $text
getContext() -> \%hash
getListOfWebs($filter) -> @webs
getScriptUrl($web, $topic, $script, @params
) -> $url
getRevisionAtTime($web, $topic, $time) -> $rev
getWorkArea($pluginName) -> $directorypath
isValidWikiWord($text) -> $boolean
loadTemplate($name, $skin, $web) -> $text
moveAttachment($web, $topic, $attachment, $newWeb, $newTopic, $newAttachment)
moveTopic($web, $topic, $newWeb, $newTopic)
moveWeb($oldName, $newName)
normalizeWebTopicName($web, $topic) ->($web, $topic)
readAttachment($web, $topic, $name, $rev) -> $data
registerRESTHandler($alias, \&fn,)
registerTagHandler($var, \&fn, $syntax)
saveAttachment($web, $topic, $attachment, $opts)
saveTopic($web, $topic, $meta, $text, $options) -> $error
searchInWebContent($searchString, $web, \@topics, \%options) -> \%map
sendEmail($text, $retries) -> $error
wikiToEmail($wikiName) -> $email
writeHeader($query, $contentLength)
checkDependencies($moduleName, $dependenciesRef) -> $error
formatGmTime($time, $format) -> $text
getDataDir() -> $dir
getOopsUrl( $web, $topic, $template, @params
) -> $url
getPubDir() -> $dir
getPublicWebList() -> @webs
getScriptUrlPath() -> $path
afterSaveHandler($text, $topic, $web, $error, $meta)
beforeSaveHandler($text, $topic, $web, $meta)
afterRenameHandler($oldWeb, $oldTopic, $oldAttachment, $newWeb, $newTopic, $newAttachment)
afterCommonTagsHandler($text, $topic, $web, $meta)
beforeCommonTagsHandler($text, $topic, $web, $meta)
commonTagsHandler($text, $topic, $web, $included, $meta)
decodeFormatTokens($str) -> $unencodedString
eachChangeSince($web, $time) -> $iterator
eachGroup() -> $iterator
eachGroupMember($group) -> $iterator
eachMembership($wikiname) -> $iterator
eachUser() -> $iterator
emailToWikiNames($email, $dontAddWeb) -> @wikiNames
expandCommonVariables($text, $topic, $web, $meta) -> $text
getCanonicalUserID( $user ) -> $cUID
getExternalResource($url) -> $response
getSessionKeys() -> @keys
isAnAdmin($login) -> $boolean
isGroup($group) -> $boolean
isGroupMember($group, $login) -> $boolean
isTrue($value, $default) -> $boolean
popTopicContext()
pushTopicContext($web, $topic)
sanitizeAttachmentName($fname) -> ($fileName, $origName)
setPreferencesValue($name, $val)
spaceOutWikiWord($word, $sep) -> $text
wikiNameToEmails($wikiname) -> @emails
permissionsSet($web) -> $boolean
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
buildWikiWord( $text ) -> $text
<<O>> Difference Topic TWikiFuncDotPm (9 - 2008-12-06 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | in the TWikiTemplates topic. Please be careful not to | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | in the 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
pushTopicContext($web, $topic)
$web.$topic
from now on. All the preferences will be reset to those of the new topic.
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.
It is the duty of the caller to restore the original context by calling
Note that this call does not re-initialise plugins, so if you have used
global variables to remember the web and topic in Since: TWiki::Plugins::VERSION 1.2
popTopicContext()
Returns the TWiki context to the state it was in before the
Since: TWiki::Plugins::VERSION 1.2
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function. Returns 1 if the preference was defined, and 0 otherwise.
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access ControlgetDefaultUserName( ) -> $loginNameGet default user name as defined in the configuration asDefaultUserLogin
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getCanonicalUserID( $user ) -> $cUID
If $user is undefined, it assumes the currently logged-in user.
Return: Since: TWiki::Plugins::VERSION 1.2
getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
Return: 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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name
$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) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2
@em |
dontlog | don't log this change in twiki log |
forcenewrevision | force the save to increment the revision counter |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { forcenewrevision => 1 } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use
checkAccessPermissions
to ensure the current user has read access to the
topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used (optional, in most cases you should not pass this parameter)
$contentLength
- Length of content (optional, in most cases you should not pass this parameter)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Deprecated in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: $TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (8 - 2008-08-03 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the
Notes on use of
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
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
Note that the
The
Note that if LWP is not available, this function:
In the event of the server returning an error, then Note: Callers can easily check the availability of other HTTP::Response methods as follows:
my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@keys
Get a list of all the names of session variables. The list is unsorted.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return the cUID of the specified user. A cUID is a unique identifier which is assigned by TWiki for each user. BEWARE: While the default TWikiUserMapping uses a cUID that looks like a user's LoginName, some characters are modified to make them compatible with rcs. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Additionally, other usermappings will use other conventions - the JoomlauserMapping | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Other usermappings may use other conventions - the JoomlaUserMapping | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
for example, has cUIDs like 'JoomlaeUserMapping_1234'. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
If $user is undefined Get the cUID of logged in user, and will generally be
'BaseUserMapping_666'
Return: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
If $user is undefined, it assumes the currently logged-in user.
Return: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | registered users (they can be autogenerated for an authenticated but unregistered user) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2
getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $user ) -> $wikiNamereturn the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name (or login name or cUID, if it can) to a login name.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | wikiToUserName( $id ) -> $loginNameTranslate a Wiki name to a login name.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since TWiki 4.2.1, $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. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe' | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | userToWikiName will always return a name, if the user does not | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | userToWikiName will always return a name. If the user does not | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
exist in the mapping, the $loginName parameter is returned. (backward compatibility)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | wikiNameToEmails( $wikiname ) -> @emails
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | @em | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
undef, returns the registered email addresses for the logged-in user. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since TWiki 4.2.1, $user may also be a login name, or the name of a group. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | isAnAdmin( $login ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isAnAdmin( $id ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Find out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | isGroupMember( $group, $login ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isGroupMember( $group, $id ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Find out if $login is in the named group. e.g. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Find out if $id is in the named group. e.g. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If $user is undef , it defaults to the currently logged-in user. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2
eachUser() -> $iteratorGet an iterator over the list of all the registered users not including groups. The iterator will return each wiki name in turn (e.g. 'FredBloggs').Use it as follows: my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | eachMembership($wikiname) -> $iterator | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | eachMembership($id) -> $iterator | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Get an iterator over the names of all groups that the user is a member of. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | If $wikiname is undef , defaults to the currently logged-in user. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.2
eachGroup() -> $iteratorGet an iterator over all groups.Use it as follows: my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
isGroup( $group ) -> $boolean
Checks if
eachGroupMember($group) -> $iteratorGet an iterator over all the members of the named group. Returns undef if $group is not a valid group.Use it as follows: my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | checkAccessPermission( $type, $wikiName, $text, $topic, $web, $meta ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | checkAccessPermission( $type, $id, $text, $topic, $web, $meta ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Check access permission for a topic based on the
TWiki.TWikiAccessControl rules
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | If $id is '', 0 or undef then access is always permitted. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Note the wierd parameter order is due to compatibility constraints with | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note the weird parameter order is due to compatibility constraints with | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
earlier TWiki releases.
Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic , then a call to checkAccessPermissions('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true .
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | while ($it->hasNext()) { my $change = $it->next(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | while ($iterator->hasNext()) { my $change = $iterator->next(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# $change is a perl hash that contains the following fields:
# topic => topic name
# user => wikiname - wikiname of user who made the change
# time => time of the change
# revision => revision number after the change
# more => more info about the change (e.g. 'minor')
}
@topics
|
dontlog | don't log this change in twiki log |
comment |
comment for save |
forcenewrevision |
force the save to increment the revision counter |
minor |
True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g;
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
checkAccessPermissions
to ensure the current user has read access to the topic.checkAccessPermissions
to ensure the current user has read access to the
topic.
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used (optional, in most cases you should not pass this parameter)
$contentLength
- Length of content (optional, in most cases you should not pass this parameter)
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file.
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$meta
- topic meta-data to use while expanding (Since TWiki::Plugins::VERSION 1.2)
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
$wikiname
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Since TWiki 4.2.1, $wikiName may also be a login name.
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
TWiki has an informal standard set of tokens used in format
parameters that are used to block evaluation of paramater strings.
For example, if you were to write
%MYTAG{format="%WURBLE%"}%
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
%MYTAG{format="$percntWURBLE$percnt"}%
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Escape: | Expands To: |
---|---|
$n or $n() |
New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar |
$nop or $nop() |
Is a "no operation". |
$quot |
Double quote (" ) |
$percnt |
Percent sign (% ) |
$dollar |
Dollar sign ($ ) |
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned!
Since: TWiki::Plugins::VERSION 1.2
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation.
Sanitation includes filtering illegal characters and mapping client file names to legal server names.
Since: TWiki::Plugins::VERSION 1.2
Spaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space.
Since: TWiki::Plugins::VERSION 1.2
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Returns 1 if $value
is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in $value
are ignored.
If the value is undef, then $default
is returned. If $default
is
not specified it is taken as 0.
Since: $TWiki::Plugins::VERSION 1.2
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Compose fully qualified 'oops' dialog URL
$web
- Web name, e.g. 'Main'
. The current web is taken if empty
$topic
- Topic name, e.g. 'WebNotify'
$template
- Oops template name, e.g. 'oopsmistake'
. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'.
$param1
... $param4
- Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
$url
URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the
oopstoestuckerror
template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use getScriptUrl
instead:
my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0;
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Test if any access restrictions are set for this web, ignoring settings on individual pages
$web
- Web name, required, e.g. 'Sandbox'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use getPreferencesValue
instead to determine
what permissions are set on the web, for example:
foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } }
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (7 - 2008-01-22 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | This module defines official functions that Plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | This module defines official functions that Plugins | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
can use to interact with the TWiki engine and content.
Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible. The version of the TWiki::Func module is defined by the VERSION number of the TWiki::Plugins module, currently 6.10. This can be shown | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | by the %PLUGINVERSION% variable. The 'Since' field in the function
documentation refers to the VERSION number and the date that the function
was addded. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | by the %PLUGINVERSION% TWiki variable, and accessed in code using
$TWiki::Plugins::VERSION . The 'Since' field in the function
documentation refers to $TWiki::Plugins::VERSION . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Note: Beware! These methods should only ever be called
from the context of a TWiki Plugin. They require a Plugins SESSION context to be
established before they are called, and will not work if simply called from
another TWiki module. For example,
use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Notes on use of $TWiki::Plugins::VERSION (from 1.2 forwards):
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | In addition, deprecation of functions in the interface trigger a minor
version increment. Note that deprecated functions are not removed, they
are merely frozen, and plugin authors are recommended to stop using them.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example,
the script:
use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: $url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | getPubUrlPath( ) -> $path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Compose fully qualified 'oops' dialog URL | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Get pub URL path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | This might be used like this: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Return: $path URL path of pub directory, e.g. "/pub" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception.
use Error qw( :try ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | getExternalResource( $url ) -> $response | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | and let TWiki handle the cleanup. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | getPubUrlPath( ) -> $path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note that the $url may have an optional user and password, as specified by | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | the relevant RFC. Any proxy set in configure is honoured. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Get pub URL path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | The $response is an object that is known to implement the following subset of | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 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:
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Return: $path URL path of pub directory, e.g. "/pub" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note that if LWP is not available, this function: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | In the event of the server returning an error, then is_error() will return | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 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). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Note: Callers can easily check the availability of other HTTP::Response methods as follows: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | my $response = TWiki::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 } Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | @keys
Get a list of all the names of session variables. The list is unsorted.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value.
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $boolean
Clear a session value that was set using
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context. The context is a set of identifiers that are set during specific phases of TWiki 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 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | in the TWikiTemplates topic. Please be careful not to | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | in the TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | pushTopicContext($web, $topic)
$web.$topic
from now on. All the preferences will be reset to those of the new topic.
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.
It is the duty of the caller to restore the original context by calling
Note that this call does not re-initialise plugins, so if you have used
global variables to remember the web and topic in Since: TWiki::Plugins::VERSION 1.2
popTopicContext()
Returns the TWiki context to the state it was in before the
Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | setPreferencesValue($name, $val)
Set the preferences value so that future calls to getPreferencesValue will
return this value, and The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function. Returns 1 if the preference was defined, and 0 otherwise. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getDefaultUserName( ) -> $loginName | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Get default user name as defined in the configuration as DefaultUserLogin
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | getWikiName( ) -> $wikiName | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | getCanonicalUserID( $user ) -> $cUID | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Return the cUID of the specified user. A cUID is a unique identifier which
is assigned by TWiki for each user.
BEWARE: While the default TWikiUserMapping uses a cUID that looks like a user's
LoginName, some characters are modified to make them compatible with rcs.
Additionally, other usermappings will use other conventions - the JoomlauserMapping
for example, has cUIDs like 'JoomlaeUserMapping_1234'.
If $user is undefined Get the cUID of logged in user, and will generally be 'BaseUserMapping_666'
Return: Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Get Wiki name of logged in user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | getWikiName( $user ) -> $wikiNamereturn the WikiName of the specified user if $user is undefined Get Wiki name of logged in user
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: $wikiName Wiki Name, e.g. 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
getWikiUserName( $user ) -> $wikiName | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | getWikiUserName( ) -> $wikiName | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | return the userWeb.WikiName of the specified user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | if $user is undefined Get Wiki name of logged in user
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Get Wiki name of logged in user with web prefix | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: $wikiName Wiki Name, e.g. "Main.JohnDoe"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginName | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Translate a Wiki name (or login name or cUID, if it can) to a login name. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Translate a Wiki name to a login name based on Main.TWikiUsers topic | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Return: $loginName Login name of user, e.g. 'jdoe' | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Return: $loginName Login name of user, e.g. 'jdoe' , or undef if not | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | matched. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | 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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiName | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Translate a login name to a Wiki name | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Translate a login name to a Wiki name based on Main.TWikiUsers topic | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe' | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | userToWikiName will always return a name, if the user does not exist in the mapping, the $loginName parameter is returned. (backward compatibility) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | emailToWikiNames( $email, $dontAddWeb ) -> @wikiNames
Since: TWiki::Plugins::VERSION 1.2
wikiNameToEmails( $wikiname ) -> @emails
Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | permissionsSet( $web ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isAnAdmin( $login ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Test if any access restrictions are set for this web, ignoring settings on individual pages
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Find out if the user is an admin or not. If the user is not given, the currently logged-in user is assumed. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isGroupMember( $group, $login ) -> $booleanFind out if $login is in the named group. e.g. if( TWiki::Func::isGroupMember( "HesperionXXGroup", "jordi" )) { ... }If $user is undef , it defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
eachUser() -> $iteratorGet an iterator over the list of all the registered users not including groups. The iterator will return each wiki name in turn (e.g. 'FredBloggs').Use it as follows: my $iterator = TWiki::Func::eachUser(); while ($it->hasNext()) { my $user = $it->next(); # $user is a wikiname } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
eachMembership($wikiname) -> $iteratorGet an iterator over the names of all groups that the user is a member of. If$wikiname is undef , defaults to the currently logged-in user.
Since: TWiki::Plugins::VERSION 1.2
eachGroup() -> $iteratorGet an iterator over all groups.Use it as follows: my $iterator = TWiki::Func::eachGroup(); while ($it->hasNext()) { my $group = $it->next(); # $group is a group name e.g. TWikiAdminGroup } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2
isGroup( $group ) -> $boolean
Checks if
eachGroupMember($group) -> $iteratorGet an iterator over all the members of the named group. Returns undef if $group is not a valid group.Use it as follows: my $iterator = TWiki::Func::eachGroupMember('RadioheadGroup'); while ($it->hasNext()) { my $user = $it->next(); # $user is a wiki name e.g. 'TomYorke', 'PhilSelway' } WARNING on large sites, this could be a long list! Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
checkAccessPermission( $type, $wikiName, $text, $topic, $web, $meta ) -> $booleanCheck access permission for a topic based on the | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | TWiki.TWikiAccessControl rules | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | TWiki.TWikiAccessControl rules | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Note the wierd parameter order is due to compatibility constraints with earlier TWiki releases. Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic , then a call to checkAccessPermissions('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true .
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | eachChangeSince($web, $time) -> $iterator
Get an iterator over the list of all the changes in the given web between
Use it as follows: my $iterator = TWiki::Func::eachChangeSince( $web, time() - 7 * 24 * 60 * 60); # the last 7 days while ($it->hasNext()) { my $change = $it->next(); # $change is a perl hash that contains the following fields: # topic => topic name # user => wikiname - wikiname of user who made the change # time => time of the change # revision => revision number *after* the change # more => more info about the change (e.g. 'minor') } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
@topics
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$web and $topic are parsed as described in the documentation for normalizeWebTopicName . | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Specifically, the Main is used if $web is not specified and $topic has no web specifier. To get an expected behaviour it is recommened to specify the current web for $web; don't leave it empty. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
checkTopicEditLock( $web, $topic, $script ) -> ( $oopsUrl, $loginName, $unlockTime )Check if a lease has been taken by some other user.
( $oopsUrl, $loginName, $unlockTime ) - The $oopsUrl for calling redirectCgiQuery(), user's $loginName , and estimated $unlockTime in minutes, or ( '', '', 0 ) if no lease exists.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
setTopicEditLock( $web, $topic, $lock )
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The edit script
always takes out a lease.
It is impossible to fully lock a topic. Concurrent changes will be merged. Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
saveTopic( $web, $topic, $meta, $text, $options ) -> $error
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) For example, my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g.
saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrlSave topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$oopsUrl Empty string if OK; the $oopsUrl for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
moveTopic( $web, $topic, $newWeb, $newTopic )
The destination topic must not already exist. Rename a topic to the $TWiki::cfg{TrashWebName} to delete it. Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
getRevisionInfo($web, $topic, $rev, $attachment ) -> ( $date, $user, $rev, $comment )Get revision info of a topic or attachment
( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
NOTE: if you are trying to get revision info for a topic, use
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | more efficient, and returns a user object that contains other user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | more efficient. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | information. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getRevisionAtTime( $web, $topic, $time ) -> $revGet the revision number of a topic at a specific time.
Since: TWiki::Plugins::VERSION 1.1
readTopic( $web, $topic, $rev ) -> ( $meta, $text )Read topic text and meta data, regardless of access permissions.
( $meta, $text ) Meta data object and topic text
This method ignores topic access permissions. You should be careful to use Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $textRead topic text, including meta data
$text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | This method is more efficient than readTopic , but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer.. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | This method is more efficient than readTopic , but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
attachmentExists( $web, $topic, $attachment ) -> $booleanTest if attachment exists
normalizeWebTopicName .
Since: TWiki::Plugins::VERSION 1.1
readAttachment( $web, $topic, $name, $rev ) -> $data
readTopic . If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; } Since: TWiki::Plugins::VERSION 1.1
saveAttachment( $web, $topic, $attachment, $opts )
$opts may include:
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1
moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
The destination topic must already exist, but the destination attachment must not exist. Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple }; Since: TWiki::Plugins::VERSION 1.1
Assembling Pages
readTemplate( $name, $skin ) -> $text | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Read a template or skin. Embedded template directives get expanded | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Read a template or skin. Embedded template directives get expanded | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$text Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
loadTemplate ( $name, $skin, $web ) -> $text
Since: TWiki::Plugins::VERSION 1.1 Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition. How TWiki searches for templates is described in TWikiTemplates. If template text is found, extracts include statements and fully expands them.
expandTemplate( $def ) -> $stringDo a , only expanding the template (not expanding any variables other than %TMPL)
Since: TWiki::Plugins::VERSION 1.1 A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
writeHeader( $query, $contentLength )Prints a basic content-type HTML header for text/html to standard out | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: none
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
redirectCgiQuery( $query, $url, $passthru )Redirect to URL
Return: none Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | file (see {PassthroughDir} in =configure ). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | file. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Note that if $passthru is set, then any parameters in $url will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1); $passthru does nothing if $url does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
addToHEAD( $id, $header )
Adds
All TWiki variables present in
Note that this is not the same as the HTTP header, which is modified through the Plugins Since: TWiki::Plugins::VERSION 1.1 example: TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />') | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | expandCommonVariables( $text, $topic, $web ) -> $text | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | expandCommonVariables( $text, $topic, $web, $meta ) -> $text | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Expand all common %VARIABLES%
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return: $text Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) See also: expandVariablesOnTopicCreation
renderText( $text, $web ) -> $text | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
$text XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by
$text XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
sendEmail ( $text, $retries ) -> $error
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body. Since: TWiki::Plugins::VERSION 1.1
wikiToEmail( $wikiName ) -> $email
Since: TWiki::Plugins::VERSION 1.1
Creating New Topics
expandVariablesOnTopicCreation ( $text ) -> $textExpand the limited set of variables that are always expanded during topic creation
Since: TWiki::Plugins::VERSION 1.1 Expands only the variables expected in templates that must be statically expanded in new content. The expanded variables are:
See also: expandVariables
Special handlersSpecial handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
registerTagHandler( $var, \&fn, $syntax )Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, and are expanded at the same time. This is a lot more efficient than using the
Since: TWiki::Plugins::VERSION 1.1 The variable handler function must be of the form: sub handler(\%session, \%params, $topic, $web)where:
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this: %EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in
registerRESTHandler( $alias, \&fn, )Should only be called from initPlugin. Adds a function to the dispatch table of the REST interface
Since: TWiki::Plugins::VERSION 1.1 The handler function must be of the form: sub handler(\%session)where:
From the REST interface, the name of the plugin must be used as the subject of the invokation. Example The EmptyPlugin has the following call in the initPlugin handler: TWiki::Func::registerRESTHandler('example', \&restExample);
This adds the
note that the URL
(ie, with the name of the function instead of the alias) will not work. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
decodeFormatTokens($str) -> $unencodedString
TWiki has an informal standard set of tokens used in
then %WURBLE would be expanded before %MYTAG is evaluated. To avoid this TWiki uses escapes in the format string. For example:
This lets you enter arbitrary strings into parameters without worrying that TWiki will expand them before your plugin gets a chance to deal with them properly. Once you have processed your tag, you will want to expand these tokens to their proper value. That's what this function does.
Note thath $quot, $percnt and $dollar all work *even if they are followed by alphanumeric characters*. You have been warned! Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Searching
searchInWebContent($searchString, $web, \@topics, \%options ) -> \%mapSearch for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
\%options hash may contain the following options:
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'. To iterate over the returned topics use: my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc Since: TWiki::Plugins::VERSION 1.1
Plugin-specific file handling
getWorkArea( $pluginName ) -> $directorypathGets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it. The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible. The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy. Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
readFile( $filename ) -> $textRead file, low level. Used for Plugin workarea.
$text Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
saveFile( $filename, $text )Save file, low level. Used for Plugin workarea.
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
General Utilities
getRegularExpression( $name ) -> $exprRetrieves a TWiki predefined regular expression or character class.
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004) Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions. In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example: my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example: my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
normalizeWebTopicName($web, $topic) -> ($web, $topic)Parse a web and topic name, supplying defaults as appropriate.
Since: TWiki::Plugins::VERSION 1.1
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | The symbols %USERSWEB%, %SYSTEMWEB%, %DOCWEB%, %MAINWEB% and %TWIKIWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | The symbols %USERSWEB%, %SYSTEMWEB% and %DOCWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | StaticMethod *sanitizeAttachmentName ($fname) -> ($fileName,$origName)Given a file namer, sanitise it according to the rules for transforming attachment names. Returns the sanitised name together with the basename before sanitisation. Sanitation includes filtering illegal characters and mapping client file names to legal server names. Since: TWiki::Plugins::VERSION 1.2
spaceOutWikiWord( $word, $sep ) -> $textSpaces out a wiki word by inserting a string (default: one space) between each word component. With parameter $sep any string may be used as separator between the word components; if $sep is undefined it defaults to a space. Since: TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
writeWarning( $text )Log Warning that may require admin intervention to data/warning.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
writeDebug( $text )Log debug message to data/debug.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
formatTime( $time, $format, $timezone ) -> $textFormat the time in seconds into the desired time string
$text Formatted time string
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | isTrue( $value, $default ) -> $boolean
Returns 1 if
If the value is undef, then Since: $TWiki::Plugins::VERSION 1.2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
isValidWikiWord ( $text ) -> $booleanCheck for a valid WikiWord or WikiName
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
extractParameters($attr ) -> %paramsExtract all parameters from a variable string and returns a hash of parameters
%params Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
extractNameValuePair( $attr, $name ) -> $valueExtract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$value Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Deprecated functionsFrom time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed. Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of TWiki::Plugins before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
getScriptUrlPath( ) -> $pathGet script URL path
DEPRECATED since 1.1 - use
Return: WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
DEPRECATED since 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException( 'toestuckerror', web => $web, topic => $topic, params => [ 'I got my toe stuck' ]);(this example will use the oopstoestuckerror template.)
If this is not possible (e.g. in a REST handler that does not trap the exception)
then you can use my $url = TWiki::Func::getScriptUrl($web, $topic, 'oops', template => 'oopstoestuckerror', param1 => 'I got my toe stuck'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
DEPRECATED since 1.2 - use foreach my $type qw( ALLOW DENY ) { foreach my $action qw( CHANGE VIEW ) { my $pref = $type . 'WEB' . $action; my $val = getPreferencesValue( $pref, $web ) || ''; if( $val =~ /\S/ ) { print "$pref is set to $val on $web\n"; } } } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
@webs
|
<<O>> Difference Topic TWikiFuncDotPm (6 - 2007-03-03 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value.
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $boolean
Clear a session value that was set using
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context. The context is a set of identifiers that are set during specific phases of TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | checkAccessPermission( $type, $wikiName, $text, $topic, $web, $meta ) -> $boolean | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Check access permission for a topic based on the TWiki.TWikiAccessControl rules
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | Check access permission for a topic based on the
TWiki.TWikiAccessControl rules
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | If $wikiName is '', 0 or undef then access is always permitted.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
A perl true result indicates that access is permitted. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
Note the wierd parameter order is due to compatibility constraints with
earlier TWiki releases.
Tip if you want, you can use this method to check your own access control types. For example, if you:
ThatWeb.ThisTopic , then a call to checkAccessPermissions('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
|
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use checkAccessPermissions
to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter.
$contentLength
- Length of content
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file (see {PassthroughDir} in =configure
).
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB%, %DOCWEB%, %MAINWEB% and %TWIKIWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (5 - 2007-02-05 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value.
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $boolean
Clear a session value that was set using
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context. The context is a set of identifiers that are set during specific phases of TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
NOTE: As of TWiki4.1, if
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
NOTE: As of TWiki4.1, if
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web
|
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
Get revision info of a topic or attachment
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use checkAccessPermissions
to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
Do a , only expanding the template (not expanding any variables other than %TMPL)
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter.
$contentLength
- Length of content
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
$passthru
- enable passthrough.
Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The $passthru
parameter allows you to pass the parameters that were passed
to the current query on to the target URL, as long as it is another URL on the
same TWiki installation. If $passthru
is set to a true value, then TWiki
will save the current URL parameters, and then try to restore them on the
other side of the redirect. Parameters are stored on the server in a cache
file (see {PassthroughDir} in =configure
).
Note that if $passthru
is set, then any parameters in $url
will be lost
when the old parameters are restored. if you want to change any parameter
values, you will need to do that in the current CGI query before redirecting
e.g.
my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
$passthru
does nothing if $url
does not point to a script in the current
TWiki installation.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Adds $header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
$id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
Expand the limited set of variables that are always expanded during topic creation
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler
) in the following ways:
commonTagsHandler
is only called later, when all system tags have already been expanded (though they are expanded again after commonTagsHandler
returns).
FRED
defines both %FRED{...}%
and also %FRED%
.
return '%SERVERTIME%';
). It won't work.
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.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web/Subweb/Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Subweb.Topic' ) | ( 'Web/Subweb', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure
.
The symbols %USERSWEB%, %SYSTEMWEB%, %DOCWEB%, %MAINWEB% and %TWIKIWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
Input | Return |
---|---|
( '%USERSWEB%', 'Topic' ) | ( 'Main', 'Topic' ) |
( '%SYSTEMWEB%', 'Topic' ) | ( 'TWiki', 'Topic' ) |
( '', '%DOCWEB%.Topic' ) | ( 'TWiki', 'Topic' ) |
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (4 - 2007-01-16 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
Return: $url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $boolean | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Set a session value via the client session module | ||||||||||||||||||||||||||||||||||||||||||
> > | Set a session value. | ||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $boolean | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Clear a session value via the client session module
| ||||||||||||||||||||||||||||||||||||||||||
> > | Clear a session value that was set using setSessionValue .
| ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Return: true if the session value was cleared | ||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hash | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
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 TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | NOTE: As of TWiki4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then
preferences set in the plugin topic will be ignored. | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | NOTE: As of TWiki4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then
preferences set in the plugin topic will be ignored. | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
| |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | NOTE: As of TWiki4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then
preferences set in the plugin topic will be ignored. | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | NOTE: As of TWiki4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then
preferences set in the plugin topic will be ignored. | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
$filter may also contain the word 'public' which will further filter
out webs that have NOSEARCHALL set on them.
'allowed' filters out webs the current user can't read.
For example, the deprecated getPublicWebList function can be duplicated as follows: my @webs = TWiki::Func::getListOfWebs( "user,public" ); Since: TWiki::Plugins::VERSION 1.1
webExists( $web ) -> $booleanTest if web exists
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
createWeb( $newWeb, $baseWeb, $opts )
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::createWeb( "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1
moveWeb( $oldName, $newName )Move (rename) a web.
use Error qw( :try ); use TWiki::AccessControlException; try { TWiki::Func::moveWeb( "Oldweb", "Newweb" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
To delete a web, move it to a subweb of TWiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" ); Since: TWiki::Plugins::VERSION 1.1
@topics
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | checkTopicEditLock( $web, $topic ) -> ( $oopsUrl, $loginName, $unlockTime ) | ||||||||||||||||||||||||||||||||||||||||||
> > | checkTopicEditLock( $web, $topic, $script ) -> ( $oopsUrl, $loginName, $unlockTime ) | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Check if a lease has been taken by some other user.
( $oopsUrl, $loginName, $unlockTime ) - The $oopsUrl for calling redirectCgiQuery(), user's $loginName , and estimated $unlockTime in minutes, or ( '', '', 0 ) if no lease exists. | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
setTopicEditLock( $web, $topic, $lock ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The It is impossible to fully lock a topic. Concurrent changes will be merged. Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
saveTopic( $web, $topic, $meta, $text, $options ) -> $error | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001) For example, my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g.
saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrlSave topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$oopsUrl Empty string if OK; the $oopsUrl for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
moveTopic( $web, $topic, $newWeb, $newTopic ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
The destination topic must not already exist. Rename a topic to the $TWiki::cfg{TrashWebName} to delete it. Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
getRevisionInfo($web, $topic, $rev, $attachment ) -> ( $date, $user, $rev, $comment ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Get revision info of a topic or attachment
( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
NOTE: if you are trying to get revision info for a topic, use
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned. Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getRevisionAtTime( $web, $topic, $time ) -> $revGet the revision number of a topic at a specific time.
Since: TWiki::Plugins::VERSION 1.1
readTopic( $web, $topic, $rev ) -> ( $meta, $text )Read topic text and meta data, regardless of access permissions.
( $meta, $text ) Meta data object and topic text
This method ignores topic access permissions. You should be careful to use Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $textRead topic text, including meta data
$text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
attachmentExists( $web, $topic, $attachment ) -> $booleanTest if attachment exists
normalizeWebTopicName .
Since: TWiki::Plugins::VERSION 1.1
readAttachment( $web, $topic, $name, $rev ) -> $data | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
readTopic . If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; } Since: TWiki::Plugins::VERSION 1.1
saveAttachment( $web, $topic, $attachment, $opts ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
$opts may include:
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... }; Since: TWiki::Plugins::VERSION 1.1
moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
The destination topic must already exist, but the destination attachment must not exist. Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple }; Since: TWiki::Plugins::VERSION 1.1
Assembling Pages
readTemplate( $name, $skin ) -> $textRead a template or skin. Embedded template directives get expanded
$text Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
loadTemplate ( $name, $skin, $web ) -> $text
Since: TWiki::Plugins::VERSION 1.1 Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition. How TWiki searches for templates is described in TWikiTemplates. If template text is found, extracts include statements and fully expands them.
expandTemplate( $def ) -> $string | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Do a , only expanding the template (not expanding any variables other than %TMPL)
Since: TWiki::Plugins::VERSION 1.1 A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
writeHeader( $query, $contentLength )Prints a basic content-type HTML header for text/html to standard out
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | redirectCgiQuery( $query, $url ) | ||||||||||||||||||||||||||||||||||||||||||
> > | redirectCgiQuery( $query, $url, $passthru ) | ||||||||||||||||||||||||||||||||||||||||||
Redirect to URL
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Return: none, never returns | ||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Return: none
Print output to STDOUT that will cause a 302 redirect to a new URL. Nothing more should be printed to STDOUT after this method has been called.
The
Note that if my $query = TWiki::Func::getCgiQuery(); $query->param(-name => 'text', -value => 'Different text'); TWiki::Func::redirectCgiQuery( undef, TWiki::Func::getScriptUrl($web, $topic, 'edit'), 1); $passthru does nothing if $url does not point to a script in the current
TWiki installation. | ||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
addToHEAD( $id, $header ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Adds $header to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css.
All TWiki variables present in
Note that this is not the same as the HTTP header, which is modified through the Plugins Since: TWiki::Plugins::VERSION 1.1 example: TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
expandCommonVariables( $text, $topic, $web ) -> $text
Expand all common
$text Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) See also: expandVariablesOnTopicCreation
renderText( $text, $web ) -> $textRender text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by
$text XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
sendEmail ( $text, $retries ) -> $error | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body. Since: TWiki::Plugins::VERSION 1.1
wikiToEmail( $wikiName ) -> $email | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.1
Creating New Topics
expandVariablesOnTopicCreation ( $text ) -> $text | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Expand the limited set of variables that are always expanded during topic creation
Since: TWiki::Plugins::VERSION 1.1 Expands only the variables expected in templates that must be statically expanded in new content. The expanded variables are:
See also: expandVariables
Special handlers | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Special handlers can be defined to make functions in plugins behave as if they were built-in to TWiki.
registerTagHandler( $var, \&fn, $syntax ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Should only be called from initPlugin.
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, and are expanded at the same time. This is a lot more efficient than using the
Since: TWiki::Plugins::VERSION 1.1 The variable handler function must be of the form: sub handler(\%session, \%params, $topic, $web)where:
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this: %EXEC{"ps -Af" silent="on"}% | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Registered tags differ from tags implemented using the old TWiki approach (text substitution in commonTagsHandler ) in the following ways:
| ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
registerRESTHandler( $alias, \&fn, ) | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Should only be called from initPlugin.
Adds a function to the dispatch table of the REST interface
Since: TWiki::Plugins::VERSION 1.1 The handler function must be of the form: sub handler(\%session)where:
From the REST interface, the name of the plugin must be used as the subject of the invokation. Example The EmptyPlugin has the following call in the initPlugin handler: TWiki::Func::registerRESTHandler('example', \&restExample);
This adds the
note that the URL
(ie, with the name of the function instead of the alias) will not work.
Searching
searchInWebContent($searchString, $web, \@topics, \%options ) -> \%map | |||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | |||||||||||||||||||||||||||||||||||||||||||
Search for a string in the content of a web. The search is over all content, including meta-data. Meta-data matches will be returned as formatted lines within the topic content (meta-data matches are returned as lines of the format %META:\w+{.*}%)
\%options hash may contain the following options:
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'. To iterate over the returned topics use: my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc Since: TWiki::Plugins::VERSION 1.1
Plugin-specific file handling
getWorkArea( $pluginName ) -> $directorypathGets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it. The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible. The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy. Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
readFile( $filename ) -> $textRead file, low level. Used for Plugin workarea.
$text Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
saveFile( $filename, $text )Save file, low level. Used for Plugin workarea.
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
General Utilities
getRegularExpression( $name ) -> $exprRetrieves a TWiki predefined regular expression or character class.
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004) Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions. In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example: my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example: my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
normalizeWebTopicName($web, $topic) -> ($web, $topic)Parse a web and topic name, supplying defaults as appropriate.
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | Return: the parsed Web/Topic pai | ||||||||||||||||||||||||||||||||||||||||||
> > | Return: the parsed Web/Topic pair | ||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.1 | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||
< < | where Main and TWiki are the web names set in $cfg{UsersWebName} and $cfg{SystemWebName} respectively. | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | Note that hierarchical web names (SubWeb) are only available if hierarchical webs are enabled in configure . | ||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||
> > | The symbols %USERSWEB%, %SYSTEMWEB%, %DOCWEB%, %MAINWEB% and %TWIKIWEB% can be used in the input to represent the web names set in $cfg{UsersWebName} and $cfg{SystemWebName}. For example:
| ||||||||||||||||||||||||||||||||||||||||||
writeWarning( $text )Log Warning that may require admin intervention to data/warning.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
writeDebug( $text )Log debug message to data/debug.txt
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
formatTime( $time, $format, $timezone ) -> $textFormat the time in seconds into the desired time string
$text Formatted time string
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
isValidWikiWord ( $text ) -> $booleanCheck for a valid WikiWord or WikiName
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
extractParameters($attr ) -> %paramsExtract all parameters from a variable string and returns a hash of parameters
%params Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
extractNameValuePair( $attr, $name ) -> $valueExtract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$value Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Deprecated functionsFrom time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed. Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of TWiki::Plugins before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
getScriptUrlPath( ) -> $pathGet script URL path
DEPRECATED since 1.1 - use
Return: WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it. Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
@webs
| |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | DEPRECATED since 1.1 - use the content handling functions to manipulate topics instead | ||||||||||||||||||||||||||||||||||||||||||
> > | DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulate topics instead | ||||||||||||||||||||||||||||||||||||||||||
Get data directory (topic file root)
Return: This function violates store encapsulation and is therefore deprecated. Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
getPubDir( ) -> $dir | |||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||
< < | DEPRECATED since 1.1 - use the content handling functions to manipulateattachments instead | ||||||||||||||||||||||||||||||||||||||||||
> > | DEPRECATED since 1.1 - use the "Webs, Topics and Attachments" functions to manipulateattachments instead | ||||||||||||||||||||||||||||||||||||||||||
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: This function violates store encapsulation and is therefore deprecated.
Use Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
checkDependencies( $moduleName, $dependenciesRef ) -> $error
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004) |
<<O>> Difference Topic TWikiFuncDotPm (3 - 2006-10-25 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value via the client session module
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $booleanClear a session value via the client session module
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context.The context is a set of identifiers that are set during specific phases of TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Changed: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Added: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
> > | A perl true result indicates that access is permitted. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web |
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use checkAccessPermissions
to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the current user.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $web, $topic, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter.
$contentLength
- Length of content
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css. $id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Adds a function to the dispatch table of the REST interface
$alias
- The name .
\&fn
- Reference to the function.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
( 'Main', 'Topic' ) | ( 'Main', 'Topic' ) |
( 'TWiki', 'Topic' ) | ( 'TWiki', 'Topic' ) |
Main
and TWiki
are the web names set in $cfg{UsersWebName} and $cfg{SystemWebName} respectively.
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (2 - 2006-06-25 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value via the client session module
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $booleanClear a session value via the client session module
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context.The context is a set of identifiers that are set during specific phases of TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Synonymous with TWiki::Func::getPreferencesValue('WIKITOOLNAME'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Synonymous with TWiki::Func::getPreferencesValue('MAINWEB'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Deleted: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
< < | Synonymous with TWiki::Func::getPreferencesValue('TWIKIWEB'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web |
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use checkAccessPermissions
to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef will be returned.readTopic
. If the attachment does not exist, or cannot be read, undef
will be returned. If the revision is not specified, the latest version will
be returned.my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try {
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter.
$contentLength
- Length of content
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css. $id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Adds a function to the dispatch table of the REST interface
$alias
- The name .
\&fn
- Reference to the function.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
( 'Main', 'Topic' ) | ( 'Main', 'Topic' ) |
( 'TWiki', 'Topic' ) | ( 'TWiki', 'Topic' ) |
Main
and TWiki
are the web names set in $cfg{UsersWebName} and $cfg{SystemWebName} respectively.
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
<<O>> Difference Topic TWikiFuncDotPm (1 - 2006-02-01 - TWikiContributor) |
Package =TWiki::Func
<-- STARTINCLUDE required for huge TWikiDocumentation topic -->
Official list of stable TWiki functions for Plugin developers This module defines official functions that Plugins can use to interact with the TWiki engine and content. Refer to EmptyPlugin and lib/TWiki/Plugins/EmptyPlugin.pm for a template Plugin and documentation on how to write a Plugin. Plugins should only use functions published in this module. If you use functions in other TWiki libraries you might create a security hole and you will probably need to change your Plugin when you upgrade TWiki. Deprecated functions will still work in older code, though they should not be called in new Plugins and should be replaced in older Plugins as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 6.10. This can be shown
by the Note: Beware! These methods should only ever be called from the context of a TWiki Plugin. They require a Plugins SESSION context to be established before they are called, and will not work if simply called from another TWiki module. For example, use TWiki; print TWiki::Func::getSkin(),"\n";will fail with Can't call method "getSkin" on an undefined value at TWiki/Func.pm line 83 .
If you want to call the methods outside the context of a plugin, you can create a Plugins SESSION object. For example, the script: use TWiki: $TWiki::Plugins::SESSION = new TWiki(); print TWiki::Func::getSkin(),"\n";will work happily.
On this page:
Environment
getSkin( ) -> $skin
Get the skin path, set by the
Return: Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $hostGet protocol, domain and optional port of script URL
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $urlCompose fully qualified URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $urlCompose fully qualified view URL
$url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $urlCompose fully qualified 'oops' dialog URL
$url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
This might be used like this: my $url = TWiki::Func::getOopsUrl($web, $topic, 'oopsmistake', 'I made a boo-boo'); TWiki::Func::redirectCgiQuery( undef, $url ); return 0; Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002) Since TWiki::Plugins::VERSION 1.1, the recommended approach is to throw an oops exception. use Error qw( :try ); throw TWiki::OopsException($web, $topic, undef, 0, [ 'I made a boo-boo' ]);and let TWiki handle the cleanup.
getPubUrlPath( ) -> $pathGet pub URL path
Return: Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $queryGet CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getSessionValue( $key ) -> $valueGet a session value from the client session module
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $booleanSet a session value via the client session module
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $booleanClear a session value via the client session module
Since: TWiki::Plugins::VERSION 1.1
getContext() -> \%hashGet a hash of context identifiers representing the currently active context.The context is a set of identifiers that are set during specific phases of TWiki 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 TWikiTemplates 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: sub initPlugin { TWiki::Func::getContext()->{'MyID'} = 1; ...This can be used in SecondPlugin.pm like this: sub initPlugin { if( TWiki::Func::getContext()->{'MyID'} ) { ... } ...or in a template, like this: %TMPL:DEF{"ON"}% Not off %TMPL:END% %TMPL:DEF{"OFF"}% Not on %TMPL:END% %TMPL:P{context="MyID" then="ON" else="OFF"}%or in a topic: %IF{"context MyID" then="MyID is ON" else="MyID is OFF"}%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. Since: TWiki::Plugins::VERSION 1.1
Preferences
getPreferencesValue( $key, $web ) -> $valueGet a preferences value from TWiki or from a Plugin
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesValue( $key ) -> $valueGet a preferences value from your Plugin
$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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getPreferencesFlag( $key, $web ) -> $valueGet a preferences flag from TWiki or from a Plugin
$value Preferences flag '1' (if set), or "0" (for preferences values "off" , "no" and "0" )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPluginPreferencesFlag( $key ) -> $booleanGet a preferences flag from your Plugin
"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. TWiki::Plugins::MyPlugin::MyModule) Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getWikiToolName( ) -> $nameGet toolname as defined in TWiki.cfg
Return: Synonymous with TWiki::Func::getPreferencesValue('WIKITOOLNAME'); Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $nameGet name of Main web as defined in TWiki.cfg
Return: Synonymous with TWiki::Func::getPreferencesValue('MAINWEB'); Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $nameGet name of TWiki documentation web as defined in TWiki.cfg
Return: Synonymous with TWiki::Func::getPreferencesValue('TWIKIWEB'); Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiNameGet Wiki name of logged in user
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( ) -> $wikiNameGet Wiki name of logged in user with web prefix
Return: Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginNameTranslate a Wiki name to a login name based on Main.TWikiUsers topic
$loginName Login name of user, e.g. 'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiNameTranslate a login name to a Wiki name based on Main.TWikiUsers topic
$wikiName Wiki name of user, e.g. 'Main.JohnDoe' or 'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $booleanTest if logged in user is a guest (TWikiGuest) Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
permissionsSet( $web ) -> $booleanTest if any access restrictions are set for this web, ignoring settings on individual pages
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $booleanCheck access permission for a topic based on the TWiki.TWikiAccessControl rules
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Webs, Topics and Attachments
@web |
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ) $text =~ s/APPLE/ORANGE/g; TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note: Plugins handlers ( e.g. beforeSaveHandler
) will be called as
appropriate.
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$text
- Topic text to save, assumed to include meta data
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK
$dontNotify
- Set to "1"
if not to notify users of the change
$oopsUrl
Empty string if OK; the $oopsUrl
for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than saveTopic
.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic ); # check for oops URL in case of error: if( $text =~ /^http.*?\/oops/ ) { TWiki::Func::redirectCgiQuery( $query, $text ); return; } # do topic text manipulation like: $text =~ s/old/new/g; # do meta data manipulation like: $text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/; $oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
$web
source web - required
$topic
source topic - required
$newWeb
dest web
$newTopic
dest topic
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
Since: TWiki::Plugins::VERSION 1.1
use Error qw( :try ); try { moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" ); } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } otherwise { ... };
$web
- Web name, optional, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revsion number, or tag name (can be in the format 1.2, or just the minor number)
$attachment
-attachment filename
( $date, $user, $rev, $comment )
List with: ( last update date, login name of last user, minor part of top revision number ), e.g. ( 1234561, 'phoeny', "5" )
$date | in epochSec |
$user | Wiki name of the author (not login name) |
$rev | actual rev number |
$comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo
instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned the login name of the user rather than the wiki name; the code documentation was totally unclear, and we have been unable to establish the intent. However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
Get the revision number of a topic at a specific time.
$web
- web for topic
$topic
- topic
$time
- time (in epoch secs) for the rev
Since: TWiki::Plugins::VERSION 1.1
Read topic text and meta data, regardless of access permissions.
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name, required, e.g. 'TokyoOffice'
$rev
- revision to read (default latest)
( $meta, $text )
Meta data object and topic text
$meta
is a perl 'object' of class TWiki::Meta
. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the lib/TWiki/Meta.pm
file.
This method ignores topic access permissions. You should be careful to use checkAccessPermissions
to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Read topic text, including meta data
$web
- Web name, e.g. 'Main'
, or empty
$topic
- Topic name, e.g. 'MyTopic'
, or "Main.MyTopic"
$rev
- Topic revision to read, optional. Specify the minor part of the revision, e.g. "5"
, not "1.5"
; the top revision is returned if omitted or empty.
$ignorePermissions
- Set to "1"
if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
$text
Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than readTopic
, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
Test if attachment exists
$web
- Web name, optional, e.g. Main
.
$topic
- Topic name, required, e.g. TokyoOffice
, or Main.TokyoOffice
$attachment
- attachment name, e.g.=logo.gif=
normalizeWebTopicName
.
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic
$name
- attachment name
$rev
- revision to read (default latest)
readTopic
. If the attachment does not exist, or cannot be read, undef will be returned.
View permission on the topic is required for the read to be successful. Access control violations are flagged by a TWiki::AccessControlException. Permissions are checked for the user passed in.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic ); my @attachments = $meta->find( 'FILEATTACHMENT' ); foreach my $a ( @attachments ) { try { my $data = TWiki::Func::readAttachment( $meta, $a->{name} ); ... } catch TWiki::AccessControlException with { }; }
Since: TWiki::Plugins::VERSION 1.1
$web
- web for topic
$topic
- topic to atach to
$attachment
- name of the attachment
$opts
- Ref to hash of options
$opts
may include:
dontlog |
don't log this change in twiki log |
comment |
comment for save |
hide |
if the attachment is to be hidden in normal topic view |
stream |
Stream of file to upload |
file |
Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath |
Client path to file |
filesize |
Size of uploaded data |
filedate |
Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try { TWiki::Func::saveAttachment( $web, $topic, 'image.gif', { file => 'image.gif', comment => 'Picture of Health', hide => 1 } ); } catch Error::Simple with { # see documentation on Error } otherwise { ... };
Since: TWiki::Plugins::VERSION 1.1
$web
source web - required
$topic
source topic - required
$attachment
source attachment - required
$newWeb
dest web
$newTopic
dest topic
$newAttachment
dest attachment
The destination topic must already exist, but the destination attachment must not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try ); try { # move attachment between topics moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat", "Countries", "France" ); # Note destination attachment name is defaulted to the same as source } catch TWiki::AccessControlException with { my $e = shift; # see documentation on TWiki::AccessControlException } catch Error::Simple with { my $e = shift; # see documentation on Error::Simple };
Since: TWiki::Plugins::VERSION 1.1
Read a template or skin. Embedded template directives get expanded
$name
- Template name, e.g. 'view'
$skin
- Comma-separated list of skin names, optional, e.g. 'print'
$text
Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$name
- template file name
$skin
- comma-separated list of skins to use (default: current skin)
$web
- the web to look in for topics that contain templates (default: current web)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
$def
- template name
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on TWiki templates for more information.
Prints a basic content-type HTML header for text/html to standard out
$query
- CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter.
$contentLength
- Length of content
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Redirect to URL
$query
- CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead.
$url
- URL to redirect to
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$header
to the HTML header (the tag).
This is useful for Plugins that want to include some javascript custom css. $id
- Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR)
$header
- the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in $header
will be expanded before being inserted into the section.
Note that this is not the same as the HTTP header, which is modified through the Plugins modifyHeaderHandler
.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
Expand all common %VARIABLES%
$text
- Text with variables to expand, e.g. 'Current user is %WIKIUSER%'
$topic
- Current topic name, e.g. 'WebNotify'
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
Expanded text, e.g. 'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
Render text from TWiki markup into XHTML as defined in TWiki.TextFormattingRules
$text
- Text to render, e.g. '*bold* text and =fixed font='
$web
- Web name, optional, e.g. 'Main'
. The current web is taken if missing
$text
XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by renderText()
$pre
- Text occuring before the TWiki link syntax, optional
$web
- Web name, required, e.g. 'Main'
$topic
- Topic name to link to, required, e.g. 'WebNotify'
$label
- Link label, required. Usually the same as $topic
, e.g. 'notify'
$anchor
- Anchor, optional, e.g. '#Jump'
$createLink
- Set to '1'
to add question linked mark after topic name if topic does not exist;'0'
to suppress link for non-existing topics
$text
XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
$text
- text of the mail, including MIME headers
$retries
- number of times to retry the send (default 1)
To: liz@windsor.gov.uk From: serf@hovel.net CC: george@whitehouse.gov Subject: Revolution Dear Liz, Please abolish the monarchy (with King George's permission, of course) Thanks, A. PeasantLeave a blank line between the last header field and the message body.
Since: TWiki::Plugins::VERSION 1.1
$wikiName
- wiki name of the user
Since: TWiki::Plugins::VERSION 1.1
$text
- the text to process
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically expanded in new content.
The expanded variables are:
%DATE%
Signature-format date
%SERVERTIME%
See TWikiVariables
%GMTIME%
See TWikiVariables
%USERNAME%
Base login name
%WIKINAME%
Wiki name
%WIKIUSERNAME%
Wiki name with prepended web
%URLPARAM{...}%
- Parameters to the current CGI query
%NOP%
No-op
See also: expandVariables
Register a function to handle a simple variable. Handles both %VAR% and %VAR{...}%. Registered variables are treated the same as TWiki internal variables, 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 %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'. 'classic' syntax is appropriate where you want the variable to support classic TWiki syntax i.e. to accept the standard %MYVAR{ "unnamed" param1="value1" param2="value2" }%
syntax, as well as an unquoted default parameter, such as %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"}%
Since: TWiki::Plugins::VERSION 1.1
The variable handler function must be of the form:
sub handler(\%session, \%params, $topic, $web)where:
\%session
- a reference to the TWiki session object (may be ignored)
\%params
- a reference to a TWiki::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
sub initPlugin{ TWiki::Func::registerTagHandler('EXEC', \&boo); } sub boo { my( $session, $params, $topic, $web ) = @_; my $cmd = $params->{_DEFAULT}; return "NO COMMAND SPECIFIED" unless $cmd; my $result = `$cmd 2>&1`; return $params->{silent} ? '' : $result; } }would let you do this:
%EXEC{"ps -Af" silent="on"}%
Adds a function to the dispatch table of the REST interface
$alias
- The name .
\&fn
- Reference to the function.
Since: TWiki::Plugins::VERSION 1.1
The handler function must be of the form:
sub handler(\%session)where:
\%session
- a reference to the TWiki session object (may be ignored)
From the REST interface, the name of the plugin must be used as the subject of the invokation.
Example
The EmptyPlugin has the following call in the initPlugin handler:
TWiki::Func::registerRESTHandler('example', \&restExample);
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.
$searchString
- the search string, in egrep format
$web
- The web to search in
\@topics
- reference to a list of topics to search
\%option
- reference to an options hash
\%options
hash may contain the following options: type
- if regex
will perform a egrep-syntax RE search (default '')
casesensitive
- false to ignore case (defaulkt true)
files_without_match
- true to return files only (default false). If files_without_match
is specified, it will return on the first match in each topic (i.e. it will return only one match per topic, and will not return matching lines).
The return value is a reference to a hash which maps each matching topic name to a list of the lines in that topic that matched the search, as would be returned by 'grep'.
To iterate over the returned topics use:
my $result = TWiki::Func::searchInWebContent( "Slimy Toad", $web, \@topics, { casesensitive => 0, files_without_match => 0 } ); foreach my $topic (keys %$result ) { foreach my $matching_line ( @{$result->{$topic}} ) { ...etc
Since: TWiki::Plugins::VERSION 1.1
Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver user. By default it will not be web accessible.
The directory and it's contents are permanent, so Plugins must be careful to keep their areas tidy.
Since: TWiki::Plugins::VERSION 1.1 (Dec 2005)
Read file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
Content of file, empty if not found
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Save file, low level. Used for Plugin workarea.
$filename
- Full path name of file
$text
- Text to save
NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
Retrieves a TWiki predefined regular expression or character class.
$name
- Name of the expression to retrieve. See notes below
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to represent various string entities in an I18N-compatible manner. Plugins authors are encouraged to use these in matching where appropriate. The following are guaranteed to be present. Others may exist, but their use is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for use within character classes (i.e. for use within square brackets inside a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha'); my $alpha = TWiki::Func::getRegularExpression('mixedAlpha'); my $capitalized = qr/[$upper][$alpha]+/;Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex'); my $isWebName = ( $s =~ m/$webRE/ );
Name | Matches | Type |
---|---|---|
upperAlpha | Upper case characters | String |
upperAlphaNum | Upper case characters and digits | String |
lowerAlpha | Lower case characters | String |
lowerAlphaNum | Lower case characters and digits | String |
numeric | Digits | String |
mixedAlpha | Alphabetic characters | String |
mixedAlphaNum | Alphanumeric characters | String |
wikiWordRegex | WikiWords | RE |
webNameRegex | User web names | RE |
anchorRegex | #AnchorNames | RE |
abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
emailAddrRegex | email@address_NOSPAM_.com | RE |
tagNameRegex | Standard variable names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Parse a web and topic name, supplying defaults as appropriate.
$web
- Web name, identifying variable, or empty string
$topic
- Topic name, may be a web.topic string, required.
Since: TWiki::Plugins::VERSION 1.1
Input | Return |
---|---|
( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Topic' ) | ( 'Main', 'Topic' ) |
( '', '' ) | ( 'Main', 'WebHome' ) |
( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |
( '', 'Web.Topic' ) | ( 'Web', 'Topic' ) |
( 'Web1', 'Web2.Topic' ) | ( 'Web2', 'Topic' ) |
( 'Main', 'Topic' ) | ( 'Main', 'Topic' ) |
( 'TWiki', 'Topic' ) | ( 'TWiki', 'Topic' ) |
Main
and TWiki
are the web names set in $cfg{UsersWebName} and $cfg{SystemWebName} respectively.
Log Warning that may require admin intervention to data/warning.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Log debug message to data/debug.txt
$text
- Text to write; timestamp gets added
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Format the time in seconds into the desired time string
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
. Can be '$iso'
(e.g. '2002-12-31T19:30Z'
), '$rcs'
(e.g. '2001/12/31 23:59:59'
, '$http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz'
for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively
$timezone
- either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
$text
Formatted time string
Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Check for a valid WikiWord or WikiName
$text
- Word to test
Since: TWiki::Plugins::VERSION 1.100 (Dec 2005)
Extract all parameters from a variable string and returns a hash of parameters
$attr
- Attribute string
%params
Hash containing all parameters. The nameless parameter is stored in key _DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
%params
hash contains now: _DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
Extract a named or unnamed value from a variable parameter string - Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
$attr
- Attribute string
$name
- Name, optional
$value
Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
%TEST{ 'nameless' name1="val1" name2="val2" }%
{...}
to get: 'nameless' name1="val1" name2="val2"
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
From time-to-time, the TWiki developers will add new functions to the interface (either to TWikiFuncDotPm, or new handlers). Sometimes these improvements mean that old functions have to be deprecated to keep the code manageable. When this happens, the deprecated functions will be supported in the interface for at least one more TWiki release, and probably longer, though this cannot be guaranteed.
Updated plugins may still need to define deprecated handlers for compatibility with old TWiki versions. In this case, the plugin package that defines old handlers can suppress the warnings in %FAILEDPLUGINS%.
This is done by defining a map from the handler name to the TWiki::Plugins
version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler
for compatibility with TWiki::Plugins
versions before 1.1, we would add this to the plugin:
package TWiki::Plugins::SinkPlugin; use vars qw( %TWikiCompatibility ); $TWikiCompatibility{endRenderingHandler} = 1.1;If the currently-running TWiki version is 1.1 or later, then the handler will not be called and the warning will not be issued. TWiki with versions of
TWiki::Plugins
before 1.1 will still call the handler as required.
The following functions are retained for compatibility only. You should stop using them as soon as possible.
Get script URL path
DEPRECATED since 1.1 - use getScriptUrl
instead.
Return: $path
URL path of TWiki scripts, e.g. "/cgi-bin"
WARNING: you are strongly recommended not to use this function, as the {ScriptUrlPaths} URL rewriting rules will not apply to urls generated using it.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use getListOfWebs
instead.
Get list of all public webs, e.g. all webs that do not have the NOSEARCHALL
flag set in the WebPreferences
Return: @webs
List of all public webs, e.g. ( 'Main', 'Know', 'TWiki' )
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use formatTime
instead.
Format the time to GM time
$time
- Time in epoc seconds
$format
- Format type, optional. Default e.g. '31 Dec 2002 - 19:30'
, can be 'iso'
(e.g. '2002-12-31T19:30Z'
), 'rcs'
(e.g. '2001/12/31 23:59:59'
, 'http'
for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'
)
$text
Formatted time string
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulate topics instead
Get data directory (topic file root)
Return: $dir
Data directory, e.g. '/twiki/data'
This function violates store encapsulation and is therefore deprecated.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use the content handling functions to manipulateattachments instead
Get pub directory (file attachment root). Attachments are in $dir/Web/TopicName
Return: $dir
Pub directory, e.g. '/htdocs/twiki/pub'
This function violates store encapsulation and is therefore deprecated.
Use readAttachment
and saveAttachment
instead.
Since: TWiki::Plugins::VERSION 1.000 (07 Dec 2002)
DEPRECATED since 1.1 - use TWiki:Plugins.BuildContrib and define DEPENDENCIES that can be statically
evaluated at install time instead. It is a lot more efficient.
Since: TWiki::Plugins::VERSION 1.025 (01 Aug 2004)
Revision r19 - 2018-07-16 - 03:20:32 - TWikiContributor | Edit |