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
  • Field Details

    • debug

      public boolean debug
      Toggles logging of debug information to stderr. Disabled (false) by default. Changes take effect immediately.
  • Method Details

    • login

      public boolean login​(String user, String password)
      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 use
      password - 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

      public okhttp3.Response basicGET​(String action, String... params)
      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

      public okhttp3.Response basicPOST​(String action, HashMap<String,​String> form)
      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

      public String convertIfNotInNS​(String title, NS ns)
      Check if a title in specified namespace and convert it if it is not.
      Parameters:
      title - The title to check
      ns - The namespace to convert the title to.
      Returns:
      The same title if it is in ns, or the converted title.
    • filterByNS

      public ArrayList<String> filterByNS​(ArrayList<String> pages, NS... ns)
      Filters pages by namespace. Only pages with a namespace in ns are selected.
      Parameters:
      pages - Titles to filter
      ns - Pages in this/these namespace(s) will be returned.
      Returns:
      Titles belonging to a NS in ns
    • getNS

      public NS getNS​(String prefix)
      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

      public Wiki getWiki​(String domain)
      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

      public String nss​(String title)
      Strip the namespace from a title.
      Parameters:
      title - The title to strip the namespace from
      Returns:
      The title without a namespace
    • nss

      public ArrayList<String> nss​(Collection<String> l)
      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

      public String talkPageOf​(String title)
      Get the talk page of title.
      Parameters:
      title - The title to get a talk page for.
      Returns:
      The talk page of title, or null if title is a special page or is already a talk page.
    • talkPageBelongsTo

      public String talkPageBelongsTo​(String title)
      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

      public NS whichNS​(String title)
      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

      public String whoami()
      Gets this Wiki's logged in user.
      Returns:
      The user who is logged in, or null if not logged in.
    • toString

      public String toString()
      Gets a String representation of this Wiki, in the format [username @ domain]
      Overrides:
      toString in class Object
    • addText

      public boolean addText​(String title, String add, String reason, boolean top)
      Appends text to a page. If title does not exist, then create the page normally with text
      Parameters:
      title - The title to edit.
      add - The text to append
      reason - The reason to use.
      top - Set to true to prepend text. False will append text.
      Returns:
      True if we were successful.
    • edit

      public boolean edit​(String title, String text, String reason)
      Edit a page, and check if the request actually went through.
      Parameters:
      title - The title to use
      text - The text to use
      reason - The edit summary to use
      Returns:
      True if the operation was successful.
    • delete

      public boolean delete​(String title, String reason)
      Deletes a page. You must have admin rights or this won't work.
      Parameters:
      title - Title to delete
      reason - The reason to use
      Returns:
      True if the operation was successful.
    • purge

      public void purge​(String... titles)
      Purges page caches.
      Parameters:
      titles - The titles to purge.
    • replaceText

      public boolean replaceText​(String title, String regex, String reason)
      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

      public boolean replaceText​(String title, String regex, String replacement, String reason)
      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

      public boolean undelete​(String title, String reason)
      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 undelete
      reason - The reason to use
      Returns:
      True if we successfully undeleted the page.
    • upload

      public boolean upload​(Path p, String title, String text, String reason)
      Upload a media file.
      Parameters:
      p - The file to use
      title - The title to upload to. Must include "File:" prefix.
      text - The text to put on the file description page
      reason - The edit summary
      Returns:
      True if we were successful.
    • uploadByUrl

      public boolean uploadByUrl​(okhttp3.HttpUrl url, String title, String desc, String summary)
      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 page
      summary - 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 disable
      redirectsOnly - 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

      public boolean exists​(String title)
      Checks if a title exists.
      Parameters:
      title - The title to query.
      Returns:
      True if the title exists.
    • fileUsage

      public ArrayList<String> fileUsage​(String title)
      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

      public ArrayList<String> 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

      public ArrayList<String> getCategoriesOnPage​(String title)
      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

      public ArrayList<String> getCategoryMembers​(String title, NS... ns)
      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 against cap.
      Returns:
      The list of titles, as specified, in the category.
    • getCategorySize

      public int getCategorySize​(String title)
      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 revisions
      ns - 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

      public ArrayList<String> getDuplicatesOf​(String title, boolean localOnly)
      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

      public ArrayList<String> getExternalLinks​(String title)
      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

      public ArrayList<ImageInfo> getImageInfo​(String title)
      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

      public ArrayList<String> getImagesOnPage​(String title)
      Gets titles of images linked on a page.
      Parameters:
      title - The title to query
      Returns:
      The images found on title
    • getLastEditor

      public String getLastEditor​(String title)
      Gets the username of the editor who last edited a page.
      Parameters:
      title - The title to query
      Returns:
      The most recent editor of title (excluding User: prefix) or null on error.
    • getLinksOnPage

      public ArrayList<String> getLinksOnPage​(String title, NS... ns)
      Gets wiki links on a page.
      Parameters:
      title - The title to query
      ns - Namespaces to include-only. Optional, leave blank to select all namespaces.
      Returns:
      The list of wiki links on the page.
    • getLinksOnPage

      public ArrayList<String> getLinksOnPage​(boolean exists, String title, NS... ns)
      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 query
      ns - Namespaces to include-only. Optional, leave blank to select all namespaces.
      Returns:
      The list of existing links on title
    • getLogs

      public ArrayList<LogEntry> getLogs​(String title, String user, String type, int cap)
      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 disable
      type - The type of log to get (e.g. delete, upload, patrol). Optional - set null to disable
      cap - Limits the number of entries returned from this log. Optional - set -1 to disable
      Returns:
      The log entries.
    • getPageCreator

      public String getPageCreator​(String title)
      Gets the first editor (creator) of a page. Specifically, get the author of the first revision of title.
      Parameters:
      title - The title to query
      Returns:
      The page creator (excluding User: prefix) or null on error.
    • getPageText

      public String getPageText​(String title)
      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

      public ArrayList<ProtectedTitleEntry> getProtectedTitles​(int limit, boolean olderFirst, NS... ns)
      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

      public ArrayList<String> getRandomPages​(int limit, NS... ns)
      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

      public ArrayList<RCEntry> getRecentChanges​(Instant start, Instant end)
      Gets a specified number of Recent Changes in between two timestamps. WARNING: if you use both start and end, then start MUST be earlier than end. If you set both start and end 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 without end. 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 query
      cap - 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 revisions
      start - 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

      public ArrayList<String> getSharedDuplicatesOf​(String title)
      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

      public ArrayList<String> getTemplatesOnPage​(String title)
      Gets templates transcluded on a page.
      Parameters:
      title - The title to query.
      Returns:
      The templates transcluded on title
    • getTextExtract

      public String getTextExtract​(String title)
      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

      public ArrayList<String> getUserUploads​(String user)
      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

      public ArrayList<Tuple<String,​String>> globalUsage​(String title)
      Gets the global usage of a file. PRECONDITION: GlobalUsage must be installed on the target Wiki.
      Parameters:
      title - The title to query. Must start with File: prefix.
      Returns:
      A HashMap with the global usage of this file; each element is of the form [ title : wiki ].
    • listUserRights

      public ArrayList<String> listUserRights​(String user)
      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 if user is an IP or non-existent user.
    • prefixIndex

      public ArrayList<String> prefixIndex​(NS namespace, String prefix)
      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

      public ArrayList<String> querySpecialPage​(String title, int cap)
      Queries a special page.
      Parameters:
      title - The special page to query, without the Special: 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

      public String resolveRedirect​(String title)
      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

      public ArrayList<String> search​(String query, int limit, NS... ns)
      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

      public ArrayList<PageSection> splitPageByHeader​(String title)
      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

      public ArrayList<String> whatLinksHere​(String title, boolean redirects)
      Gets a list of links or redirects to a page.
      Parameters:
      title - The title to query
      redirects - 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

      public ArrayList<String> whatLinksHere​(String title)
      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 call whatLinksHere() on each of those redirects.
      Parameters:
      title - The title to query
      Returns:
      A list of links to this page.
    • whatTranscludesHere

      public ArrayList<String> whatTranscludesHere​(String title, NS... ns)
      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.