Difference: TWikiFuncDotPm (17 vs. 18)

Revision 182018-03-09 - ChrisManchen

Line: 1 to 1
 

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.01. This can be shown 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.

Notes on use of $TWiki::Plugins::VERSION 6.00 and later:

  • The version number is now aligned with the TWiki release version.
  • A TWiki-6.7.8 release will have a $TWiki::Plugins::VERSION = 6.78.
  • In an unlikely case where the patch number is 10 or larger, the patch number is added to the previous patch number. For example, TWiki-6.7.9 will have version 6.79, TWiki-6.7.10 will have 6.7910, and TWiki-6.7.11 will have 6.7911. This ensures that the version number can sort properly.
  • TWiki::Plugins::VERSION also applies to the plugin handlers. The handlers are documented in the EmptyPlugin, and that module indicates what version of TWiki::Plugins::VERSION it relates to.

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 SKIN and COVER preferences variables or the skin and cover CGI parameters

Return: $skin Comma-separated list of skins, e.g. 'gnu,tartan'. Empty string if none.

Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)

getUrlHost( ) -> $host

Get protocol, domain and optional port of script URL

Return: $host URL host, e.g. "http://example.com:80"

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

getScriptUrl( $web, $topic, $script, ... ) -> $url

Compose fully qualified URL

  • $web - Web name, e.g. 'Main'
  • $topic - Topic name, e.g. 'WebNotify'
  • $script - Script name, e.g. 'view'
  • ... - an arbitrary number of name=>value parameter pairs that will be url-encoded and added to the url. The special parameter name '#' is reserved for specifying an anchor. e.g. getScriptUrl('x','y','view','#'=>'XXX',a=>1,b=>2) will give .../view/x/y?a=1&b=2#XXX

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 ) -> $url

Compose fully qualified view URL

  • $web - Web name, e.g. 'Main'. The current web is taken if empty
  • $topic - Topic name, e.g. 'WebNotify'
Return: $url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

getPubUrlPath( ) -> $path

Get pub URL path

Return: $path URL path of pub directory, e.g. "/pub"

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 https if the LWP CPAN module is installed.

Note that the $url may have an optional user and password, as specified by the relevant RFC. Any proxy set in configure is honored.

Optional parameters may be supplied:

  • \@headers (an array ref): Additional HTTP headers of form 'name1', '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.
  • \%params (a hash ref): Additional options.

Below is the list of available %params. See CPAN:LWP::UserAgent for more details.

Name Usage
agent => $useragent ("User-Agent:" header)
cookie_jar => $cookies
credentials => [$netloc, $realm, $uname, $pass]
handlers => {$phase => \&cb, ...} Note: %matchspec is not available.
local_address => $address
max_redirect => $n
max_size => $bytes
method * => $method E.g. 'HEAD'
parse_head => $boolean
requests_redirectable => \@requests
ssl_opts => {$key => $value, ...}
timeout * => $secs
The parameters with * do not require 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 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:

code()
message()
header($field)
content()
is_error()
is_redirect()

Note that if LWP is not available, this function:

  1. can only really be trusted for HTTP/1.0 urls. If HTTP/1.1 or another protocol is required, you are strongly recommended to require LWP.
  2. Will not parse multipart content

In the event of the server returning an error, then is_error() will return true, code() will return a valid HTTP status code as specified in RFC 2616 and RFC 2518, and message() will return the message that was received from the server. In the event of a client-side error (e.g. an unparseable URL) then is_error() will return true and message() will return an explanatory message. code() will return 400 (BAD REQUEST).

Note: Callers can easily check the availability of other HTTP::Response methods as follows:

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 getExternalResource() except that it uses an HTTP POST method and that the additional $text parameter is required.

The $text is sent to the server as the body content of the HTTP request.

See getExternalResource() for more details.

Since: TWiki::Plugins::VERSION 6.00

getCgiQuery( ) -> $query

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)

getSessionKeys() -> @keys

Get a list of all the names of session variables. The list is unsorted.

Session keys are stored and retrieved using setSessionValue and getSessionValue.

Since: TWiki::Plugins::VERSION 1.2

getSessionValue( $key ) -> $value

Get a session value from the client session module

  • $key - Session key
Return: $value Value associated with key; empty string if not set

Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)

setSessionValue( $key, $value ) -> $boolean

