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.

797 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 == "blocked":
  340. if tries > 0 or not all(self.site._login_info):
  341. raise exceptions.PermissionsError(error.info)
  342. else:
  343. # Perhaps we are blocked from being logged-out? Try to log in:
  344. self.site._login(self.site._login_info)
  345. self._token = None # Need a new token; old one is invalid now
  346. return self._edit(params=params, tries=1)
  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. if not all(self.site._login_info):
  375. # Insufficient login info:
  376. e = "AssertEdit: bot assertion failed, and no login info was provided."
  377. raise exceptions.PermissionsError(e)
  378. if tries == 0:
  379. # Try to log in if we got logged out:
  380. self.site._login(self.site._login_info)
  381. self._token = None # Need a new token; old one is invalid now
  382. return self._edit(params=params, tries=1)
  383. else:
  384. # We already tried to log in, so we don't have a bot flag:
  385. e = "AssertEdit: bot assertion failed: we don't have a bot flag!"
  386. raise exceptions.PermissionsError(e)
  387. # Unknown assertion, maybe "true", "false", or "exists":
  388. e = "AssertEdit: assertion '{0}' failed.".format(assertion)
  389. raise exceptions.PermissionsError(e)
  390. @property
  391. def site(self):
  392. """The page's corresponding Site object."""
  393. return self._site
  394. @property
  395. def title(self):
  396. """The page's title, or "pagename".
  397. This won't do any API queries on its own. Any other attributes or
  398. methods that do API queries will reload the title, however, like
  399. :py:attr:`exists` and :py:meth:`get`, potentially "normalizing" it or
  400. following redirects if :py:attr:`self._follow_redirects` is ``True``.
  401. """
  402. return self._title
  403. @property
  404. def exists(self):
  405. """Whether or not the page exists.
  406. This will be a number; its value does not matter, but it will equal
  407. one of :py:attr:`self.PAGE_INVALID <PAGE_INVALID>`,
  408. :py:attr:`self.PAGE_MISSING <PAGE_MISSING>`, or
  409. :py:attr:`self.PAGE_EXISTS <PAGE_EXISTS>`.
  410. Makes an API query only if we haven't already made one.
  411. """
  412. if self._exists == self.PAGE_UNKNOWN:
  413. self._load()
  414. return self._exists
  415. @property
  416. def pageid(self):
  417. """An integer ID representing the page.
  418. Makes an API query only if we haven't already made one and the *pageid*
  419. parameter to :py:meth:`__init__` was left as ``None``, which should be
  420. true for all cases except when pages are returned by an SQL generator
  421. (like :py:meth:`category.get_members()
  422. <earwigbot.wiki.category.Category.get_members>`).
  423. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  424. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  425. invalid or the page does not exist, respectively.
  426. """
  427. if self._pageid:
  428. return self._pageid
  429. if self._exists == self.PAGE_UNKNOWN:
  430. self._load()
  431. self._assert_existence() # Missing pages do not have IDs
  432. return self._pageid
  433. @property
  434. def url(self):
  435. """The page's URL.
  436. Like :py:meth:`title`, this won't do any API queries on its own. If the
  437. API was never queried for this page, we will attempt to determine the
  438. URL ourselves based on the title.
  439. """
  440. if self._fullurl:
  441. return self._fullurl
  442. else:
  443. encoded = self._title.encode("utf8").replace(" ", "_")
  444. slug = quote(encoded, safe="/:").decode("utf8")
  445. path = self.site._article_path.replace("$1", slug)
  446. return u"".join((self.site.url, path))
  447. @property
  448. def namespace(self):
  449. """The page's namespace ID (an integer).
  450. Like :py:meth:`title`, this won't do any API queries on its own. If the
  451. API was never queried for this page, we will attempt to determine the
  452. namespace ourselves based on the title.
  453. """
  454. return self._namespace
  455. @property
  456. def protection(self):
  457. """The page's current protection status.
  458. Makes an API query only if we haven't already made one.
  459. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` if the page
  460. name is invalid. Won't raise an error if the page is missing because
  461. those can still be create-protected.
  462. """
  463. if self._exists == self.PAGE_UNKNOWN:
  464. self._load()
  465. self._assert_validity() # Invalid pages cannot be protected
  466. return self._protection
  467. @property
  468. def is_talkpage(self):
  469. """``True`` if the page is a talkpage, otherwise ``False``.
  470. Like :py:meth:`title`, this won't do any API queries on its own. If the
  471. API was never queried for this page, we will attempt to determine
  472. whether it is a talkpage ourselves based on its namespace.
  473. """
  474. return self._is_talkpage
  475. @property
  476. def is_redirect(self):
  477. """``True`` if the page is a redirect, otherwise ``False``.
  478. Makes an API query only if we haven't already made one.
  479. We will return ``False`` even if the page does not exist or is invalid.
  480. """
  481. if self._exists == self.PAGE_UNKNOWN:
  482. self._load()
  483. return self._is_redirect
  484. def reload(self):
  485. """Forcibly reload the page's attributes.
  486. Emphasis on *reload*: this is only necessary if there is reason to
  487. believe they have changed.
  488. """
  489. self._load()
  490. if self._content is not None:
  491. # Only reload content if it has already been loaded:
  492. self._load_content()
  493. def toggle_talk(self, follow_redirects=None):
  494. """Return a content page's talk page, or vice versa.
  495. The title of the new page is determined by namespace logic, not API
  496. queries. We won't make any API queries on our own.
  497. If *follow_redirects* is anything other than ``None`` (the default), it
  498. will be passed to the new :py:class:`~earwigbot.wiki.page.Page`
  499. object's :py:meth:`__init__`. Otherwise, we'll use the value passed to
  500. our own :py:meth:`__init__`.
  501. Will raise :py:exc:`~earwigbot.exceptions.InvalidPageError` if we try
  502. to get the talk page of a special page (in the ``Special:`` or
  503. ``Media:`` namespaces), but we won't raise an exception if our page is
  504. otherwise missing or invalid.
  505. """
  506. if self._namespace < 0:
  507. ns = self.site.namespace_id_to_name(self._namespace)
  508. e = u"Pages in the {0} namespace can't have talk pages.".format(ns)
  509. raise exceptions.InvalidPageError(e)
  510. if self._is_talkpage:
  511. new_ns = self._namespace - 1
  512. else:
  513. new_ns = self._namespace + 1
  514. try:
  515. body = self._title.split(":", 1)[1]
  516. except IndexError:
  517. body = self._title
  518. new_prefix = self.site.namespace_id_to_name(new_ns)
  519. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  520. # but unnecessary), just do "Title":
  521. if new_prefix:
  522. new_title = u":".join((new_prefix, body))
  523. else:
  524. new_title = body
  525. if follow_redirects is None:
  526. follow_redirects = self._follow_redirects
  527. return Page(self.site, new_title, follow_redirects)
  528. def get(self):
  529. """Return page content, which is cached if you try to call get again.
  530. Raises InvalidPageError or PageNotFoundError if the page name is
  531. invalid or the page does not exist, respectively.
  532. """
  533. if self._exists == self.PAGE_UNKNOWN:
  534. # Kill two birds with one stone by doing an API query for both our
  535. # attributes and our page content:
  536. query = self.site.api_query
  537. result = query(action="query", rvlimit=1, titles=self._title,
  538. prop="info|revisions", inprop="protection|url",
  539. intoken="edit", rvprop="content|timestamp")
  540. self._load_attributes(result=result)
  541. self._assert_existence()
  542. self._load_content(result=result)
  543. # Follow redirects if we're told to:
  544. if self._keep_following and self._is_redirect:
  545. self._title = self.get_redirect_target()
  546. self._keep_following = False # Don't follow double redirects
  547. self._exists = self.PAGE_UNKNOWN # Force another API query
  548. self.get()
  549. return self._content
  550. # Make sure we're dealing with a real page here. This may be outdated
  551. # if the page was deleted since we last called self._load_attributes(),
  552. # but self._load_content() can handle that:
  553. self._assert_existence()
  554. if self._content is None:
  555. self._load_content()
  556. return self._content
  557. def get_redirect_target(self):
  558. """If the page is a redirect, return its destination.
  559. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  560. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  561. invalid or the page does not exist, respectively. Raises
  562. :py:exc:`~earwigbot.exceptions.RedirectError` if the page is not a
  563. redirect.
  564. """
  565. re_redirect = "^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  566. content = self.get()
  567. try:
  568. return re.findall(re_redirect, content, flags=re.I)[0]
  569. except IndexError:
  570. e = "The page does not appear to have a redirect target."
  571. raise exceptions.RedirectError(e)
  572. def get_creator(self):
  573. """Return the User object for the first person to edit the page.
  574. Makes an API query only if we haven't already made one. Normally, we
  575. can get the creator along with everything else (except content) in
  576. :py:meth:`_load_attributes`. However, due to a limitation in the API
  577. (can't get the editor of one revision and the content of another at
  578. both ends of the history), if our other attributes were only loaded
  579. through :py:meth:`get`, we'll have to do another API query.
  580. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  581. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  582. invalid or the page does not exist, respectively.
  583. """
  584. if self._exists == self.PAGE_UNKNOWN:
  585. self._load()
  586. self._assert_existence()
  587. if not self._creator:
  588. self._load()
  589. self._assert_existence()
  590. return self.site.get_user(self._creator)
  591. def parse(self):
  592. """Parse the page content for templates, links, etc.
  593. Actual parsing is handled by :py:mod:`mwparserfromhell`. Raises
  594. :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  595. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  596. invalid or the page does not exist, respectively.
  597. """
  598. return mwparserfromhell.parse(self.get())
  599. def edit(self, text, summary, minor=False, bot=True, force=False):
  600. """Replace the page's content or creates a new page.
  601. *text* is the new page content, with *summary* as the edit summary.
  602. If *minor* is ``True``, the edit will be marked as minor. If *bot* is
  603. ``True``, the edit will be marked as a bot edit, but only if we
  604. actually have a bot flag.
  605. Use *force* to push the new content even if there's an edit conflict or
  606. the page was deleted/recreated between getting our edit token and
  607. editing our page. Be careful with this!
  608. """
  609. self._edit(text=text, summary=summary, minor=minor, bot=bot,
  610. force=force)
  611. def add_section(self, text, title, minor=False, bot=True, force=False):
  612. """Add a new section to the bottom of the page.
  613. The arguments for this are the same as those for :py:meth:`edit`, but
  614. instead of providing a summary, you provide a section title. Likewise,
  615. raised exceptions are the same as :py:meth:`edit`'s.
  616. This should create the page if it does not already exist, with just the
  617. new section as content.
  618. """
  619. self._edit(text=text, summary=title, minor=minor, bot=bot, force=force,
  620. section="new")
  621. def check_exclusion(self, username=None, optouts=None):
  622. """Check whether or not we are allowed to edit the page.
  623. Return ``True`` if we *are* allowed to edit this page, and ``False`` if
  624. we aren't.
  625. *username* is used to determine whether we are part of a specific list
  626. of allowed or disallowed bots (e.g. ``{{bots|allow=EarwigBot}}`` or
  627. ``{{bots|deny=FooBot,EarwigBot}}``). It's ``None`` by default, which
  628. will swipe our username from :py:meth:`site.get_user()
  629. <earwigbot.wiki.site.Site.get_user>`.\
  630. :py:attr:`~earwigbot.wiki.user.User.name`.
  631. *optouts* is a list of messages to consider this check as part of for
  632. the purpose of opt-out; it defaults to ``None``, which ignores the
  633. parameter completely. For example, if *optouts* is ``["nolicense"]``,
  634. we'll return ``False`` on ``{{bots|optout=nolicense}}`` or
  635. ``{{bots|optout=all}}``, but `True` on
  636. ``{{bots|optout=orfud,norationale,replaceable}}``.
  637. """
  638. def parse_param(template, param):
  639. value = template.get(param).value
  640. return [item.strip().lower() for item in value.split(",")]
  641. if not username:
  642. username = self.site.get_user().name
  643. # Lowercase everything:
  644. username = username.lower()
  645. optouts = [optout.lower() for optout in optouts] if optouts else []
  646. r_bots = "\{\{\s*(no)?bots\s*(\||\}\})"
  647. filter = self.parse().ifilter_templates(recursive=True, matches=r_bots)
  648. for template in filter:
  649. if template.has_param("deny"):
  650. denies = parse_param(template, "deny")
  651. if "all" in denies or username in denies:
  652. return False
  653. if template.has_param("allow"):
  654. allows = parse_param(template, "allow")
  655. if "all" in allows or username in allows:
  656. continue
  657. if optouts and template.has_param("optout"):
  658. tasks = parse_param(template, "optout")
  659. matches = [optout in tasks for optout in optouts]
  660. if "all" in tasks or any(matches):
  661. return False
  662. if template.name.strip().lower() == "nobots":
  663. return False
  664. return True