public package
Foswiki::Meta public package
Foswiki::Meta Objects of this class act as handles onto real store objects. An object of this class can represent the Foswiki root, a web, or a topic.
Meta objects interact with the store using only the methods of Foswiki::Store. The rest of the core should interact only with Meta objects; the only exception to this are the *Exists methods that are published by the store interface (and facaded by the Foswiki class).A meta object exists in one of two states; either unloaded, in which case it is simply a lightweight handle to a store location, and loaded, in which case it acts as a portal onto the actual store content of a specific revision of the topic.
An unloaded object is constructed by thenew
constructor on this class,
passing one to three parameters depending on whether the object represents the
root, a web, or a topic.
A loaded object may be constructed by calling the load
constructor, or
a previously constructed object may be converted to 'loaded' state by
calling loadVersion
. Once an object is loaded with a specific revision, it
cannot be reloaded.
Unloaded objects return undef from getLoadedRev
, or the loaded revision
otherwise.
An unloaded object can be populated through calls to text($text)
, put
and putKeyed
. Such an object can be saved using save()
to create a new
revision of the topic.
To the caller, a meta object carries two types of data. The first
is the "plain text" of the topic, which is accessible through the text()
method. The object also behaves as a hash of different types of
meta-data (keyed on the type, such as 'FIELD' and 'FILEATTACHMENT').
Each entry in the hash is an array, where each entry in the array contains another hash of the key=value pairs, corresponding to a single meta-datum.
If there may be multiple entries of the same top-level type (i.e. for FIELD and FILEATTACHMENT) then the array has multiple entries. These types are referred to as "keyed" types. The array entries are keyed with the attribute 'name' which must be in each entry in the array.
For unkeyed types, the array has only one entry.
Pictorially,_indices
field gives a quick lookup into this
structure; it is a hash of top-level types, each mapping to a hash indexed
on the key name. For the above example, it looks like this: Foswiki::Meta
do not check access permissions
(other than haveAccess
, obviously).
This is a deliberate design decision, as these checks are expensive and many
callers don't require them. For this reason, be very careful how you use
Foswiki::Meta
. Extension authors will almost always find the methods
they want in Foswiki::Func
, rather than in this class.
Since date indicates where functions or parameters have been added since
the baseline of the API (Foswiki release 4.2.3). The date indicates the
earliest date of a Foswiki release that will support that function or
parameter.
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.
PUBLIC %VALIDATE;
META:x validation. This hash maps from META: names to the type record registered by registerMETA. See registerMETA for more information on what these records contain.
_default is set on base meta-data types (those not added by Foswiki::Func::registerMETA) to differentiate the minimum required meta-data and that added by extensions.StaticMethod
registerMETA($name, %syntax) Foswiki supports embedding meta-data into topics. For example,
%META:BOOK{title="Transit" author="Edmund Cooper" isbn="0-571-05724-1"}%
This meta-data is validated when it is read from the store. Meta-data
that is not registered, or doesn't pass validation, is ignored. This
function allows you to register a new META datum, passing the name in
$name
. %syntax
contains information about the syntax and semantics of
the tag.
The following entries are supported in %syntax
many=>1
. By default meta-data are single valued i.e. can only occur once
in a topic. If you require the meta-data to be repeated many times (like
META:FIELD and META:ATTACHMENT) then you must set this option. For example,
to declare a many-valued BOOK
meta-data type:
registerMeta('BOOK', many => 1)
require=>[]
is used to check that a list of named parameters are present on
the tag. For example,
registerMETA('BOOK', require => [ 'title', 'author' ]);can be used to check that both
title
and author
are present.
allow=>[]
lets you specify other optional parameters that are allowed
on the tag. If you specify allow
then the validation will fail if the
tag contains any parameters that are not in the allow
or require
lists.
If you don't specify allow
then all parameters will be allowed.
require
and allow
only verify the presence of parameters, and
not their values.
other=[]
lets you declare other legal parameters, and is provided
mainly to support the initialisation of DB schema. It it is like
allow
except that it doesn't imply any exclusion of META that contains
unallowed params.
function=>\&fn
causes the function fn
to be called when the
datum is encountered when reading a topic, passing in the name of the
macro and the argument hash. The function must return a non-zero/undef
value if the tag is acceptable, or 0 otherwise. For example:
registerMETA('BOOK', function => sub { my ($name, $args) = @_; # $name will be BOOK return isValidTitle($args->{title}); }can be used to check that
%META:BOOK{}
contains a valid title.
Checks are cumulative, so if you:
registerMETA('BOOK', function => \&checkParameters, require => [ 'title' ], allow => [ 'author', 'isbn' ]);then all these conditions will be tested. Note that
require
and allow
are tested after function
is called, to give the function a chance to
rewrite the parameter list.
If no checker is registered for a META tag, then it will automatically be accepted into the topic meta-data.
alias=>'name'
lets you set an alias for the datum that will be added to
the query language. For example, alias=>'info'
is used to alias
'META:TOPICINFO' in queries.
registerMeta('BOOK', alias => 'book', many => 1)This lets you use syntax such as
books[author='Anais Nin']
in queries.
See QuerySearch for more on aliases.
ClassMethod
new($session, $web, $topic [, $text]) $session
- a Foswiki object (e.g. $Foswiki::Plugins::SESSION
)
$web
, $topic
- the pathname of the object. If both are undef, this object is a handle for the root container. If $topic is undef, it is the handle to a web. Otherwise it's a handle to a topic.
$web
and $topic
are defined.
load
method to load the content.
ClassMethod
new($prototype) ClassMethod
load($session, $web, $topic, $rev) $rev
- revision to load. If undef, 0, '' or > max available rev, will load the latest rev. If the revision is in range but does not exist, then will return an unloaded meta object (getLoadedRev() will be undef)
$this = Foswiki::Meta->new( $session, $web, $topic ); $this->loadVersion( $rev );WARNING: see notes on revision numbers under
getLoadedRev
.
ObjectMethod
load($rev) → $metaObject Load an unloaded meta-data object with a given version of the data. Once loaded, the object is locked to that revision.
$rev
- revision to load. If undef, 0, '' or > max available rev, will load the latest rev. If the revision is in range but does not exist, then will return an unloaded meta object (getLoadedRev() will be undef)
getLoadedRev
TODO: this is insane. load() can fail - but it will give you a seemingly fine Meta object anyway.
ObjectMethod
unload() Return the object to an unloaded state. This method should be used with the greatest of care, as it resets the load state of the object, which may have surprising effects on other code that shares the object.
ObjectMethod
finish() ObjectMethod
session() Get the session (Foswiki) object associated with the object when it was created.
ObjectMethod
web([$name]) $name
- optional, change the web name in the object ObjectMethod
topic([$name]) $name
- optional, change the topic name in the object ObjectMethod
getPath() → $objectpath Get the canonical content access path for the object. For example, a topic "MyTopic" in subweb "Subweb" of web "Myweb" will have an access path "Myweb/Subweb.MyTopic"
ObjectMethod
isSessionTopic() → $boolean ObjectMethod
getPreference( $key ) → $value Foswiki::Func::getPreferencesValue
,
which is almost certainly what you want to call instead.
ObjectMethod
getContainer() → $containerObject Get the container of this object; for example, the web that a topic is within
ObjectMethod
existsInStore() → $boolean A Meta object can be created for a web or topic that doesn't exist in the actual store (e.g. is in the process of being created). This method returns true if the corresponding web or topic really exists in the store.
ObjectMethod
stringify( $debug ) → $string Return a string version of the meta object. $debug adds extra debug info.
ObjectMethod
addDependency() → $this ObjectMethod
fireDependency() → $this ObjectMethod
isCacheable() → $boolean Return true if page caching is enabled and this topic object is cacheable.
ObjectMethod
populateNewWeb( [$baseWeb [, $opts]] ) $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 this 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.
StaticMethod
query($query, $inputTopicSet, \%options) → $outputTopicSet $query
must be a Foswiki::*::Node
object.
web
param of SEARCH
ObjectMethod
eachWeb( $all ) → $iterator $all
is set, will return a
list of all web names under the current location. Returns web pathnames
relative to $this.
Only valid on webs and the root.
ObjectMethod
eachTopic() → $iterator Return an iterator over each topic name in the web. Only valid on webs.
ObjectMethod
eachAttachment() → $iterator Return an iterator over each attachment name in the topic. Only valid on topics.
The list of the names of attachments stored for the given topic may be a longer list than the list that comes from the topic meta-data, which may only lists the attachments that are normally visible to the user.
ObjectMethod
eachChange( $time ) → $iterator $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}). Changes are returned in most-recent-first
order.
If the object is a web, changes for all topics within that web will be iterated. If it's a topic, then all changes to the topic will be iterated.
Each element of the iterator is a reference to a hash:verb
- the action - one of update
- a web, topic or attachment has been modified
insert
- a web, topic or attachment is being inserted
remove
- a topic or attachment is being removed
time
- epoch-secs time of the change
cuid
- who is making the change
revision
- the revision of the topic that the change appears in
path
- canonical web.topic path for the affected object
attachment
- attachment name (optional)
oldpath
- canonical web.topic path for the origin of a move/rename
oldattachment
- origin of move
minor
- boolean true if this change is flagged as minor
comment
- descriptive text
topic
- name of the topic the change occurred to
more
- formatted string indicating if the change was minor or not
user
- wikiname of the changing user
ObjectMethod
loadVersion($rev) → $version Load the object from the store. The object must not be already loaded with a different rev (verified by an ASSERT)
SeegetLoadedRev
to determine what revision is currently being viewed. $rev
- revision to load. If undef, 0, '' or > max available rev, will load the latest rev. If the revision is in range but does not exist, then will return an unloaded meta object (getLoadedRev() will be undef)
Returns the version identifier for the loaded revision. (and undef if it failed to load)
WARNING: see notes on revision numbers undergetLoadedRev
ObjectMethod
text([$text]) → $text Get/set the topic body text. If $text is undef, gets the value, if it is defined, sets the value to that and returns the new text.
Be warned - it can return undef - when a topic exists but has no topicText.
ObjectMethod
put($type, \%args) putKeyed
)
For example,
$meta->put( 'FIELD', { name => 'MaxAge', title => 'Max Age', value =>'103' } );
ObjectMethod
putKeyed($type, \%args) Put a hash of key=value pairs into the given type set in this meta, replacing any existing value with the same key.
For example,$meta->putKeyed( 'FIELD', { name => 'MaxAge', title => 'Max Age', value =>'103' } );
ObjectMethod
putAll Replaces all the items of a given key with a new array.
For example,$meta->putAll( 'FIELD', { name => 'MinAge', title => 'Min Age', value =>'50' }, { name => 'MaxAge', title => 'Max Age', value =>'103' }, { name => 'HairColour', title => 'Hair Colour', value =>'white' } );
ObjectMethod
get( $type, $key ) → \%hash name
), the $key
parameter is required
to say which entry you want. Otherwise you will just get the first value.
If you want all the keys of a given type use the 'find' method.
The result is a reference to the hash for the item.
For example,my $ma = $meta->get( 'FIELD', 'MinAge' ); my $topicinfo = $meta->get( 'TOPICINFO' ); # get the TOPICINFO hash
ObjectMethod
find ( $type ) → @values Get all meta data for a specific type. Returns the array stored for the type. This will be zero length if there are no entries.
For example,my $attachments = $meta->find( 'FILEATTACHMENT' );
ObjectMethod
remove($type, $key) With no type, will remove all the meta-data in the object.
With a $type but no $key, will remove all items of that type (so for example if $type were FILEATTACHMENT it would remove all of them)With a $type and a $key it will remove only the specific item.
ObjectMethod
copyFrom( $otherMeta [, $type [, $nameFilter]] ) Copy all entries of a type from another meta data set. This will destroy the old values for that type, unless the copied object doesn't contain entries for that type, in which case it will retain the old values.
If $type is undef, will copy ALL TYPES.
If $nameFilter is defined (a perl regular expression), it will copy only data where{name}
matches $nameFilter.
Does not copy web, topic or text.
ObjectMethod
count($type) → $integer Return the number of entries of the given type
ObjectMethod
setRevisionInfo( %opts ) version
- the revision number
time
- the time stamp
author
- the user id (cUID)
ObjectMethod
getRevisionInfo([$attachment [,$rev]]) → \%info $attachment
- (optional) attachment name to get info about
$rev
- (optional) revision of attachment for which to get info
{date}
in epochSec
{author}
canonical user ID
{version}
the revision number
ObjectMethod
getRevisionInfo() → ( $revDate, $author, $rev, $comment ) ObjectMethod
merge( $otherMeta, $formDef ) $otherMeta
- a block of meta-data to merge with $this
$formDef
reference to a Foswiki::Form that gives the types of the fields in $this
isTextMergeable
method on the form def is used to determine if that field is mergeable. If it isn't, the value currently in meta will not be changed.
ObjectMethod
forEachSelectedValue( $types, $keys, \&fn, \%options ) $types
- regular expression matching the names of fields to be processed. Will default to qr/^[A-Z]+$/ if undef.
$keys
- regular expression matching the names of keys to be processed. Will default to qr/^[a-z]+$/ if undef.
\&fn
on each, and replacing the value
with the result of \&fn.
\%options will be passed on to $fn, with the following additions: _type
=> the type name (e.g. "FILEATTACHMENT")
_key
=> the key name (e.g. "user")
ObjectMethod
getParent() → $parent Gets the TOPICPARENT name. Safe shortcut for =$meta->get('TOPICPARENT')->{name} Returns the emty string if there is no parent.
ObjectMethod
getFormName() → $formname Returns the name of the FORM, or '' if none.
ObjectMethod
renderFormForDisplay() → $html Render the form contained in the meta for display.
ObjectMethod
renderFormFieldForDisplay($name, $format, $attrs) → $text ObjectMethod
haveAccess($mode, $cUID) → $boolean $mode
- 'VIEW', 'CHANGE', 'CREATE', etc. (defaults to VIEW)
$cUID
- Canonical user id (defaults to current user)
ObjectMethod
save( %options ) %options
- Hash of options, see saveAs for list of keys
ObjectMethod
saveAs( $web, $topic, %options ) → $rev $web.$topic
- where to move to (defaults to web.topic in the object)
%options
- Hash of options, may include: forcenewrevision
- force an increment in the revision number, even if content doesn't change.
dontlog
- don't include this change in statistics
minor
- don't notify this change
savecmd
- Save command (core use only)
forcedate
- force the revision date to be this (core only)
author
- cUID of author of change (core only - default current user)
nohandlers
- do not call plugins handlers
Returns the saved revision number.
ObjectMethod
move($to, %opts) user
- cUID of the user doing the moving.
ObjectMethod
deleteMostRecentRevision(%opts) %opts
may include user
- cUID of user doing the unlocking
ObjectMethod
replaceMostRecentRevision( %opts ) forcedate
- try and re-use the date of the original check
user
- cUID of the user doing the action
ObjectMethod
getRevisionHistory([$attachment]) → $iterator Get an iterator over the range of version identifiers (just the identifiers, not the content) starting with the most recent revision.
The iterator will be empty ($iterator->hasNext() will be false) if the object does not exist.
$attachment is optional.
Not valid on webs.
ObjectMethod
getLatestRev[$attachment]) → $revision Get the revision ID of the latest revision.
$attachment is optional.
Not valid on webs.
Returns an integer revision number > 0 if the object exists.
Returns 0 if the object does not exist.
ObjectMethod
latestIsLoaded() → $boolean Only valid on topics.
ObjectMethod
getLoadedRev() → $integer Get the currently loaded revision. Result will be a revision number, or undef if no revision has been loaded. Only valid on topics.
WARNING: some store implementations use the concept of a "working copy" of each topic that may be modified without being added to the revision control system. This means that the version number reported for the latest rev may not be the actual latest version.ObjectMethod
setLoadStatus($rev, $isLatest) Foswiki::Store::readTopic
. Do not use for anything else!
ObjectMethod
removeFromStore( $attachment ) $attachment
- optional, provide to delete an attachment
Use with great care! Removes all trace of the given web, topic or attachment from the store, possibly including all its history.
Also does not ensure consistency of the store (for eg, if you delete an attachment, it does not update the in-topic META)
ObjectMethod
getDifferences( $rev2, $contextLines ) → \@diffArray $rev2
- the other revision to diff against
$contextLines
- number of lines of context required
type | Means |
---|---|
+ |
Added |
- |
Deleted |
c |
Changed |
u |
Unchanged |
l |
Line Number |
ObjectMethod
getRevisionAtTime( $time ) → $rev $time
- time (in epoch secs) for the rev
Get the revision number for a topic at a specific time. Returns a single-digit rev number or 0 if it couldn't be determined (either because the topic isn't that old, or there was a problem)
ObjectMethod
setLease( $length ) Take out an lease on the given topic for this user for $length seconds.
SeegetLease
for more details about Leases.
ObjectMethod
getLease() → $lease user
, taken
and expires
).
Leases are taken out when a topic is edited. Only one lease
can be active on a topic at a time. Leases are used to warn if
another user is already editing a topic.
ObjectMethod
clearLease() Cancel the current lease.
SeegetLease
for more details about Leases.
ObjectMethod
onTick($time) Method invoked at regular intervals, usually by a cron job. The job of this method is to prod the store into cleaning up expired leases, and any other admin job that needs doing at regular intervals.
$attachment
- attachment name
$rev
- optional integer attachment revision number
$info will contain at least: date, author, version, comment
Deprecated 2014-11-03 use getRevisionInfo instead.ObjectMethod
attach ( %opts ) %opts
may include: name
- Name of the attachment - required
dontlog
- don't add to statistics
comment
- comment for save
hide
- if the attachment is to be hidden in normal topic view
stream
- Stream of file to upload. Uses file
if not set.
file
- Name of a server file to use for the attachment data. This should be passed if it is known, as it may be used to optimise handler calls.
filepath
- Optional. Client path to file.
filesize
- Optional. Size of uploaded data.
filedate
- Optional. Date of file.
author
- Optional. cUID of author of change. Defaults to current.
notopicchange
- Optional. if the topic is not to be modified. This may result in incorrect meta-data stored in the topic, so must be used with care. Only has a meaning if the store implementation stores meta-data in topics.
nohandlers
- do not call plugin handlers
Saves a new revision of the attachment, invoking plugin handlers as appropriate. This method automatically updates the loaded rev of $this to the latest topic revision.
If neither ofstream
or file
are set, this is a properties-only save.
Throws an exception on error.
ObjectMethod
hasAttachment( $name ) → $boolean ObjectMethod
testAttachment( $name, $test ) → $value $name
- name of the attachment to test e.g lolcat.gif
* $test
- the test to perform e.g. 'r'
The return value is the value that would be returned by the standard perl file operations, as indicated by $type
* r File is readable by current user (tests Foswiki VIEW permission) * w File is writable by current user (tests Foswiki CHANGE permission) * e File exists. * z File has zero size. * s File has nonzero size (returns size). * T File is an ASCII text file (heuristic guess). * B File is a "binary" file (opposite of T). * M Last modification time (epoch seconds). * A Last access time (epoch seconds).
Note that all these types should behave as the equivalent standard perl operator behaves, except M and A which are independent of the script start time (see perldoc -f -X for more information)
Other standard Perl file tests may also be supported on some store implementations, but cannot be relied on.
Errors will be signalled by an Error::Simple exception.
$attachment
- the attachment
$mode
- mode to open the attachment in
$mode
can be '<', '>' or '>>' for read, write, and append
respectively.
%opts
can take different settings depending on $mode
. $mode='<'
version
- revision of the object to open e.g. version => 6
$mode='>'
or ='>>' Error
exception.
See also attach
if this function is too basic for you.
ObjectMethod
moveAttachment( $name, $to, %opts ) → $data %opts
may include: new_name
- new name for the attachment
user
- cUID of user doing the moving
ObjectMethod
copyAttachment( $name, $to, %opts ) → $data %opts
may include: new_name
- new name for the attachment
user
- cUID of user doing the moving
ObjectMethod
expandNewTopic() The expansion is in-place in the object data.
Only valid on topics.
ObjectMethod
expandMacros( $text ) → $text ObjectMethod
renderTML( $text ) → $text ObjectMethod
summariseText( $flags [, $text, \%searchOptions] ) → $tml Makes a plain text summary of the topic text by simply trimming a bit off the top. Truncates to $TMTRUNC chars or, if a number is specified in $flags, to that length.
If $text is defined, use it in place of the topic text.
The\%searchOptions
hash may contain the following options: type
- search type: keyword, literal, query
casesensitive
- false to ignore case (default true)
wordboundaries
- if type is 'keyword'
tokens
- array ref of search tokens
TODO: should this really be in Meta? it seems like a rendering issue to me.
warning: this will produce text that contains html entities - including quotes use$summary = Foswiki::entityEncode($summary);
to diffuse them
ObjectMethod
_summariseTextSimple( $text, $limit ) → $tml Makes a plain text summary of the topic text by simply trimming a bit off the top. Truncates to $TMTRUNC chars or, if a number is specified in $flags, to that length.
TODO: should this really be in Meta? it seems like a rendering issue to me.
ObjectMethod
_summariseTextWithSearchContext( $text, $limit, $type, $searchOptions ) → $tml Improves the presentation of summaries for keyword, word and literal searches, by displaying topic content on either side of the search terms wherever they are found in the topic.
The\%searchOptions
hash may contain the following options: type
- search type: keyword, literal, query
casesensitive
- false to ignore case (default true)
wordboundaries
- if type is 'keyword'
tokens
- array ref of search tokens
ObjectMethod
summariseChanges( $orev, $nrev, $tml, $nochecks) → $text Generate a (max 3 line) summary of the differences between the revs.
$orev
- older rev, if not defined will use ($nrev - 1)
$nrev
- later rev, if not defined defaults to latest
$tml
- if true will generate renderable TML (i.e. HTML with NOPs. If false will generate a summary suitable for use in plain text (mail, for example)
$nochecks
- if true, access control checks will be suppressed
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.
Generate the embedded store form of the topic. The embedded store form has meta-data values embedded using %META: lines. The text stored in the meta is taken as the topic text.
Deprecated 2014-11-13, and will be removed in Foswiki 2.0. It is retained for compatibility only. useFoswiki::Serialise::serialise($meta, 'Embedded')
instead.
Populate this object with embedded meta-data from $text. This method is a utility provided for use with stores that store data embedded in topic text. Only valid on topics.
Note: line endings must be normalised to \n before calling this method. Deprecated 2014-11-13, and will be removed in Foswiki 2.0. It is retained for compatibility only. useFoswiki::Serialise::deserialise($text, 'Embedded', $meta)
instead.
StaticMethod
isValidEmbedding($macro, \%args) → $boolean \%args
are sufficient to satisfy the
requirements of the embeddable meta-data given by $macro
. For example,
isValidEmbedding('FILEATTACHMENT', $args)
will only succeed if $args contains
at least name
, date
, user
and attr
fields. Note that extra fields are
simply ignored (unless they are explicitly excluded).
If the macro is not registered for validation, then it will be ignored.
If the embedding is not valid, then $Foswiki::Meta::reason is set with a message explaining why.StaticMethod
dataDecode( $encoded ) → $decoded Decode escapes in a string that was encoded using dataEncode
The encoding has to be exported because Foswiki (and plugins) use encoded field data in other places e.g. RDiff, mainly as a shorthand for the properly parsed meta object. Some day we may be able to eliminate that....
ClassMethod
type() → $resourcetype Web/SubWeb/