Set a session value.

  • $key - Session key
  • $value - Value associated with key
Return: true if function succeeded

Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)

clearSessionValue( $key ) -> $boolean

Clear a session value that was set using setSessionValue.

  • $key - name of value stored in session to be cleared. Note that you cannot clear AUTHUSER.
Return: true if the session value was cleared

Since: TWiki::Plugins::VERSION 1.1

getContext() -> \%hash

Get a hash of context identifiers representing the currently active context.

The context is a set of identifiers that are set during specific phases of 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 'FirstPluginEnabled' will be set.

Since: TWiki::Plugins::VERSION 1.1

pushTopicContext($web, $topic)

  • $web - new web
  • $topic - new topic
Change the TWiki context so it behaves as if it was processing $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

popTopicContext()

Returns the TWiki context to the state it was in before the pushTopicContext was called.

Since: TWiki::Plugins::VERSION 1.2

Preferences

getPreferencesValue( $key, $web ) -> $value

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
Return: $value Preferences value; empty string if not set

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

  • Example for Plugin setting:
    • MyPlugin topic has: * Set COLOR = red
    • Use "MYPLUGIN_COLOR" for $key
    • my $color = TWiki::Func::getPreferencesValue( "MYPLUGIN_COLOR" );

  • Example for preferences setting:
    • WebPreferences topic has: * Set WEBBGCOLOR = #FFFFC0
    • my $webColor = TWiki::Func::getPreferencesValue( 'WEBBGCOLOR', 'Sandbox' );

NOTE: As of TWiki-4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

getPluginPreferencesValue( $key ) -> $value

Get a preferences value from your Plugin

  • $key - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return: $value Preferences value; empty string if not set

Note: This function will will only work when called from the Plugin.pm file itself. it will not work if called from a sub-package (e.g. TWiki::Plugins::MyPlugin::MyModule)

Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)

NOTE: As of TWiki-4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

getPreferencesFlag( $key, $web ) -> $value

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
Return: $value Preferences flag '1' (if set), or "0" (for preferences values "off", "no" and "0")

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

  • Example for Plugin setting:
    • MyPlugin topic has: * Set SHOWHELP = off
    • Use "MYPLUGIN_SHOWHELP" for $key
    • my $showHelp = TWiki::Func::getPreferencesFlag( "MYPLUGIN_SHOWHELP" );

NOTE: As of TWiki-4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

getPluginPreferencesFlag( $key ) -> $boolean

Get a preferences flag from your Plugin

  • $key - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return: false for preferences values "off", "no" and "0", or values not set at all. True otherwise.

Note: This function will will only work when called from the Plugin.pm file itself. it will not work if called from a sub-package (e.g. TWiki::Plugins::MyPlugin::MyModule)

Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)

NOTE: As of TWiki-4.1, if $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

setPreferencesValue($name, $val)

Set the preferences value so that future calls to getPreferencesValue will return this value, and %$name% will expand to the preference when used in future variable expansions.

The preference only persists for the rest of this request. Finalised preferences cannot be redefined using this function.

Returns 1 if the preference was defined, and 0 otherwise.

getWikiToolName( ) -> $name

Get toolname as defined in TWiki.cfg

Return: $name Name of tool, e.g. 'TWiki'

Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)

getMainWebname( ) -> $name

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)

getTwikiWebname( ) -> $name

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)

User Handling and Access Control

getDefaultUserName( ) -> $loginName

Get default user name as defined in the configuration as DefaultUserLogin

Return: $loginName Default user name, e.g. 'guest'

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

getCanonicalUserID( $user ) -> $cUID

  • $user can be a login, wikiname or web.wikiname
Return the cUID of the specified user. A cUID is a unique identifier which is assigned by 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. Other usermappings may use other conventions - the JoomlaUserMapping for example, has cUIDs like 'JoomlaeUserMapping_1234'.

If $user is undefined, it assumes the currently logged-in user.

Return: $cUID, an internal unique and portable escaped identifier for registered users. This may be autogenerated for an authenticated but unregistered user.

Since: TWiki::Plugins::VERSION 1.2

getWikiName( $user ) -> $wikiName

return the WikiName of the specified user if $user is undefined Get Wiki name of logged in user

  • $user can be a cUID, login, wikiname or web.wikiname

Return: $wikiName Wiki Name, e.g. 'JohnDoe'

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

