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.

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