PerlDoc

26 August 2025 - 17:41 | Version 1 |
See PublishedAPI for packages intended to be used by Plugin and Contrib authors, or browse all packages.
See also Developing plugins, Developer's Bible, Technical Overview


Parent package: Foswiki
Child packages:

    public package Foswiki::Func

    Interface for Foswiki extensions developers

    This module defines the main interfaces that extensions can use to interact with the Foswiki engine and content.

    Refer to lib/Foswiki/Plugins/EmptyPlugin.pm for a template Plugin and starter documentation on how to write a Plugin.

    Plugins should only call methods in packages documented in DevelopingPlugins. If you use functions in other Foswiki libraries you risk creating a security hole, and you will probably need to change your plugin when you upgrade Foswiki.

    Since: date indicates where functions or parameters have been added since the baseline of the API (Foswiki 1.0.0). The date indicates the earliest date of a Foswiki release that will support that function or parameter. See Foswiki:Download.ReleaseDates for version release dates.

    Deprecated date indicates where a function or parameters has been deprecated. Deprecated functions will still work, though they should not be called in new plugins and should be replaced in older plugins as soon as possible. Deprecated parameters are simply ignored in Foswiki releases after date.

    Until date indicates where a function or parameter has been removed. The date indicates the latest date at which Foswiki releases still supported the function or parameter.

    Note that the Foswiki::Func API should always be the first place extension authors look for methods. Certain other lower-level APIs are also exposed by the core, but those APIs should only be called if there is no alternative available through Foswiki::Func. The APIs in question are documented in DevelopingPlugins.

    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.

    getUrlHost( ) → $host

    Get protocol, domain and optional port of script URL

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

    getScriptUrl( $web, $topic, $script, … ) → $url

    Compose fully qualified URL

    Return: $url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"

    Examples:
    my $url;
    # $url eq 'http://wiki.example.org/url/to/bin'
    $url = Foswiki::Func::getScriptUrl();
    # $url eq 'http://wiki.example.org/url/to/bin/edit'
    $url = Foswiki::Func::getScriptUrl(undef, undef, 'edit');
    # $url eq 'http://wiki.example.org/url/to/bin/edit/Web/Topic'
    $url = Foswiki::Func::getScriptUrl('Web', 'Topic', 'edit');

    getScriptUrlPath( $web, $topic, $script, … ) → $path

    Compose absolute URL path. See Foswiki::Func::getScriptUrl

    Examples:
    my $path;
    # $path eq '/path/to/bin'
    $path = Foswiki::Func::getScriptUrlPath();
    # $path eq '/path/to/bin/edit'
    $path = Foswiki::Func::getScriptUrlPath(undef, undef, 'edit');
    # $path eq '/path/to/bin/edit/Web/Topic'
    $path = Foswiki::Func::getScriptUrlPath('Web', 'Topic', 'edit');

    Since: 19 Jan 2012 (when called without parameters, this function is backwards-compatible with the old version which was deprecated 28 Nov 2008).

    getViewUrl( $web, $topic ) → $url

    Compose fully qualified view URL Return: $url URL, e.g. "http://example.com:80/cgi-bin/view.pl/Main/WebNotify"

    getPubUrlPath( $web, $topic, $attachment, %options ) → $url

    Get pub URL path/attachment URL

    Return: with no parameters, returns the URL path of the root of all attachments.

    Prior to Foswiki 2, URLs to attachments had to be constructed by the caller. For example, %PUBURL%/Main/JohnSmith/picture.gif This method of constructing URLs causes many problems, and is strongly discouraged.

    Since Foswiki 2 this function accepts parameters as follows: %options may include:

    If $web is not given, $topic and $attachment are ignored. If $topic is not given, $attachment is ignored.

    If topic_version is not given, the most recent revision of the topic will be linked. Similarly if attachment_version= is not given, the most recent revision of the attachment will be assumed. If topic_version is specified but attachment_version is not (or the specified attachment_version is not present), then the most recent version of the attachment in that topic version will be linked. Not all stores support retrieving old attachment versions this way.

    If absolute is not specified (or is 0), this function will generate relative URLs. However if Foswiki is running in an absolute URL context (the skin requires absolute URLs, such as print or rss, or Foswiki is running from the command-line) then absolute will be ignored and absolute URLs will always be generated.

    getExternalResource( $url ) → $response

    Get whatever is at the other end of a URL (using an HTTP GET request). Will only work for encrypted protocols such as https if the LWP CPAN module is installed.

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

    The $response is an object that is known to implement the following subset of the methods of LWP::Response. It may in fact be an LWP::Response object, but it may also not be if LWP is not available, so callers may only assume the following subset of methods is available:
    code()
    message()
    header($field)
    content()
    is_error()
    is_redirect()

    Note that if LWP is not available, this function:
    1. can only really be trusted for HTTP/1.0 urls. If HTTP/1.1 or another protocol is required, you are strongly recommended to require LWP.
    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 = Foswiki::Func::getExternalResource($url);
    if (!$response->is_error() && $response->isa('HTTP::Response')) {
        ... other methods of HTTP::Response may be called
    } else {
        ... only the methods listed above may be called
    }
    

    getRequestObject( ) → $query

    Get the request object. This is a subclass of Foswiki::Request. The request object can be used to get the parameters passed to the request, either via CGI or on the command line (depending on how the script was called).

    A Foswiki::Request object is largely compatible with a CPAN:CGI object. Most of the time, documentation for that class applies directly to Foswiki::Request objects as well.

    Note that this method replaces getCgiQuery (which is a synonym for this method). Code that is expected to run with pre-1.1 versions of Foswiki can continue to call getCgiQuery for as long as necessary.

    Caution: Direct use of the CGI parameters can introduce security vulnerabilities. Any parameters from the URL should be carefully validated, and encoded for safety before displaying the data back to the user.

    Example:
       my $query    = Foswiki::Func::getRequestObject();
       my $single   = $query->param('parm1');        # Get a scalar value (Returns 1st value if multiple valued)
       my @multi    = $query->multi_param('parm2');  # Get multi-valued parameter
    

    Since: 31 Mar 2009

    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.

    getSessionValue( $key ) → $value

    Get a session value from the client session module Return: $value Value associated with key; empty string if not set

    setSessionValue( $key, $value ) → $boolean

    Set a session value. Return: true if function succeeded

    clearSessionValue( $key ) → $boolean

    Clear a session value that was set using setSessionValue. Return: true if the session value was cleared

    getContext() → \%hash

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

    The context is a set of identifiers that are set during specific phases of processing. For example, each of the standard scripts in the 'bin' directory each has a context identifier - the view script has 'view', the edit script has 'edit' etc. So you can easily tell what 'type' of script your Plugin is being called within.

    A comprehensive list of core context identifiers used by Foswiki is found in IfStatements 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 {
       Foswiki::Func::getContext()->{'MyID'} = 1;
       ...
    
    This can be used in SecondPlugin.pm like this:
    sub initPlugin {
       if( Foswiki::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.

    pushTopicContext($web, $topic)

    Change the Foswiki context, adding the requested $web.$topic onto the preferences stack. Any preferences found in $web.$topic will be used in place of preferences previously set in the stack, provided that they were not finalized in a lower level. Preferences set in the prior web.topic are not cleared. $web.$topic replaces and adds to preferences but does not remove preferences that it does not set.

    Note that if the new topic is not readable by the logged in user due to access control considerations, there will not be an exception. It is the duty of the caller to check access permissions before changing the topic. All other errors will throw an exception.

    It is the duty of the caller to restore the original context by calling popTopicContext.

    Note that this call does not re-initialise plugins, so if you have used global variables to remember the web and topic in initPlugin, then those values will be unchanged.

    popTopicContext()

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

    Registering extensions

    Plugins work either by using handlers to manipulate the text being processed, or by registering extensions, such as new macros, scripts, or meta-data types.

    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 internal macros, and are expanded at the same time. This is a lot more efficient than using the commonTagsHandler.
    1. 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"}%

    The variable handler function must be of the form:
    sub handler(\%session, \%params, $topic, $web, $topicObject)
    
    where: for example, to execute an arbitrary command on the server, you might do this:
    sub initPlugin{
       Foswiki::Func::registerTagHandler('EXEC', \&boo);
    }
    
    sub boo {
        my( $session, $params, $topic, $web, $topicObject ) = @_;
        my $cmd = $params->{_DEFAULT};
    
        return "NO COMMAND SPECIFIED" unless $cmd;
    
        my $result = `$cmd 2>&1`;
        return $params->{silent} ? '' : $result;
    }
    
    would let you do this: %EXEC{"ps -Af" silent="on"}%

    Registered tags differ from tags implemented using the old approach (text substitution in commonTagsHandler) in the following ways:

    registerRESTHandler( $alias, \&fn, %options )

    Should only be called from initPlugin.

    Adds a function to the dispatch table of the REST interface 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.

    Additional options are set in the %options hash. These options are important to ensuring that requests to your handler can't be used in cross-scripting attacks, or used for phishing.

    See http://foswiki.org/Support/GuidelinesForSecureExtensions for more information.

    Example

    The EmptyPlugin has the following call in the initPlugin handler:
       Foswiki::Func::registerRESTHandler('example', \&restExample,
         authenticate  => 1,      # Set to 0 if handler should be useable by WikiGuest
         validate      => 1,      # Set to 0 to disable StrikeOne CSRF protection
         http_allow    => 'POST', # Set to 'GET,POST' to allow use HTTP GET and POST
         description   => 'Example handler for Empty Plugin'
         );
    

    This adds the restExample function to the REST dispatch table for the EmptyPlugin under the 'example' alias, and allows it to be invoked using the URL

    http://server:port/bin/rest/EmptyPlugin/example

    note that the URL

    http://server:port/bin/rest/EmptyPlugin/restExample

    (ie, with the name of the function instead of the alias) will not work.

    Calling REST handlers from the command-line

    The rest script allows handlers to be invoked from the command line. The script is invoked passing the parameters as described in CommandAndCGIScripts. If the handler requires authentication ( authenticate=>1 ) then this can be passed in the username and password parameters.

    For example,

    perl -wT rest /EmptyPlugin/example -username HughPugh -password trumpton

    registerMETA($macro, $spec)

    Deprecated: please use Foswiki::Meta::registerMETA instead.

    Preferences

    getPreferencesValue( $key, $web ) → $value

    Get a preferences value for the currently requested context, from the currently request topic, its web and the site.

    Return: $value Preferences value; undefined if not set

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

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

    NOTE: If $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

    getPreferencesFlag( $key, $web ) → $value

    Get a preferences flag from Foswiki or from a Plugin Return: $value Preferences flag '1' (if set), or "0" (for preferences values "off", "no" and "0")

    NOTE: 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 Return: false for preferences values "off", "no" and "0", or values not set at all. True otherwise.

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

    NOTE: If $NO_PREFS_IN_TOPIC is enabled in the plugin, then preferences set in the plugin topic will be ignored.

    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.

    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'

    getCanonicalUserID( $user ) → $cUID

    Return the cUID of the specified user. A cUID is a unique identifier which is assigned by Foswiki for each user. BEWARE: While the default TopicUserMapping uses a cUID that looks like a user's LoginName, some characters may be 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.

    getWikiName( $user ) → $wikiName

    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'

    getWikiUserName( $user ) → $wikiName

    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"

    wikiToUserName( $id ) → $loginName

    Translate a Wiki name to a login name.

    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.

    userToWikiName( $loginName, $dontAddWeb ) → $wikiName

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

    emailToWikiNames( $email, $dontAddWeb ) → @wikiNames

    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.

    wikinameToEmails( $user ) → @emails

    Returns the registered email addresses of the named user. If $user is undef, returns the registered email addresses for the logged-in user.

    $user may also be a group.

    isGuest( ) → $boolean

    Test if logged in user is a guest (WikiGuest)

    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.

    isGroupMember( $group, $id, $options ) → $boolean

    Find out if $id is in the named group. The expand option controls whether or not nested groups are searched.

    e.g. Is jordi in the HesperionXXGroup, and not in a nested group. e.g.
    if( Foswiki::Func::isGroupMember( "HesperionXXGroup", "jordi", { expand => 0 } )) {
        ...
    }
    
    If $user is undef, it defaults to the currently logged-in user.

    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 $it = Foswiki::Func::eachUser();
        while ($it->hasNext()) {
            my $user = $it->next();
            # $user is a wikiname
        }
    

    WARNING on large sites, this could be a long list!

    eachMembership($id) → $iterator

    Get an iterator over the names of all groups that the user is a member of.

    eachGroup() → $iterator

    Get an iterator over all groups.

    Use it as follows:
        my $iterator = Foswiki::Func::eachGroup();
        while ($it->hasNext()) {
            my $group = $it->next();
            # $group is a group name e.g. AdminGroup
        }
    

    WARNING on large sites, this could be a long list!

    isGroup( $group ) → $boolean

    Checks if $group is the name of a user group.

    eachGroupMember($group) → $iterator

    Get an iterator over all the members of the named group. Returns undef if $group is not a valid group. Nested groups are expanded unless the expand option is set to false.

    Use it as follows: Process all users in RadioHeadGroup without expanding nested groups
        my $iterator = Foswiki::Func::eachGroupMember('RadioheadGroup', {expand => 'false');
        while ($it->hasNext()) {
            my $user = $it->next();
            # $user is a wiki name e.g. 'TomYorke', 'PhilSelway'
            #   With expand set to false, group names can also be returned.
            #   Users are not checked to exist.
        }
    

    WARNING on large sites, this could be a long list!

    addUserToGroup( $id, $group, $create ) → $boolean

    removeUserFromGroup( $id, $group ) → $boolean

    checkAccessPermission( $type, $id, $text, $topic, $web, $meta ) → $boolean

    Check access permission for a topic based on the AccessControl rules A perl true result indicates that access is permitted.

    Note the weird parameter order is due to compatibility constraints with earlier releases.

    TIP Tip: if you want, you can use this method to check your own access control types. For example, if you: in ThatWeb.ThisTopic, then a call to checkAccessPermission('SPIN', 'IncyWincy', undef, 'ThisTopic', 'ThatWeb', undef) will return true.

    Example code:

        use Error qw(:try);
        use Foswiki::AccessControlException;
        ...
        unless (
            Foswiki::Func::checkAccessPermission(
                "VIEW", $session->{user}, undef, $topic, $web
            )
          )
        {
            throw Foswiki::AccessControlException( "VIEW", $session->{user}, $web,
                $topic,  $Foswiki::Meta::reason );
        }
    

    Traversing

    getListOfWebs( $filter [, $web] ) → @webs

    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 = Foswiki::Func::getListOfWebs( "user,public" );
    

    isValidWebName( $name [, $system] ) → $boolean

    Check for a valid web name. If $system is true, then system web names are considered valid (names starting with _) otherwise only user web names are valid

    If $Foswiki::cfg{EnableHierarchicalWebs} is off, it will also return false when a nested web name is passed to it.

    webExists( $web ) → $boolean

    Test if web exists

    getTopicList( $web ) → @topics

    Get list of all topics in a web Return: @topics Topic list, e.g. ( 'WebChanges',  'WebHome', 'WebIndex', 'WebNotify' )

    isValidTopicName( $name [, $allowNonWW] ) → $boolean

    Check for a valid topic name.

    topicExists( $web, $topic ) → $boolean

    Test if topic exists

    $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.

    readTopic( $web, $topic, $rev ) → ( $meta, $text )

    Read topic text and meta data, regardless of access permissions. Return: ( $meta, $text ) Meta data object and topic text

    $meta is a perl 'object' of class Foswiki::Meta. This class is fully documented in the source code documentation shipped with the release, or can be inspected in the lib/Foswiki/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.

    getRevisionInfo($web, $topic, $rev, $attachment ) → ( $date, $user, $rev, $comment )

    Get revision info of a topic or attachment Return: ( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number, comment of attachment if attachment ), e.g. ( 1234561, 'phoeny', "5",  )
    $date in epochSec
    $user Wiki name of the author (not login name)
    $rev actual rev number
    $comment comment given for uploaded attachment

    NOTE: if you are trying to get revision info for a topic, use $meta→getRevisionInfo instead if you can - it is significantly more efficient.

    getRevisionAtTime( $web, $topic, $time ) → $rev

    Get the revision number of a topic at a specific time. Return: Single-digit revision number, or undef if it couldn't be determined (either because the topic isn't that old, or there was a problem)

    getAttachmentList( $web, $topic ) → @list

    Get a list of the attachments on the given topic.

    Since: 31 Mar 2009

    attachmentExists( $web, $topic, $attachment ) → $boolean

    Test if attachment exists $web and $topic are parsed as described in the documentation for normalizeWebTopicName.

    The attachment must exist in the store (it is not sufficient for it to be referenced in the object only)

    readAttachment( $web, $topic, $name, $rev ) → $data

    Read an attachment from the store for a topic, and return it as a string. The names of attachments on a topic can be recovered from the meta-data returned by 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 Foswiki::AccessControlException. Permissions are checked for the current user.

    use Error qw(:try);
    use Foswiki::AccessControlException ();
    
    my( $meta, $text ) = Foswiki::Func::readTopic( $web, $topic );
    my @attachments = $meta->find( 'FILEATTACHMENT' );
    foreach my $a ( @attachments ) {
       try {
           my $data = Foswiki::Func::readAttachment( $web, $topic, $a->{name} );
           ...
       } catch Foswiki::AccessControlException with {
       };
    }
    

    This is the way 99% of extensions will access attachments. See Foswiki::Meta::openAttachment for a lower level interface that does not check access controls.

    Manipulating

    createWeb( $newWeb, $baseWeb, $opts )

    the web preferences topic in the new web.

    use Error qw( :try );
    use Foswiki::AccessControlException ();
    
    try {
        Foswiki::Func::createWeb( "Newweb" );
    } catch Foswiki::AccessControlException with {
        my $e = shift;
        # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
        my $e = shift;
        # see documentation on Error
    } otherwise {
        ...
    };
    

    moveWeb( $oldName, $newName )

    Move (rename) a web.

    use Error qw( :try );
    use Foswiki::AccessControlException ();
    
    try {
        Foswiki::Func::moveWeb( "Oldweb", "Newweb" );
    } catch Foswiki::AccessControlException with {
        my $e = shift;
        # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
        my $e = shift;
        # see documentation on Error::Simple
    } otherwise {
        ...
    };
    

    To delete a web, move it to a subweb of Trash
    Foswiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" );
    

    checkTopicEditLock( $web, $topic, $script ) → ( $oopsUrl, $loginName, $unlockTime )

    Check if a lease has been taken by some other user. Return: ( $oopsUrl, $loginName, $unlockTime ) - The $oopsUrl for calling redirectCgiQuery(), user's $loginName, and estimated $unlockTime in minutes, or ( '', '', 0 ) if no lease exists.

    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 edit script always takes out a lease.

    It is impossible to fully lock a topic. Concurrent changes will be merged.

    saveTopic( $web, $topic, $meta, $text, $options )

    For example,
    use Error qw( :try );
    use Foswiki::AccessControlException ();
    
    my( $meta, $text );
    if (Foswiki::Func::topicExists($web, $topic)) {
        ( $meta, $text ) = Foswiki::Func::readTopic( $web, $topic );
    } else {
        #if the topic doesn't exist, we can either leave $meta undefined
        #or if we need to set more than just the topic text, we create a new Meta object and use it.
        $meta = new Foswiki::Meta($Foswiki::Plugins::SESSION, $web, $topic );
        $text = '';
    }
    $text =~ s/APPLE/ORANGE/g;
    try {
        Foswiki::Func::saveTopic( $web, $topic, $meta, $text );
    } catch Foswiki::AccessControlException with {
        my $e = shift;
        # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
        my $e = shift;
        # see documentation on Error::Simple
    } otherwise {
        ...
    };
    

    In the event of an error an exception will be thrown. Callers can elect to trap the exceptions thrown, or allow them to propagate to the calling environment. May throw Foswiki::OopsException or Error::Simple.

    Note: The ignorepermissions option is only available in Foswiki 1.1 and later.

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

    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 $Foswiki::cfg{TrashWebName} to delete it.

    use Error qw( :try );
    
    try {
        moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" );
    } catch Foswiki::AccessControlException with {
        my $e = shift;
        # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
        my $e = shift;
        # see documentation on Error::Simple
    } otherwise {
        ...
    };
    

    saveAttachment( $web, $topic, $attachment, \%opts )

    Create an attachment on the given topic. \%opts may include:
    dontlog mark this change so it is not picked up in statistics
    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
    createlink Set true to create a link at the end of the topic
    notopicchange Set to true to prevent this upload being recorded in the meta-data of the topic.
    Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown. The current user must have CHANGE access on the topic being attached to.

        try {
            Foswiki::Func::saveAttachment( $web, $topic, 'image.gif',
                                         { file => 'image.gif',
                                           comment => 'Picture of Health',
                                           hide => 1 } );
       } catch Foswiki::AccessControlException with {
          # Topic CHANGE access denied
       } catch Foswiki::OopsException with {
            shift->throw();    # propagate
       } catch Error with {
          # see documentation on Error
       } otherwise {
          ...
       };
    
    This is the way 99% of extensions will create new attachments. See Foswiki::Meta::openAttachment for a much lower-level interface.

    moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )

    Renames the attachment. Throws an exception on error or access violation. If $newWeb is undef, it defaults to $web. If $newTopic is undef, it defaults to $topic. If $newAttachment is undef, it defaults to $attachment. If all of $newWeb, $newTopic and $newAttachment are undef, it is an error.

    The destination topic must already exist, but the destination attachment must not exist.

    Rename an attachment to $Foswiki::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 Foswiki::AccessControlException with {
       my $e = shift;
       # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
       my $e = shift;
       # see documentation on Error
    };
    

    copyAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )

    Copies the attachment. Throws an exception on error or access violation. If $newWeb is undef, it defaults to $web. If $newTopic is undef, it defaults to $topic. If $newAttachment is undef, it defaults to $attachment. If all of $newWeb, $newTopic and $newAttachment are undef, it is an error.

    The destination topic must already exist, but the destination attachment must not exist.

    use Error qw( :try );
    
    try {
       # copy attachment between topics
       copyAttachment( "Countries", "Germany", "AlsaceLorraine.dat",
                         "Countries", "France" );
       # Note destination attachment name is defaulted to the same as source
    } catch Foswiki::AccessControlException with {
       my $e = shift;
       # see documentation on Foswiki::AccessControlException
    } catch Foswiki::OopsException with {
            shift->throw();    # propagate
    } catch Error with {
       my $e = shift;
       # see documentation on Error
    };
    

    Since: 19 Jul 2010

    Finding changes

    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 = Foswiki::Func::eachChangeSince(
            $web, time() - 7 * 24 * 60 * 60); # the last 7 days
        while ($iterator->hasNext()) {
            my $change = $iterator->next();
            ...
        }
    
    $change is a reference to a hash containing the following fields:

    The following additional fields are deprecated and will be removed in Foswiki 2.0: These additional fields

    If you are writing an extension that requires compatibility with Foswiki < 2 only the more, revision, time, topic and user can be assumed.

    summariseChanges($web, $topic, $orev, $nrev, $tml, $nochecks) → $text

    Generate a summary of the changes between rev $orev and rev $nrev of the given topic. Generate a (max 3 line) summary of the differences between the revs.

    If there is only one rev, a topic summary will be returned.

    If $tml is not set, all HTML will be removed.

    In non-tml, lines are truncated to 70 characters. Differences are shown using + and - to indicate added and removed text.

    If access is denied to either revision, then it will be treated as blank text.

    Since 2009-03-06

    Templates

    readTemplate( $name, $skin ) → $text

    Read a template or skin. Embedded template directives get expanded Return: $text Template text

    loadTemplate ( $name, $skin, $web ) → $text

    Return: expanded template text (what's left after removal of all %TMPL:DEF% statements)

    Reads a template and extracts template definitions, adding them to the list of loaded templates, overwriting any previous definition.

    How Foswiki searches for templates is described in SkinTemplates.

    If template text is found, extracts include statements and fully expands them.

    expandTemplate( $def ) → $string

    Do a %TMPL:P{$def}%, only expanding the template (not expanding any variables other than %TMPL%.) Return: the text of the expanded template

    A template is defined using a %TMPL:DEF% statement in a template file. See the documentation on Foswiki templates for more information.

    eg: #load the templates (relying on the system-wide skin path.) Foswiki::Func::loadTemplate('linkedin'); #get the 'profile' DEF section my $tml = Foswiki::Func::expandTemplate('profile'); #get the 'profile' DEF section expanding the inline Template macros (such as %USER% and %TYPE%) #NOTE: when using it this way, it is important to use the double quotes "" to delineate the values of the parameters. my $tml = Foswiki::Func::expandTemplate( '"profile" USER="' . $user . '" TYPE="' . $type . '"' );

    Rendering

    expandCommonVariables( $text, $topic, $web, $meta ) → $text

    Expand all common %VARIABLES% Return: $text Expanded text, e.g. 'Current user is WikiGuest'

    See also: expandVariablesOnTopicCreation

    Caution: This function needs all the installed plugins to have gone through initialization. Never call this function from within an initPlugin handler, bad things happen.

    Caution: This function ultimately calls the following handlers:

    ALERT! It is possible to create an infinite loop if expandCommonVariables is called in any of these handlers. It can be used, but care should be taken to ensure that the text being expanded does not cause this function to be called recursively.

    expandVariablesOnTopicCreation ( $text ) → $text

    Expand the limited set of variables that are always expanded during topic creation Return: text with variables expanded

    Expands only the variables expected in templates that must be statically expanded in new content.

    The expanded variables are:

    See also: expandVariables

    renderText( $text, $web, $topic ) → $text

    Render text from TML into XHTML as defined in TextFormattingRules Return: $text XHTML text, e.g. '<b>bold</b> and <code>fixed font</code>'

    NOTE: renderText expects that all %MACROS% have already been expanded - it does not expand them for you (call expandCommonVariables above).

    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() Return: $text XHTML anchor, e.g. '<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'

    addToZone( $zone, $id, $data, $requires )

    Direct interface to %ADDTOZONE (see VarADDTOZONE)

    All macros present in $data will be expanded before being inserted into the <head> section.

    ALERT! Note: Read the developer supplement at Foswiki:Development.AddToZoneFromPluginHandlers if you are calling addToZone() from a rendering or macro/tag-related plugin handler

    Examples:
    Foswiki::Func::addToZone( 'head', 'PATTERN_STYLE',
       '<link rel="stylesheet" type="text/css" href="%PUBURL%/Foswiki/PatternSkin/layout.css" media="all" />');
    
    Foswiki::Func::addToZone( 'script', 'MY_JQUERY',
       '<script type="text/javascript" src="%PUBURL%/Myweb/MyJQuery/myjquery.js"></scipt>',
       'JQUERYPLUGIN::FOSWIKI');
    

    Controlling page output

    writeHeader()

    Prints a basic content-type HTML header for text/html to standard out.

    redirectCgiQuery( $query, $url, $passthru, $status )

    Redirect to URL

    Return: none

    Issue a Location HTTP header that will cause a 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 installation. If $passthru is set to a true value, then Foswiki 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 = Foswiki::Func::getRequestObject();
    $query->param(-name => 'text', -value => 'Different text');
    Foswiki::Func::redirectCgiQuery(
      undef, Foswiki::Func::getScriptUrl($web, $topic, 'edit'), 1);
    
    $passthru does nothing if $url does not point to a script in the current Foswiki installation.

    Plugin-specific file handling

    getWorkArea( $pluginName ) → $directorypath

    Gets a private directory for Plugin use. The Plugin is entirely responsible for managing this directory; Foswiki 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 its contents are permanent, so Plugins must be careful to keep their areas tidy.

    For temporary file storage that only exists for the life of the transaction, use the Perl File::Temp or related File::Spec functions.

    readFile( $filename, $unicode ) → $text

    Read file, low level. Used for Plugin workarea. Return: $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.

    Foswiki 2.0 APIs generally all use UNICODE strings, and all data is properly decoded from/to utf-8 at the edge. This API is an exception! Because this API can be used to retrieve data of any type including binary data, it is not decoded to unicode by default. By default, data is read as raw bytes, without any encoding layer.

    If you are using this API to read topic originated data, topic names, etc. then you should set the $unicode flag so that the data returned is a valid perl character string.

    saveFile( $filename, $text, $unicode )

    Save file, low level. Used for Plugin workarea.

    Return: none

    NOTE: Use this function only for the Plugin workarea, not for topics and attachments. Use the appropriate functions to manipulate topics and attachments.

    Foswiki 2.0 APIs generally all use UNICODE strings, and all data is properly decoded from/to utf-8 at the edge. This API is an exception! Because this API can be used to save data of any type including binary data, it is not decoded to unicode by default. By default, data is written as raw bytes, without any encoding layer.

    If you are using this API to write topic data, topic names, etc. then you should set the $unicode flag so that the data returned as a valid perl character string.

    Failure to set the $unicode flag when required will result in perl "Wide character in print" errors.

    General Utilities

    normalizeWebTopicName($web, $topic) → ($web, $topic)

    Parse a web and topic name, supplying defaults as appropriate. Return: the parsed Web/Topic pair

    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' )
    ( 'Web1', 'Web2.' ) ( 'Web2', 'WebHome' )

    Note that sub web names (SubWeb) are only available if hierarchical webs are enabled in configure.

    The symbols %HOMEWEB%, %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
    ( '%HOMEWEB%', 'Topic' ) ( 'Main', 'Topic' )
    ( '%USERSWEB%', 'Topic' ) ( 'Main', 'Topic' )
    ( '%SYSTEMWEB%', 'Topic' ) ( 'System', 'Topic' )
    ( '', '%DOCWEB%.Topic' ) ( 'System', 'Topic' )

    query($searchString, $topics, \%options ) → iterator (resultset)

    Query the topic data in the specified webs. A programatic interface to SEARCH results.

    The \%options hash may contain the following options:

    To iterate over the returned topics use:
        my $matches = Foswiki::Func::query( "Slimy Toad", undef,
                { web => 'Main,San*', casesensitive => 0, files_without_match => 0 } );
        while ($matches->hasNext) {
            my $webtopic = $matches->next;
            my ($web, $topic) = Foswiki::Func::normalizeWebTopicName('', $webtopic);
          ...etc
    

    decodeFormatTokens($str) → $unencodedString

    Foswiki 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 Foswiki uses escapes in the format string. For example:

    %MYTAG{format="$percentWURBLE$percent"}%

    This lets you enter arbitrary strings into parameters without worrying that Foswiki 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.

    The set of tokens that is expanded is described in FormatTokens.

    sanitizeAttachmentName($fname) → ($fileName, $origName)

    Given a file path, 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.

    Avoid using this if you can; rewriting attachment names uses some very nasty heuristics that cannot be changed because of compatibility issues. It is much better use point-of-source validation to ensure only valid attachment names are uploaded.

    spaceOutWikiWord( $word, $sep ) → $text

    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.

    isTrue( $value, $default ) → $boolean

    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.

    isValidWikiWord ( $text ) → $boolean

    Check for a valid WikiWord or WikiName

    extractParameters($attr ) → %params

    Extract all parameters from a variable string and returns a hash of parameters Return: %params Hash containing all parameters. The nameless parameter is stored in key _DEFAULT

    extractNameValuePair( $attr, $name ) → $value

    Extract a named or unnamed value from a variable parameter string - Note: | Function Foswiki::Func::extractParameters is more efficient for extracting several parameters Return: $value Extracted value

    sendEmail ( $text, $retries ) → $error

    Send an e-mail specified as MIME format content. To specify MIME format mails, you create a string that contains a set of header lines that contain field definitions and a message body such as:
    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. Peasant
    
    Leave a blank line between the last header field and the message body.

    Logging

    writeEvent( $action, $extra )

    Log an event. You can enumerate the contents of the log using the eachEventSince function.

    NOTE: Older plugins may use $Foswiki::cfg{LogFileName}. These plugins must be modified to use writeEvent and eachEventSince instead.

    To maintain compatibility with older Foswiki releases, you can write conditional code as follows:
    if (defined &Foswiki::Func::writeEvent) {
       # use writeEvent and eachEventSince
    } else {
       # old code using {LogFileName}
    }
    

    Note that the ability to read/write $Foswiki::cfg{LogFileName} is maintained for compatibility but is deprecated (should not be used in new code intended to work only with Foswiki 1.1 and later) and will not work with any installation that stores logs in a database.

    writeWarning( $text )

    Log a warning that may require admin intervention to the warnings log (data/warn*.txt)

    writeDebug( $text )

    Log debug message to the debug log

    eachEventSince($time, $level) → $iterator

    Get an iterator over the list of all the events at the given level between $time and now. Events are written to the event log using writeEvent. The Foswiki core will write other events that will also be returned.

    If the chosen Logger does not support querying the logs, an empty iterator will be returned. The supplied PlainFile and Compatibility loggers will return events only if the log files have not been archived.

    Events are returned in oldest-first order.

    Each event is returned as a reference to an array. The elements are:
    1. date of the event (seconds since the epoch)
    2. login name of the user who triggered the event
    3. the event name (the $action passed to writeEvent)
    4. the Web.Topic that the event applied to
    5. Extras (the $extra passed to writeEvent)
    6. The IP address that was the source of the event (if known)

    Use the iterator like this:
    my $it = Foswiki::Func::eachEventSince(Foswiki::Time::parseTime("1 Apr 2010"));
    while ($it->hasNext()) {
       my $entry = $it->next();
       my $date = $entry->[0];
       my $loginName = $entry->[1];
       ...
    }
    

    Deprecated functions

    From time-to-time, the Foswiki developers will add new functions to the interface (either to Foswiki::Func, 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 release, and probably longer, though this cannot be guaranteed.

    Updated plugins may still need to define deprecated handlers for compatibility with old Foswiki 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 Foswiki::Plugins version in which the handler was first deprecated. For example, if we need to define the endRenderingHandler for compatibility with Foswiki::Plugins versions before 1.1, we would add this to the plugin:
    package Foswiki::Plugins::SinkPlugin;
    use vars qw( %FoswikiCompatibility );
    $FoswikiCompatibility{endRenderingHandler} = 1.1;
    
    If the currently-running code version is 1.1 or later, then the handler will not be called and the warning will not be issued. Wersions of Foswiki::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.

    getRegularExpression( $name ) → $expr

    Deprecated 28 Nov 2008 - use $Foswiki::regex{...} instead, it is directly equivalent.

    See DevelopingPlugins for more information

    getWikiToolName( ) → $name

    Deprecated 28 Nov 2008 in Foswiki; use $Foswiki::cfg{WikiToolName} instead

    getMainWebname( ) → $name

    Deprecated 28 Nov 2008 in Foswiki; use $Foswiki::cfg{UsersWebName} instead

    getTwikiWebname( ) → $name

    Deprecated 28 Nov 2008 in Foswiki; use $Foswiki::cfg{SystemWebName} instead

    getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) → $url

    Compose fully qualified 'oops' dialog URL Return: $url URL, e.g. "http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked&param1=joe"

    Deprecated 28 Nov 2008, the recommended approach is to throw an oops exception.
       use Error qw( :try );
    
       throw Foswiki::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 = Foswiki::Func::getScriptUrl($web, $topic, 'oops',
                template => 'oopstoestuckerror',
                param1 => 'I got my toe stuck');
       Foswiki::Func::redirectCgiQuery( undef, $url );
       return 0;
    

    wikiToEmail( $wikiName ) → $email

    Get the e-mail address(es) of the named user. If the user has multiple e-mail addresses (for example, the user is a group), then the list will be comma-separated.

    Deprecated 28 Nov 2008 in favour of wikinameToEmails, because this function only returns a single email address, where a user may in fact have several.

    $wikiName may also be a login name.

    permissionsSet( $web ) → $boolean

    Test if any access restrictions are set for this web, ignoring settings on individual pages

    Deprecated 28 Nov 2008 - 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 = Foswiki::Func::getPreferencesValue( $pref, $web ) || '';
            if( $val =~ m/\S/ ) {
                print "$pref is set to $val on $web\n";
            }
        }
    }
    

    getPublicWebList( ) → @webs

    Deprecated 28 Nov 2008 - use getListOfWebs instead.

    Get list of all public webs, e.g. all webs and subwebs that do not have the NOSEARCHALL flag set in the WebPreferences

    Return: @webs List of all public webs and subwebs

    formatTime( $time, $format, $timezone ) → $text

    Deprecated 28 Nov 2008 - use Foswiki::Time::formatTime instead (it has an identical interface).

    Format the time in seconds into the desired time string Return: $text Formatted time string
    Note: if you used the removed formatGmTime, add a third parameter 'gmtime'

    formatGmTime( $time, $format ) → $text

    Deprecated 28 Nov 2008 - use Foswiki::Time::formatTime instead.

    Format the time to GM time Return: $text Formatted time string

    getDataDir( ) → $dir

    Deprecated 28 Nov 2008 - use $Foswiki::cfg{DataDir} instead

    getPubDir( ) → $dir

    Deprecated 28 Nov 2008 - use $Foswiki::cfg{PubDir} instead

    getCgiQuery( ) → $query

    Deprecated 31 Mar 2009 - use getRequestObject instead if you can. Code that is expected to run with pre-1.1 versions of Foswiki will still need to use this method, as getRequestObject will not be available.

    readTopicText( $web, $topic, $rev, $ignorePermissions ) → $text

    Read topic text, including meta data

    Return: $text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error

    *Deprecated: 6 Aug 2009. Use readTopic instead. This method returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. Use readTopic instead, which is a lot safer and supports the full set of read options.

    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.

    Deprecated 6 Aug 2009 - use saveTopic instead. saveTopic supports embedded meta-data in the saved text, and also supports the full set of save options.

    Return: $oopsUrl Empty string if OK; the $oopsUrl for calling redirectCgiQuery() in case of error

    my $text = Foswiki::Func::readTopicText( $web, $topic );
    
    # check for oops URL in case of error:
    if( $text =~ m/^http.*?\/oops/ ) {
        Foswiki::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 = Foswiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
    

    addToHEAD( $id, $data, $requires )

    Adds $data to the HTML header (the <head> tag).

    Deprecated 26 Mar 2010 - use addZoZone('head', …).

    ALERT! Note: Any calls using addToHEAD for javascript should be rewritten to use the new script zone in addToZone as soon as possible.

    Rewrite:
    Foswiki::Func::addToHEAD("id", "<script>...</script>", "JQUERYPLUGIN");
    
    To:
    Foswiki::Func::addToZone("script", "id", "<script>...</script>", "JQUERYPLUGIN");
    

    The reason is that all <script> markup should be added to a dedicated zone, script, and so any usage of ADDTOHEAD - which adds to the head zone - will be unable to satisfy ordering requirements when the requirements exist in another zone ( script ).

    See Foswiki:Development/UpdatingExtensionsScriptZone for more details.

    searchInWebContent($searchString, $web, \@topics, \%options ) → reference to a hash - keys of which are topic names

    Deprecated 17 Oct 2010 - use query( …). WARNING: This function has been deprecated in foswiki 1.1.0 for scalability reasons

    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+{.*}%) The \%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 $matches = Foswiki::Func::searchInWebContent( "Slimy Toad", $searchWeb, \@topics,
                { casesensitive => 0, files_without_match => 0 } );
        foreach my $topic (keys(%$matches)) {
             ...etc