getWikiUserName( $user ) -> $wikiName

return the userWeb.WikiName of the specified user if $user is undefined Get Wiki name of logged in user

  • $user can be a cUID, login, wikiname or web.wikiname

Return: $wikiName Wiki Name, e.g. "Main.JohnDoe"

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

wikiToUserName( $id ) -> $loginName

Translate a Wiki name to a login name.
  • $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)

userToWikiName( $loginName, $dontAddWeb ) -> $wikiName

Translate a login name to a Wiki name
  • $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"
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

  • $email - email address to look up
  • $dontAddWeb - Do not add web prefix if "1"
Find the wikinames of all users who have the given email address as their registered address. Since several users could register with the same email address, this returns a list of wikinames rather than a single wikiname.

Since: TWiki::Plugins::VERSION 1.2

wikinameToEmails( $user ) -> @emails

  • $user - wikiname of user to look up
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( ) -> $boolean

Test if logged in user is a guest (TWikiGuest)

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

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.

  • $user can be either a login name or a WikiName
  • a user mapping handler's isAdmin() may take $topic and $web arguments. That's why this function takes them too. For a user mapping handler whose isAdmin() doesn't care $topic and $web (e.g. TWikiUserMapping), $topic and $web are irrelevant, needless to say.

Since: TWiki::Plugins::VERSION 1.2

Note: The parameters $topic and $web were added in TWiki::Plugins::VERSION 6.00

isGroupMember( $group, $id ) -> $boolean

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

eachUser() -> $iterator

Get 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

  • $id - WikiName or login name of the user. If $id is undef, defaults to the currently logged-in user.
Get an iterator over the names of all groups that the user is a member of.

Since: TWiki::Plugins::VERSION 1.2

eachGroup() -> $iterator

Get 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 $group is the name of a group known to TWiki.

eachGroupMember($group) -> $iterator

Get 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 ) -> $boolean

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:
    1. You are setting different access controls in the text to those defined in the stored topic,
    2. You already have the topic text in hand, and want to help TWiki avoid having to read it again,
    3. You are providing a $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.
A perl true result indicates that access is permitted.

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:

  • Set ALLOWTOPICSPIN = IncyWincy
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

getListOfWebs( $filter ) -> @webs

  • $filter - spec of web types to recover
Gets a list of webs, filtered according to the spec in the $filter, which may include one of:
  1. 'user' (for only user webs)
  2. 'template' (for only template webs i.e. those starting with "_")
$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 ) -> $boolean

Test if web exists

  • $web - Web name, required, e.g. 'Sandbox'

Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)

isValidWebName( $name, $templateWeb ) -> $boolean

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.
Return: true if web name is 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

createWeb( $newWeb, $baseWeb, $opts )

  • $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
the web preferences topic in the new web.

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 Trash

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 $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')
    }

Since: TWiki::Plugins::VERSION 1.2

getTopicList( $web ) -> @topics

Get list of all topics in a web

  • $web - Web name, required, e.g. 'Sandbox'
Return: @topics Topic list, e.g. ( 'WebChanges',  'WebHome', 'WebIndex', 'WebNotify' )

Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)

topicExists( $web, $topic ) -> $boolean

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)

isValidTopicName( $name ) -> $boolean

Check for a valid topic name. Names considerd valid for autolinking are WikiWords (such as 'SanFrancisco') and acronym (such as 'SWMBO').

  • $name - topic name
Return: true if topic name is valid

Since: TWiki::Plugins::VERSION 1.4

checkTopicEditLock( $web, $topic, $script ) -> ( $oopsUrl, $loginName, $unlockTime )

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"
Return: ( $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)

setTopicEditLock( $web, $topic, $lock )

  • $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)

saveTopic( $web, $topic, $meta, $text, $options ) -> $error

  • $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
Return: error message or undef.

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.

saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrl

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
Return: $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

moveTopic( $web, $topic, $newWeb, $newTopic )

  • $web source web - required
  • $topic source topic - required
  • $newWeb dest web
  • $newTopic dest topic
Renames the topic. Throws an exception if something went wrong. If $newWeb is undef, it defaults to $web. If $newTopic is undef, it defaults to $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" );
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 1999-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback
Note: Please contribute updates to this topic on TWiki.org at TWiki:TWiki.TWikiFuncDotPm.