A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

788 lines
32 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from hashlib import md5
  23. from logging import getLogger, NullHandler
  24. import re
  25. from time import gmtime, strftime
  26. from urllib import quote
  27. import mwparserfromhell
  28. from earwigbot import exceptions
  29. from earwigbot.wiki.copyvios import CopyvioMixIn
  30. __all__ = ["Page"]
  31. class Page(CopyvioMixIn):
  32. """
  33. **EarwigBot: Wiki Toolset: Page**
  34. Represents a page on a given :py:class:`~earwigbot.wiki.site.Site`. Has
  35. methods for getting information about the page, getting page content, and
  36. so on. :py:class:`~earwigbot.wiki.category.Category` is a subclass of
  37. :py:class:`Page` with additional methods.
  38. *Attributes:*
  39. - :py:attr:`site`: the page's corresponding Site object
  40. - :py:attr:`title`: the page's title, or pagename
  41. - :py:attr:`exists`: whether or not the page exists
  42. - :py:attr:`pageid`: an integer ID representing the page
  43. - :py:attr:`url`: the page's URL
  44. - :py:attr:`namespace`: the page's namespace as an integer
  45. - :py:attr:`protection`: the page's current protection status
  46. - :py:attr:`is_talkpage`: ``True`` if this is a talkpage, else ``False``
  47. - :py:attr:`is_redirect`: ``True`` if this is a redirect, else ``False``
  48. *Public methods:*
  49. - :py:meth:`reload`: forcibly reloads the page's attributes
  50. - :py:meth:`toggle_talk`: returns a content page's talk page, or vice versa
  51. - :py:meth:`get`: returns the page's content
  52. - :py:meth:`get_redirect_target`: returns the page's destination if it is a
  53. redirect
  54. - :py:meth:`get_creator`: returns a User object representing the first
  55. person to edit the page
  56. - :py:meth:`parse`: parses the page content for templates, links, etc
  57. - :py:meth:`edit`: replaces the page's content or creates a new page
  58. - :py:meth:`add_section`: adds a new section at the bottom of the page
  59. - :py:meth:`check_exclusion`: checks whether or not we are allowed to edit
  60. the page, per ``{{bots}}``/``{{nobots}}``
  61. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_check`:
  62. checks the page for copyright violations
  63. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_compare`:
  64. checks the page like :py:meth:`copyvio_check`, but against a specific URL
  65. """
  66. PAGE_UNKNOWN = 0
  67. PAGE_INVALID = 1
  68. PAGE_MISSING = 2
  69. PAGE_EXISTS = 3
  70. def __init__(self, site, title, follow_redirects=False, pageid=None,
  71. logger=None):
  72. """Constructor for new Page instances.
  73. Takes four arguments: a Site object, the Page's title (or pagename),
  74. whether or not to follow redirects (optional, defaults to False), and
  75. a page ID to supplement the title (optional, defaults to None - i.e.,
  76. we will have to query the API to get it).
  77. As with User, site.get_page() is preferred.
  78. __init__() will not do any API queries, but it will use basic namespace
  79. logic to determine our namespace ID and if we are a talkpage.
  80. """
  81. super(Page, self).__init__(site)
  82. self._site = site
  83. self._title = title.strip()
  84. self._follow_redirects = self._keep_following = follow_redirects
  85. self._pageid = pageid
  86. # Set up our internal logger:
  87. if logger:
  88. self._logger = logger
  89. else: # Just set up a null logger to eat up our messages:
  90. self._logger = getLogger("earwigbot.wiki")
  91. self._logger.addHandler(NullHandler())
  92. # Attributes to be loaded through the API:
  93. self._exists = self.PAGE_UNKNOWN
  94. self._is_redirect = None
  95. self._lastrevid = None
  96. self._protection = None
  97. self._fullurl = None
  98. self._content = None
  99. self._creator = None
  100. # Attributes used for editing/deleting/protecting/etc:
  101. self._token = None
  102. self._basetimestamp = None
  103. self._starttimestamp = None
  104. # Try to determine the page's namespace using our site's namespace
  105. # converter:
  106. prefix = self._title.split(":", 1)[0]
  107. if prefix != title: # ignore a page that's titled "Category" or "User"
  108. try:
  109. self._namespace = self.site.namespace_name_to_id(prefix)
  110. except exceptions.NamespaceNotFoundError:
  111. self._namespace = 0
  112. else:
  113. self._namespace = 0
  114. # Is this a talkpage? Talkpages have odd IDs, while content pages have
  115. # even IDs, excluding the "special" namespaces:
  116. if self._namespace < 0:
  117. self._is_talkpage = False
  118. else:
  119. self._is_talkpage = self._namespace % 2 == 1
  120. def __repr__(self):
  121. """Return the canonical string representation of the Page."""
  122. res = "Page(title={0!r}, follow_redirects={1!r}, site={2!r})"
  123. return res.format(self._title, self._follow_redirects, self._site)
  124. def __str__(self):
  125. """Return a nice string representation of the Page."""
  126. return '<Page "{0}" of {1}>'.format(self.title, str(self.site))
  127. def _assert_validity(self):
  128. """Used to ensure that our page's title is valid.
  129. If this method is called when our page is not valid (and after
  130. _load_attributes() has been called), InvalidPageError will be raised.
  131. Note that validity != existence. If a page's title is invalid (e.g, it
  132. contains "[") it will always be invalid, and cannot be edited.
  133. """
  134. if self._exists == self.PAGE_INVALID:
  135. e = u"Page '{0}' is invalid.".format(self._title)
  136. raise exceptions.InvalidPageError(e)
  137. def _assert_existence(self):
  138. """Used to ensure that our page exists.
  139. If this method is called when our page doesn't exist (and after
  140. _load_attributes() has been called), PageNotFoundError will be raised.
  141. It will also call _assert_validity() beforehand.
  142. """
  143. self._assert_validity()
  144. if self._exists == self.PAGE_MISSING:
  145. e = u"Page '{0}' does not exist.".format(self._title)
  146. raise exceptions.PageNotFoundError(e)
  147. def _load(self):
  148. """Call _load_attributes() and follows redirects if we're supposed to.
  149. This method will only follow redirects if follow_redirects=True was
  150. passed to __init__() (perhaps indirectly passed by site.get_page()).
  151. It avoids the API's &redirects param in favor of manual following,
  152. so we can act more realistically (we don't follow double redirects, and
  153. circular redirects don't break us).
  154. This will raise RedirectError if we have a problem following, but that
  155. is a bug and should NOT happen.
  156. If we're following a redirect, this will make a grand total of three
  157. API queries. It's a lot, but each one is quite small.
  158. """
  159. self._load_attributes()
  160. if self._keep_following and self._is_redirect:
  161. self._title = self.get_redirect_target()
  162. self._keep_following = False # don't follow double redirects
  163. self._content = None # reset the content we just loaded
  164. self._load_attributes()
  165. def _load_attributes(self, result=None):
  166. """Load various data from the API in a single query.
  167. Loads self._title, ._exists, ._is_redirect, ._pageid, ._fullurl,
  168. ._protection, ._namespace, ._is_talkpage, ._creator, ._lastrevid,
  169. ._token, and ._starttimestamp using the API. It will do a query of
  170. its own unless *result* is provided, in which case we'll pretend
  171. *result* is what the query returned.
  172. Assuming the API is sound, this should not raise any exceptions.
  173. """
  174. if not result:
  175. query = self.site.api_query
  176. result = query(action="query", rvprop="user", intoken="edit",
  177. prop="info|revisions", rvlimit=1, rvdir="newer",
  178. titles=self._title, inprop="protection|url")
  179. res = result["query"]["pages"].values()[0]
  180. self._title = res["title"] # Normalize our pagename/title
  181. self._is_redirect = "redirect" in res
  182. self._pageid = int(result["query"]["pages"].keys()[0])
  183. if self._pageid < 0:
  184. if "missing" in res:
  185. # If it has a negative ID and it's missing; we can still get
  186. # data like the namespace, protection, and URL:
  187. self._exists = self.PAGE_MISSING
  188. else:
  189. # If it has a negative ID and it's invalid, then break here,
  190. # because there's no other data for us to get:
  191. self._exists = self.PAGE_INVALID
  192. return
  193. else:
  194. self._exists = self.PAGE_EXISTS
  195. self._fullurl = res["fullurl"]
  196. self._protection = res["protection"]
  197. try:
  198. self._token = res["edittoken"]
  199. except KeyError:
  200. pass
  201. else:
  202. self._starttimestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
  203. # We've determined the namespace and talkpage status in __init__()
  204. # based on the title, but now we can be sure:
  205. self._namespace = res["ns"]
  206. self._is_talkpage = self._namespace % 2 == 1 # talkpages have odd IDs
  207. # These last two fields will only be specified if the page exists:
  208. self._lastrevid = res.get("lastrevid")
  209. try:
  210. self._creator = res['revisions'][0]['user']
  211. except KeyError:
  212. pass
  213. def _load_content(self, result=None):
  214. """Load current page content from the API.
  215. If *result* is provided, we'll pretend that is the result of an API
  216. query and try to get content from that. Otherwise, we'll do an API
  217. query on our own.
  218. Don't call this directly, ever; use reload() followed by get() if you
  219. want to force content reloading.
  220. """
  221. if not result:
  222. query = self.site.api_query
  223. result = query(action="query", prop="revisions", rvlimit=1,
  224. rvprop="content|timestamp", titles=self._title)
  225. res = result["query"]["pages"].values()[0]
  226. try:
  227. self._content = res["revisions"][0]["*"]
  228. self._basetimestamp = res["revisions"][0]["timestamp"]
  229. except KeyError:
  230. # This can only happen if the page was deleted since we last called
  231. # self._load_attributes(). In that case, some of our attributes are
  232. # outdated, so force another self._load_attributes():
  233. self._load_attributes()
  234. self._assert_existence()
  235. def _edit(self, params=None, text=None, summary=None, minor=None, bot=None,
  236. force=None, section=None, captcha_id=None, captcha_word=None,
  237. tries=0):
  238. """Edit the page!
  239. If *params* is given, we'll use it as our API query parameters.
  240. Otherwise, we'll build params using the given kwargs via
  241. _build_edit_params().
  242. We'll then try to do the API query, and catch any errors the API raises
  243. in _handle_edit_errors(). We'll then throw these back as subclasses of
  244. EditError.
  245. """
  246. # Try to get our edit token, and die if we can't:
  247. if not self._token:
  248. self._load_attributes()
  249. if not self._token:
  250. e = "You don't have permission to edit this page."
  251. raise exceptions.PermissionsError(e)
  252. # Weed out invalid pages before we get too far:
  253. self._assert_validity()
  254. # Build our API query string:
  255. if not params:
  256. params = self._build_edit_params(text, summary, minor, bot, force,
  257. section, captcha_id, captcha_word)
  258. else: # Make sure we have the right token:
  259. params["token"] = self._token
  260. # Try the API query, catching most errors with our handler:
  261. try:
  262. result = self.site.api_query(**params)
  263. except exceptions.APIError as error:
  264. if not hasattr(error, "code"):
  265. raise # We can only handle errors with a code attribute
  266. result = self._handle_edit_errors(error, params, tries)
  267. # If everything was successful, reset invalidated attributes:
  268. if result["edit"]["result"] == "Success":
  269. self._content = None
  270. self._basetimestamp = None
  271. self._exists = self.PAGE_UNKNOWN
  272. return
  273. # If we're here, then the edit failed. If it's because of AssertEdit,
  274. # handle that. Otherwise, die - something odd is going on:
  275. try:
  276. assertion = result["edit"]["assert"]
  277. except KeyError:
  278. raise exceptions.EditError(result["edit"])
  279. self._handle_assert_edit(assertion, params, tries)
  280. def _build_edit_params(self, text, summary, minor, bot, force, section,
  281. captcha_id, captcha_word):
  282. """Given some keyword arguments, build an API edit query string."""
  283. unitxt = text.encode("utf8") if isinstance(text, unicode) else text
  284. hashed = md5(unitxt).hexdigest() # Checksum to ensure text is correct
  285. params = {"action": "edit", "title": self._title, "text": text,
  286. "token": self._token, "summary": summary, "md5": hashed}
  287. if section:
  288. params["section"] = section
  289. if captcha_id and captcha_word:
  290. params["captchaid"] = captcha_id
  291. params["captchaword"] = captcha_word
  292. if minor:
  293. params["minor"] = "true"
  294. else:
  295. params["notminor"] = "true"
  296. if bot:
  297. params["bot"] = "true"
  298. if not force:
  299. params["starttimestamp"] = self._starttimestamp
  300. if self._basetimestamp:
  301. params["basetimestamp"] = self._basetimestamp
  302. if self._exists == self.PAGE_MISSING:
  303. # Page does not exist; don't edit if it already exists:
  304. params["createonly"] = "true"
  305. else:
  306. params["recreate"] = "true"
  307. return params
  308. def _handle_edit_errors(self, error, params, tries):
  309. """If our edit fails due to some error, try to handle it.
  310. We'll either raise an appropriate exception (for example, if the page
  311. is protected), or we'll try to fix it (for example, if we can't edit
  312. due to being logged out, we'll try to log in).
  313. """
  314. if error.code in ["noedit", "cantcreate", "protectedtitle",
  315. "noimageredirect"]:
  316. raise exceptions.PermissionsError(error.info)
  317. elif error.code in ["noedit-anon", "cantcreate-anon",
  318. "noimageredirect-anon"]:
  319. if not all(self.site._login_info):
  320. # Insufficient login info:
  321. raise exceptions.PermissionsError(error.info)
  322. if tries == 0:
  323. # We have login info; try to login:
  324. self.site._login(self.site._login_info)
  325. self._token = None # Need a new token; old one is invalid now
  326. return self._edit(params=params, tries=1)
  327. else:
  328. # We already tried to log in and failed!
  329. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  330. raise exceptions.LoginError(e)
  331. elif error.code in ["editconflict", "pagedeleted", "articleexists"]:
  332. # These attributes are now invalidated:
  333. self._content = None
  334. self._basetimestamp = None
  335. self._exists = self.PAGE_UNKNOWN
  336. raise exceptions.EditConflictError(error.info)
  337. elif error.code in ["emptypage", "emptynewsection"]:
  338. raise exceptions.NoContentError(error.info)
  339. elif error.code == "contenttoobig":
  340. raise exceptions.ContentTooBigError(error.info)
  341. elif error.code == "spamdetected":
  342. raise exceptions.SpamDetectedError(error.info)
  343. elif error.code == "filtered":
  344. raise exceptions.FilteredError(error.info)
  345. raise exceptions.EditError(": ".join((error.code, error.info)))
  346. def _handle_assert_edit(self, assertion, params, tries):
  347. """If we can't edit due to a failed AssertEdit assertion, handle that.
  348. If the assertion was 'user' and we have valid login information, try to
  349. log in. Otherwise, raise PermissionsError with details.
  350. """
  351. if assertion == "user":
  352. if not all(self.site._login_info):
  353. # Insufficient login info:
  354. e = "AssertEdit: user assertion failed, and no login info was provided."
  355. raise exceptions.PermissionsError(e)
  356. if tries == 0:
  357. # We have login info; try to login:
  358. self.site._login(self.site._login_info)
  359. self._token = None # Need a new token; old one is invalid now
  360. return self._edit(params=params, tries=1)
  361. else:
  362. # We already tried to log in and failed!
  363. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  364. raise exceptions.LoginError(e)
  365. elif assertion == "bot":
  366. if not all(self.site._login_info):
  367. # Insufficient login info:
  368. e = "AssertEdit: bot assertion failed, and no login info was provided."
  369. raise exceptions.PermissionsError(e)
  370. if tries == 0:
  371. # Try to log in if we got logged out:
  372. self.site._login(self.site._login_info)
  373. self._token = None # Need a new token; old one is invalid now
  374. return self._edit(params=params, tries=1)
  375. else:
  376. # We already tried to log in, so we don't have a bot flag:
  377. e = "AssertEdit: bot assertion failed: we don't have a bot flag!"
  378. raise exceptions.PermissionsError(e)
  379. # Unknown assertion, maybe "true", "false", or "exists":
  380. e = "AssertEdit: assertion '{0}' failed.".format(assertion)
  381. raise exceptions.PermissionsError(e)
  382. @property
  383. def site(self):
  384. """The page's corresponding Site object."""
  385. return self._site
  386. @property
  387. def title(self):
  388. """The page's title, or "pagename".
  389. This won't do any API queries on its own. Any other attributes or
  390. methods that do API queries will reload the title, however, like
  391. :py:attr:`exists` and :py:meth:`get`, potentially "normalizing" it or
  392. following redirects if :py:attr:`self._follow_redirects` is ``True``.
  393. """
  394. return self._title
  395. @property
  396. def exists(self):
  397. """Whether or not the page exists.
  398. This will be a number; its value does not matter, but it will equal
  399. one of :py:attr:`self.PAGE_INVALID <PAGE_INVALID>`,
  400. :py:attr:`self.PAGE_MISSING <PAGE_MISSING>`, or
  401. :py:attr:`self.PAGE_EXISTS <PAGE_EXISTS>`.
  402. Makes an API query only if we haven't already made one.
  403. """
  404. if self._exists == self.PAGE_UNKNOWN:
  405. self._load()
  406. return self._exists
  407. @property
  408. def pageid(self):
  409. """An integer ID representing the page.
  410. Makes an API query only if we haven't already made one and the *pageid*
  411. parameter to :py:meth:`__init__` was left as ``None``, which should be
  412. true for all cases except when pages are returned by an SQL generator
  413. (like :py:meth:`category.get_members()
  414. <earwigbot.wiki.category.Category.get_members>`).
  415. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  416. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  417. invalid or the page does not exist, respectively.
  418. """
  419. if self._pageid:
  420. return self._pageid
  421. if self._exists == self.PAGE_UNKNOWN:
  422. self._load()
  423. self._assert_existence() # Missing pages do not have IDs
  424. return self._pageid
  425. @property
  426. def url(self):
  427. """The page's URL.
  428. Like :py:meth:`title`, this won't do any API queries on its own. If the
  429. API was never queried for this page, we will attempt to determine the
  430. URL ourselves based on the title.
  431. """
  432. if self._fullurl:
  433. return self._fullurl
  434. else:
  435. encoded = self._title.encode("utf8").replace(" ", "_")
  436. slug = quote(encoded, safe="/:").decode("utf8")
  437. path = self.site._article_path.replace("$1", slug)
  438. return u"".join((self.site.url, path))
  439. @property
  440. def namespace(self):
  441. """The page's namespace ID (an integer).
  442. Like :py:meth:`title`, this won't do any API queries on its own. If the
  443. API was never queried for this page, we will attempt to determine the
  444. namespace ourselves based on the title.
  445. """
  446. return self._namespace
  447. @property
  448. def protection(self):
  449. """The page's current protection status.
  450. Makes an API query only if we haven't already made one.
  451. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` if the page
  452. name is invalid. Won't raise an error if the page is missing because
  453. those can still be create-protected.
  454. """
  455. if self._exists == self.PAGE_UNKNOWN:
  456. self._load()
  457. self._assert_validity() # Invalid pages cannot be protected
  458. return self._protection
  459. @property
  460. def is_talkpage(self):
  461. """``True`` if the page is a talkpage, otherwise ``False``.
  462. Like :py:meth:`title`, this won't do any API queries on its own. If the
  463. API was never queried for this page, we will attempt to determine
  464. whether it is a talkpage ourselves based on its namespace.
  465. """
  466. return self._is_talkpage
  467. @property
  468. def is_redirect(self):
  469. """``True`` if the page is a redirect, otherwise ``False``.
  470. Makes an API query only if we haven't already made one.
  471. We will return ``False`` even if the page does not exist or is invalid.
  472. """
  473. if self._exists == self.PAGE_UNKNOWN:
  474. self._load()
  475. return self._is_redirect
  476. def reload(self):
  477. """Forcibly reload the page's attributes.
  478. Emphasis on *reload*: this is only necessary if there is reason to
  479. believe they have changed.
  480. """
  481. self._load()
  482. if self._content is not None:
  483. # Only reload content if it has already been loaded:
  484. self._load_content()
  485. def toggle_talk(self, follow_redirects=None):
  486. """Return a content page's talk page, or vice versa.
  487. The title of the new page is determined by namespace logic, not API
  488. queries. We won't make any API queries on our own.
  489. If *follow_redirects* is anything other than ``None`` (the default), it
  490. will be passed to the new :py:class:`~earwigbot.wiki.page.Page`
  491. object's :py:meth:`__init__`. Otherwise, we'll use the value passed to
  492. our own :py:meth:`__init__`.
  493. Will raise :py:exc:`~earwigbot.exceptions.InvalidPageError` if we try
  494. to get the talk page of a special page (in the ``Special:`` or
  495. ``Media:`` namespaces), but we won't raise an exception if our page is
  496. otherwise missing or invalid.
  497. """
  498. if self._namespace < 0:
  499. ns = self.site.namespace_id_to_name(self._namespace)
  500. e = u"Pages in the {0} namespace can't have talk pages.".format(ns)
  501. raise exceptions.InvalidPageError(e)
  502. if self._is_talkpage:
  503. new_ns = self._namespace - 1
  504. else:
  505. new_ns = self._namespace + 1
  506. try:
  507. body = self._title.split(":", 1)[1]
  508. except IndexError:
  509. body = self._title
  510. new_prefix = self.site.namespace_id_to_name(new_ns)
  511. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  512. # but unnecessary), just do "Title":
  513. if new_prefix:
  514. new_title = u":".join((new_prefix, body))
  515. else:
  516. new_title = body
  517. if follow_redirects is None:
  518. follow_redirects = self._follow_redirects
  519. return Page(self.site, new_title, follow_redirects)
  520. def get(self):
  521. """Return page content, which is cached if you try to call get again.
  522. Raises InvalidPageError or PageNotFoundError if the page name is
  523. invalid or the page does not exist, respectively.
  524. """
  525. if self._exists == self.PAGE_UNKNOWN:
  526. # Kill two birds with one stone by doing an API query for both our
  527. # attributes and our page content:
  528. query = self.site.api_query
  529. result = query(action="query", rvlimit=1, titles=self._title,
  530. prop="info|revisions", inprop="protection|url",
  531. intoken="edit", rvprop="content|timestamp")
  532. self._load_attributes(result=result)
  533. self._assert_existence()
  534. self._load_content(result=result)
  535. # Follow redirects if we're told to:
  536. if self._keep_following and self._is_redirect:
  537. self._title = self.get_redirect_target()
  538. self._keep_following = False # Don't follow double redirects
  539. self._exists = self.PAGE_UNKNOWN # Force another API query
  540. self.get()
  541. return self._content
  542. # Make sure we're dealing with a real page here. This may be outdated
  543. # if the page was deleted since we last called self._load_attributes(),
  544. # but self._load_content() can handle that:
  545. self._assert_existence()
  546. if self._content is None:
  547. self._load_content()
  548. return self._content
  549. def get_redirect_target(self):
  550. """If the page is a redirect, return its destination.
  551. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  552. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  553. invalid or the page does not exist, respectively. Raises
  554. :py:exc:`~earwigbot.exceptions.RedirectError` if the page is not a
  555. redirect.
  556. """
  557. re_redirect = "^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  558. content = self.get()
  559. try:
  560. return re.findall(re_redirect, content, flags=re.I)[0]
  561. except IndexError:
  562. e = "The page does not appear to have a redirect target."
  563. raise exceptions.RedirectError(e)
  564. def get_creator(self):
  565. """Return the User object for the first person to edit the page.
  566. Makes an API query only if we haven't already made one. Normally, we
  567. can get the creator along with everything else (except content) in
  568. :py:meth:`_load_attributes`. However, due to a limitation in the API
  569. (can't get the editor of one revision and the content of another at
  570. both ends of the history), if our other attributes were only loaded
  571. through :py:meth:`get`, we'll have to do another API query.
  572. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  573. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  574. invalid or the page does not exist, respectively.
  575. """
  576. if self._exists == self.PAGE_UNKNOWN:
  577. self._load()
  578. self._assert_existence()
  579. if not self._creator:
  580. self._load()
  581. self._assert_existence()
  582. return self.site.get_user(self._creator)
  583. def parse(self):
  584. """Parse the page content for templates, links, etc.
  585. Actual parsing is handled by :py:mod:`mwparserfromhell`. Raises
  586. :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  587. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  588. invalid or the page does not exist, respectively.
  589. """
  590. return mwparserfromhell.parse(self.get())
  591. def edit(self, text, summary, minor=False, bot=True, force=False):
  592. """Replace the page's content or creates a new page.
  593. *text* is the new page content, with *summary* as the edit summary.
  594. If *minor* is ``True``, the edit will be marked as minor. If *bot* is
  595. ``True``, the edit will be marked as a bot edit, but only if we
  596. actually have a bot flag.
  597. Use *force* to push the new content even if there's an edit conflict or
  598. the page was deleted/recreated between getting our edit token and
  599. editing our page. Be careful with this!
  600. """
  601. self._edit(text=text, summary=summary, minor=minor, bot=bot,
  602. force=force)
  603. def add_section(self, text, title, minor=False, bot=True, force=False):
  604. """Add a new section to the bottom of the page.
  605. The arguments for this are the same as those for :py:meth:`edit`, but
  606. instead of providing a summary, you provide a section title. Likewise,
  607. raised exceptions are the same as :py:meth:`edit`'s.
  608. This should create the page if it does not already exist, with just the
  609. new section as content.
  610. """
  611. self._edit(text=text, summary=title, minor=minor, bot=bot, force=force,
  612. section="new")
  613. def check_exclusion(self, username=None, optouts=None):
  614. """Check whether or not we are allowed to edit the page.
  615. Return ``True`` if we *are* allowed to edit this page, and ``False`` if
  616. we aren't.
  617. *username* is used to determine whether we are part of a specific list
  618. of allowed or disallowed bots (e.g. ``{{bots|allow=EarwigBot}}`` or
  619. ``{{bots|deny=FooBot,EarwigBot}}``). It's ``None`` by default, which
  620. will swipe our username from :py:meth:`site.get_user()
  621. <earwigbot.wiki.site.Site.get_user>`.\
  622. :py:attr:`~earwigbot.wiki.user.User.name`.
  623. *optouts* is a list of messages to consider this check as part of for
  624. the purpose of opt-out; it defaults to ``None``, which ignores the
  625. parameter completely. For example, if *optouts* is ``["nolicense"]``,
  626. we'll return ``False`` on ``{{bots|optout=nolicense}}`` or
  627. ``{{bots|optout=all}}``, but `True` on
  628. ``{{bots|optout=orfud,norationale,replaceable}}``.
  629. """
  630. def parse_param(template, param):
  631. value = template.get(param).value
  632. return [item.strip().lower() for item in value.split(",")]
  633. if not username:
  634. username = self.site.get_user().name
  635. # Lowercase everything:
  636. username = username.lower()
  637. optouts = [optout.lower() for optout in optouts] if optouts else []
  638. r_bots = "\{\{\s*(no)?bots\s*(\||\}\})"
  639. filter = self.parse().ifilter_templates(recursive=True, matches=r_bots)
  640. for template in filter:
  641. if template.has_param("deny"):
  642. denies = parse_param(template, "deny")
  643. if "all" in denies or username in denies:
  644. return False
  645. if template.has_param("allow"):
  646. allows = parse_param(template, "allow")
  647. if "all" in allows or username in allows:
  648. continue
  649. if optouts and template.has_param("optout"):
  650. tasks = parse_param(template, "optout")
  651. matches = [optout in tasks for optout in optouts]
  652. if "all" in tasks or any(matches):
  653. return False
  654. if template.name.strip().lower() == "nobots":
  655. return False
  656. return True