Package org.fastily.jwiki.core
Class Wiki
java.lang.Object
org.fastily.jwiki.core.Wiki
public class Wiki extends Object
Main entry point of jwiki. This class aggregates most of the queries/actions which jwiki can perform on a wiki. All methods are backed by static functions and are therefore thread-safe.
- Author:
- Fastily
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Wiki.Builder
Builder used to create Wiki objects. -
Field Summary
Fields Modifier and Type Field Description boolean
debug
Toggles logging of debug information to stderr. -
Method Summary
Modifier and Type Method Description boolean
addText(String title, String add, String reason, boolean top)
Appends text to a page.ArrayList<String>
allPages(String prefix, boolean redirectsOnly, boolean protectedOnly, int cap, NS ns)
Get a list of pages from the Wiki.okhttp3.Response
basicGET(String action, String... params)
Performs a basic GET action on this Wiki.okhttp3.Response
basicPOST(String action, HashMap<String,String> form)
Performs a basic POST action on this Wiki.String
convertIfNotInNS(String title, NS ns)
Check if a title in specified namespace and convert it if it is not.boolean
delete(String title, String reason)
Deletes a page.boolean
edit(String title, String text, String reason)
Edit a page, and check if the request actually went through.boolean
exists(String title)
Checks if a title exists.ArrayList<String>
fileUsage(String title)
Gets a list of pages linking to a file.ArrayList<String>
filterByNS(ArrayList<String> pages, NS... ns)
Filters pages by namespace.ArrayList<String>
getAllowedFileExts()
Gets a list of file extensions for the types of files which can be uploaded to this Wiki.ArrayList<String>
getCategoriesOnPage(String title)
Get the categories of a page.ArrayList<String>
getCategoryMembers(String title, NS... ns)
Get a limited number of titles in a category.int
getCategorySize(String title)
Gets the number of elements contained in a category.ArrayList<Contrib>
getContribs(String user, int cap, boolean olderFirst, boolean createdOnly, NS... ns)
Gets the contributions of a user.ArrayList<String>
getDuplicatesOf(String title, boolean localOnly)
List duplicates of a file.ArrayList<String>
getExternalLinks(String title)
Gets a list of external URLs on a page.ArrayList<ImageInfo>
getImageInfo(String title)
Gets information about a File's revisions.ArrayList<String>
getImagesOnPage(String title)
Gets titles of images linked on a page.String
getLastEditor(String title)
Gets the username of the editor who last edited a page.ArrayList<String>
getLinksOnPage(boolean exists, String title, NS... ns)
Gets all existing or non-existing wiki links on a page.ArrayList<String>
getLinksOnPage(String title, NS... ns)
Gets wiki links on a page.ArrayList<LogEntry>
getLogs(String title, String user, String type, int cap)
List log events.NS
getNS(String prefix)
Takes a Namespace prefix and gets a NS representation of it.String
getPageCreator(String title)
Gets the first editor (creator) of a page.String
getPageText(String title)
Gets the text of a page.ArrayList<ProtectedTitleEntry>
getProtectedTitles(int limit, boolean olderFirst, NS... ns)
Fetches protected titles (create-protected) on the Wiki.ArrayList<String>
getRandomPages(int limit, NS... ns)
Gets a list of random pages.ArrayList<RCEntry>
getRecentChanges(Instant start, Instant end)
Gets a specified number of Recent Changes in between two timestamps.ArrayList<Revision>
getRevisions(String title, int cap, boolean olderFirst, Instant start, Instant end)
Gets the revisions of a page.ArrayList<String>
getSharedDuplicatesOf(String title)
Gets the shared (non-local) duplicates of a file.ArrayList<String>
getTemplatesOnPage(String title)
Gets templates transcluded on a page.String
getTextExtract(String title)
Gets a text extract (the lead paragraph) of a page.ArrayList<String>
getUserUploads(String user)
Get a user's uploads.Wiki
getWiki(String domain)
Gets a Wiki object for this domain.ArrayList<Tuple<String,String>>
globalUsage(String title)
Gets the global usage of a file.ArrayList<String>
listUserRights(String user)
Gets the list of usergroups (rights) a user belongs to.boolean
login(String user, String password)
Performs a login with the specified username and password.String
nss(String title)
Strip the namespace from a title.ArrayList<String>
nss(Collection<String> l)
Strips the namespaces from a Collection of titles.ArrayList<String>
prefixIndex(NS namespace, String prefix)
Does the same thing as Special:PrefixIndex.void
purge(String... titles)
Purges page caches.ArrayList<String>
querySpecialPage(String title, int cap)
Queries a special page.void
refreshLoginStatus()
Refresh the login status of a Wiki.boolean
replaceText(String title, String regex, String reason)
Removes text from a page.boolean
replaceText(String title, String regex, String replacement, String reason)
Replaces text on a page.String
resolveRedirect(String title)
Attempts to resolve title redirects on a Wiki.ArrayList<String>
search(String query, int limit, NS... ns)
Performs a search on the Wiki.ArrayList<PageSection>
splitPageByHeader(String title)
Splits the text of a page by header.String
talkPageBelongsTo(String title)
Get the name of a page belonging to a talk page (title
).String
talkPageOf(String title)
Get the talk page oftitle
.String
toString()
Gets a String representation of this Wiki, in the format[username @ domain]
boolean
undelete(String title, String reason)
Undelete a page.boolean
upload(Path p, String title, String text, String reason)
Upload a media file.boolean
uploadByUrl(okhttp3.HttpUrl url, String title, String desc, String summary)
Upload a file by URL.ArrayList<String>
whatLinksHere(String title)
Gets a list of direct links to a page.ArrayList<String>
whatLinksHere(String title, boolean redirects)
Gets a list of links or redirects to a page.ArrayList<String>
whatTranscludesHere(String title, NS... ns)
Gets a list of pages transcluding a template.NS
whichNS(String title)
Gets the namespace, in NS form, of a title.String
whoami()
Gets this Wiki's logged in user.
-
Field Details
-
debug
public boolean debugToggles logging of debug information to stderr. Disabled (false) by default. Changes take effect immediately.
-
-
Method Details
-
login
Performs a login with the specified username and password. Does nothing if this Wiki is already logged in as a user.- Parameters:
user
- The username to usepassword
- The password to use- Returns:
- True if the user is now logged in.
-
refreshLoginStatus
public void refreshLoginStatus()Refresh the login status of a Wiki. This runs automatically on login or creation of a new CentralAuth'd Wiki. -
basicGET
Performs a basic GET action on this Wiki. Use this to implement custom or non-standard API calls.- Parameters:
action
- The action to perform.params
- Each parameter and its corresponding value. For example, the parameters,&foo=bar&baz=blah
, should be passed in as {"foo", "bar", "baz", "blah"
}. URL-encoding will be applied automatically.- Returns:
- The Response from the server, or null on error.
-
basicPOST
Performs a basic POST action on this Wiki. Use this to implement custom or non-standard API calls.- Parameters:
action
- The action to perform.form
- The form data to post. This will be automatically URL-encoded.- Returns:
- The Response from the server, or null on error.
-
convertIfNotInNS
Check if a title in specified namespace and convert it if it is not.- Parameters:
title
- The title to checkns
- The namespace to convert the title to.- Returns:
- The same title if it is in
ns
, or the converted title.
-
filterByNS
Filters pages by namespace. Only pages with a namespace inns
are selected.- Parameters:
pages
- Titles to filterns
- Pages in this/these namespace(s) will be returned.- Returns:
- Titles belonging to a NS in
ns
-
getNS
Takes a Namespace prefix and gets a NS representation of it. PRECONDITION: the prefix must be a valid namespace prefix. WARNING: This method is CASE-SENSITIVE, so be sure to spell and capitalize the prefix exactly as it would appear on-wiki.- Parameters:
prefix
- The prefix to use, without the ":".- Returns:
- An NS representation of the prefix.
-
getWiki
Gets a Wiki object for this domain. This method is cached. A new Wiki will be created as necessary. PRECONDITION: The CentralAuth extension is installed on the target MediaWiki farm.- Parameters:
domain
- The domain to use- Returns:
- The Wiki, or null on error.
-
nss
Strip the namespace from a title.- Parameters:
title
- The title to strip the namespace from- Returns:
- The title without a namespace
-
nss
Strips the namespaces from a Collection of titles.- Parameters:
l
- The Collection of titles to strip namespaces from- Returns:
- A List where each of the titles does not have a namespace.
-
talkPageOf
Get the talk page oftitle
.- Parameters:
title
- The title to get a talk page for.- Returns:
- The talk page of
title
, or null iftitle
is a special page or is already a talk page.
-
talkPageBelongsTo
Get the name of a page belonging to a talk page (title
).- Parameters:
title
- The talk page whose content page will be determined.- Returns:
- The title of the content page associated with the specified talk page, or null if
title
is a special page or is already a content page.
-
whichNS
Gets the namespace, in NS form, of a title. No namespace or an invalid namespace is assumed to be part of Main.- Parameters:
title
- The title to get an NS for.- Returns:
- The title's NS.
-
whoami
Gets this Wiki's logged in user.- Returns:
- The user who is logged in, or null if not logged in.
-
toString
Gets a String representation of this Wiki, in the format[username @ domain]
-
addText
Appends text to a page. Iftitle
does not exist, then create the page normally withtext
- Parameters:
title
- The title to edit.add
- The text to appendreason
- The reason to use.top
- Set to true to prepend text. False will append text.- Returns:
- True if we were successful.
-
edit
Edit a page, and check if the request actually went through.- Parameters:
title
- The title to usetext
- The text to usereason
- The edit summary to use- Returns:
- True if the operation was successful.
-
delete
Deletes a page. You must have admin rights or this won't work.- Parameters:
title
- Title to deletereason
- The reason to use- Returns:
- True if the operation was successful.
-
purge
Purges page caches.- Parameters:
titles
- The titles to purge.
-
replaceText
Removes text from a page. Does nothing if the replacement requested wouldn't change any text on wiki (method still returns true however).- Parameters:
title
- The title to perform the replacement at.regex
- A regex matching the text to remove.reason
- The edit summary.- Returns:
- True if we were successful.
-
replaceText
Replaces text on a page. Does nothing if the replacement requested wouldn't change any text on wiki (method still returns true however).- Parameters:
title
- The title to perform replacement on.regex
- The regex matching the text to replace.replacement
- The replacing text.reason
- The edit summary.- Returns:
- True if were were successful.
-
undelete
Undelete a page. You must have admin rights on the wiki you are trying to perform this task on, otherwise it won't go through.- Parameters:
title
- The title to undeletereason
- The reason to use- Returns:
- True if we successfully undeleted the page.
-
upload
Upload a media file.- Parameters:
p
- The file to usetitle
- The title to upload to. Must include "File:" prefix.text
- The text to put on the file description pagereason
- The edit summary- Returns:
- True if we were successful.
-
uploadByUrl
Upload a file by URL. The URL must be on the upload by url whitelist for the target Wiki or this method will automatically fail.- Parameters:
url
- The URL the target file is located at.title
- The title to upload to.desc
- The text to put on the file description pagesummary
- The edit summary- Returns:
- True if the upload was successful.
-
allPages
public ArrayList<String> allPages(String prefix, boolean redirectsOnly, boolean protectedOnly, int cap, NS ns)Get a list of pages from the Wiki.- Parameters:
prefix
- Only return titles starting with this prefix. DO NOT include a namespace prefix (e.g.File:
). Optional param - set null to disableredirectsOnly
- Set true to get redirects only.protectedOnly
- Set true to get protected pages only.cap
- The max number of titles to return. Optional param - set-1
to get all pages.ns
- The namespace to filter by. Optional param - set null to disable- Returns:
- A list of titles on this Wiki, as specified.
-
exists
Checks if a title exists.- Parameters:
title
- The title to query.- Returns:
- True if the title exists.
-
fileUsage
Gets a list of pages linking to a file.- Parameters:
title
- The title to query. PRECONDITION: This must be a valid file name prefixed with the "File:" prefix, or you will get strange results.- Returns:
- A list of pages linking to the file.
-
getAllowedFileExts
Gets a list of file extensions for the types of files which can be uploaded to this Wiki. WARNING: this method is not cached so save the result.- Returns:
- A list of file extensions for files which can be uploaded to this Wiki.
-
getCategoriesOnPage
Get the categories of a page.- Parameters:
title
- The title to get categories of.- Returns:
- A list of categories, or the empty list if something went wrong.
-
getCategoryMembers
Get a limited number of titles in a category.- Parameters:
title
- The category to query, including the "Category:" prefix.ns
- Namespace filter. Any title not in the specified namespace(s) will be ignored. Leave blank to select all namespaces. CAVEAT: skipped items are counted againstcap
.- Returns:
- The list of titles, as specified, in the category.
-
getCategorySize
Gets the number of elements contained in a category.- Parameters:
title
- The title to query. PRECONDITION: Title *must* begin with the "Category:" prefix- Returns:
- The number of elements in the category. Value returned will be -1 if Category entered was empty and non-existent.
-
getContribs
public ArrayList<Contrib> getContribs(String user, int cap, boolean olderFirst, boolean createdOnly, NS... ns)Gets the contributions of a user.- Parameters:
user
- The user to get contribs for, without the "User:" prefix.cap
- The maximum number of results to return. Optional, disable with -1 (caveat: this will get *all* of a user's contributions)olderFirst
- Set to true to enumerate from older → newer revisionsns
- Restrict titles returned to the specified Namespace(s). Optional, leave blank to select all namespaces.createdOnly
- Filter returned titles for instances where the contribution was a page creation. Optional, set false to disable.- Returns:
- A list of contributions.
-
getDuplicatesOf
List duplicates of a file.- Parameters:
title
- The title to query. PRECONDITION: You MUST include the namespace prefix (e.g. "File:")localOnly
- Set to true to restrict results to local duplicates only.- Returns:
- Duplicates of this file.
-
getExternalLinks
Gets a list of external URLs on a page.- Parameters:
title
- The title to query- Returns:
- A List of external links found on the page.
-
getImageInfo
Gets information about a File's revisions. Does not fill the thumbnail param of ImageInfo.- Parameters:
title
- The title of the file to use (must be in the file namespace and exist, else return null)- Returns:
- A list of ImageInfo objects, one for each revision. The order is newer -> older.
-
getImagesOnPage
Gets titles of images linked on a page.- Parameters:
title
- The title to query- Returns:
- The images found on
title
-
getLastEditor
Gets the username of the editor who last edited a page.- Parameters:
title
- The title to query- Returns:
- The most recent editor of
title
(excludingUser:
prefix) or null on error.
-
getLinksOnPage
Gets wiki links on a page.- Parameters:
title
- The title to queryns
- Namespaces to include-only. Optional, leave blank to select all namespaces.- Returns:
- The list of wiki links on the page.
-
getLinksOnPage
Gets all existing or non-existing wiki links on a page.- Parameters:
exists
- Fetch mode. Set true to get existing pages and false to get missing/non-existent pages.title
- The title to queryns
- Namespaces to include-only. Optional, leave blank to select all namespaces.- Returns:
- The list of existing links on
title
-
getLogs
List log events. Order is newer -> older.- Parameters:
title
- The title to fetch logs for. Optional - set null to disable.user
- The performing user to filter log entries by. Optional - set null to disabletype
- The type of log to get (e.g. delete, upload, patrol). Optional - set null to disablecap
- Limits the number of entries returned from this log. Optional - set -1 to disable- Returns:
- The log entries.
-
getPageCreator
Gets the first editor (creator) of a page. Specifically, get the author of the first revision oftitle
.- Parameters:
title
- The title to query- Returns:
- The page creator (excluding
User:
prefix) or null on error.
-
getPageText
Gets the text of a page.- Parameters:
title
- The title to query- Returns:
- The text of the page, or an empty string if the page is non-existent/something went wrong.
-
getProtectedTitles
Fetches protected titles (create-protected) on the Wiki.- Parameters:
limit
- The maximum number of returned entries. Set -1 to disable.olderFirst
- Set to true to get older entries first.ns
- Namespace filter, limits returned titles to these namespaces. Optional param - leave blank to disable.- Returns:
- An ArrayList of protected titles.
-
getRandomPages
Gets a list of random pages.- Parameters:
limit
- The number of titles to retrieve. PRECONDITION:limit
cannot be a negative number.ns
- Returned titles will be in these namespaces. Optional param - leave blank to disable.- Returns:
- A list of random titles on this Wiki.
-
getRecentChanges
Gets a specified number of Recent Changes in between two timestamps. WARNING: if you use bothstart
andend
, thenstart
MUST be earlier thanend
. If you set bothstart
andend
to null, then the default behavior is to fetch the last 30 seconds of recent changes.- Parameters:
start
- The Instant to start enumerating from. Can be used withoutend
. Optional param - set null to disable.end
- The Instant to stop enumerating at.start
must be set, otherwise this will be ignored. Optional param - set null to disable.- Returns:
- A list Recent Changes where return order is newer -> Older
-
getRevisions
public ArrayList<Revision> getRevisions(String title, int cap, boolean olderFirst, Instant start, Instant end)Gets the revisions of a page.- Parameters:
title
- The title to querycap
- The maximum number of results to return. Optional param: set to any number zero or less to disable.olderFirst
- Set to true to enumerate from older → newer revisionsstart
- The instant to start enumerating from. Start date must occur before end date. Optional param - set null to disable.end
- The instant to stop enumerating at. Optional param - set null to disable.- Returns:
- A list of page revisions
-
getSharedDuplicatesOf
Gets the shared (non-local) duplicates of a file. PRECONDITION: The Wiki this query is run against has the GlobalUsage extension installed.- Parameters:
title
- The title of the file to query- Returns:
- An ArrayList containing shared duplicates of the file
-
getTemplatesOnPage
Gets templates transcluded on a page.- Parameters:
title
- The title to query.- Returns:
- The templates transcluded on
title
-
getTextExtract
Gets a text extract (the lead paragraph) of a page.- Parameters:
title
- The title to get a text extract for.- Returns:
- The text extract. Null if
title
does not exist or is a special page.
-
getUserUploads
Get a user's uploads.- Parameters:
user
- The username, without the "User:" prefix. PRECONDITION:user
must be a valid username.- Returns:
- This user's uploads
-
globalUsage
Gets the global usage of a file. PRECONDITION: GlobalUsage must be installed on the target Wiki.- Parameters:
title
- The title to query. Must start withFile:
prefix.- Returns:
- A HashMap with the global usage of this file; each element is of the form
[ title : wiki ]
.
-
listUserRights
Gets the list of usergroups (rights) a user belongs to. Sample groups: sysop, user, autoconfirmed, editor.- Parameters:
user
- The user to get rights information for. Do not include "User:" prefix.- Returns:
- The usergroups
user
belongs to, or null ifuser
is an IP or non-existent user.
-
prefixIndex
Does the same thing as Special:PrefixIndex.- Parameters:
namespace
- The namespace to filter by (inclusive)prefix
- Get all titles in the specified namespace, that start with this String. To select subpages only, append a/
to the end of this parameter.- Returns:
- The list of titles starting with the specified prefix
-
querySpecialPage
Queries a special page.- Parameters:
title
- The special page to query, without theSpecial:
prefix. CAVEAT: this is CASE-sensitive, so be sure to use the exact title (e.g.UnusedFiles
,BrokenRedirects
). For a full list of titles, see the official documentation.cap
- The maximum number of elements to return. Use-1
to get everything, but be careful because some pages can have 10k+ entries.- Returns:
- A List of titles returned by this special page.
-
resolveRedirect
Attempts to resolve title redirects on a Wiki.- Parameters:
title
- The title to attempt resolution at.- Returns:
- The resolved title, or the original title if it was not a redirect.
-
search
Performs a search on the Wiki.- Parameters:
query
- The query string to search the Wiki with.limit
- The maximum number of entries to return. Optional, specify-1
to disable (not recommended if your wiki is big).ns
- Limit search to these namespaces. Optional, leave blank to disable. The default behavior is to search all namespaces.- Returns:
- A List of titles found by the search.
-
splitPageByHeader
Splits the text of a page by header.- Parameters:
title
- The title to query- Returns:
- An ArrayList where each section (in order) is contained in a PageSection object.
-
whatLinksHere
Gets a list of links or redirects to a page.- Parameters:
title
- The title to queryredirects
- Set to true to get redirects only. Set to false to filter out all redirects.- Returns:
- A list of links or redirects to this page.
-
whatLinksHere
Gets a list of direct links to a page. CAVEAT: This does not get any pages linking to a redirect pointing to this page; in order to do this you will first need to obtain a list of redirects to the target, and then callwhatLinksHere()
on each of those redirects.- Parameters:
title
- The title to query- Returns:
- A list of links to this page.
-
whatTranscludesHere
Gets a list of pages transcluding a template.- Parameters:
title
- The title to query. You *must* include the namespace prefix (e.g. "Template:") or you will get strange results.ns
- Only return results from this/these namespace(s). Optional param: leave blank to disable.- Returns:
- The pages transcluding
title
.
-