A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

779 líneas
31 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. import re
  24. from time import gmtime, strftime
  25. from urllib import quote
  26. try:
  27. import mwparserfromhell
  28. except ImportError:
  29. mwparserfromhell = None
  30. from earwigbot import exceptions
  31. from earwigbot.wiki.copyright import CopyrightMixIn
  32. __all__ = ["Page"]
  33. class Page(CopyrightMixIn):
  34. """
  35. **EarwigBot: Wiki Toolset: Page**
  36. Represents a page on a given :py:class:`~earwigbot.wiki.site.Site`. Has
  37. methods for getting information about the page, getting page content, and
  38. so on. :py:class:`~earwigbot.wiki.category.Category` is a subclass of
  39. :py:class:`Page` with additional methods.
  40. *Attributes:*
  41. - :py:attr:`site`: the page's corresponding Site object
  42. - :py:attr:`title`: the page's title, or pagename
  43. - :py:attr:`exists`: whether or not the page exists
  44. - :py:attr:`pageid`: an integer ID representing the page
  45. - :py:attr:`url`: the page's URL
  46. - :py:attr:`namespace`: the page's namespace as an integer
  47. - :py:attr:`protection`: the page's current protection status
  48. - :py:attr:`is_talkpage`: ``True`` if this is a talkpage, else ``False``
  49. - :py:attr:`is_redirect`: ``True`` if this is a redirect, else ``False``
  50. *Public methods:*
  51. - :py:meth:`reload`: forcibly reloads the page's attributes
  52. - :py:meth:`toggle_talk`: returns a content page's talk page, or vice versa
  53. - :py:meth:`get`: returns the page's content
  54. - :py:meth:`get_redirect_target`: returns the page's destination if it is a
  55. redirect
  56. - :py:meth:`get_creator`: returns a User object representing the first
  57. person to edit the page
  58. - :py:meth:`parse`: parses the page content for templates, links, etc
  59. - :py:meth:`edit`: replaces the page's content or creates a new page
  60. - :py:meth:`add_section`: adds a new section at the bottom of the page
  61. - :py:meth:`check_exclusion`: checks whether or not we are allowed to edit
  62. the page, per ``{{bots}}``/``{{nobots}}``
  63. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_check`:
  64. checks the page for copyright violations
  65. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_compare`:
  66. checks the page like :py:meth:`copyvio_check`, but against a specific URL
  67. """
  68. PAGE_UNKNOWN = 0
  69. PAGE_INVALID = 1
  70. PAGE_MISSING = 2
  71. PAGE_EXISTS = 3
  72. def __init__(self, site, title, follow_redirects=False, pageid=None):
  73. """Constructor for new Page instances.
  74. Takes four arguments: a Site object, the Page's title (or pagename),
  75. whether or not to follow redirects (optional, defaults to False), and
  76. a page ID to supplement the title (optional, defaults to None - i.e.,
  77. we will have to query the API to get it).
  78. As with User, site.get_page() is preferred.
  79. __init__() will not do any API queries, but it will use basic namespace
  80. logic to determine our namespace ID and if we are a talkpage.
  81. """
  82. super(Page, self).__init__(site)
  83. self._site = site
  84. self._title = title.strip()
  85. self._follow_redirects = self._keep_following = follow_redirects
  86. self._pageid = pageid
  87. self._exists = self.PAGE_UNKNOWN
  88. self._is_redirect = None
  89. self._lastrevid = None
  90. self._protection = None
  91. self._fullurl = None
  92. self._content = None
  93. self._creator = None
  94. # Attributes used for editing/deleting/protecting/etc:
  95. self._token = None
  96. self._basetimestamp = None
  97. self._starttimestamp = None
  98. # Try to determine the page's namespace using our site's namespace
  99. # converter:
  100. prefix = self._title.split(":", 1)[0]
  101. if prefix != title: # ignore a page that's titled "Category" or "User"
  102. try:
  103. self._namespace = self.site.namespace_name_to_id(prefix)
  104. except exceptions.NamespaceNotFoundError:
  105. self._namespace = 0
  106. else:
  107. self._namespace = 0
  108. # Is this a talkpage? Talkpages have odd IDs, while content pages have
  109. # even IDs, excluding the "special" namespaces:
  110. if self._namespace < 0:
  111. self._is_talkpage = False
  112. else:
  113. self._is_talkpage = self._namespace % 2 == 1
  114. def __repr__(self):
  115. """Return the canonical string representation of the Page."""
  116. res = "Page(title={0!r}, follow_redirects={1!r}, site={2!r})"
  117. return res.format(self._title, self._follow_redirects, self._site)
  118. def __str__(self):
  119. """Return a nice string representation of the Page."""
  120. return '<Page "{0}" of {1}>'.format(self.title, str(self.site))
  121. def _assert_validity(self):
  122. """Used to ensure that our page's title is valid.
  123. If this method is called when our page is not valid (and after
  124. _load_attributes() has been called), InvalidPageError will be raised.
  125. Note that validity != existence. If a page's title is invalid (e.g, it
  126. contains "[") it will always be invalid, and cannot be edited.
  127. """
  128. if self._exists == self.PAGE_INVALID:
  129. e = u"Page '{0}' is invalid.".format(self._title)
  130. raise exceptions.InvalidPageError(e)
  131. def _assert_existence(self):
  132. """Used to ensure that our page exists.
  133. If this method is called when our page doesn't exist (and after
  134. _load_attributes() has been called), PageNotFoundError will be raised.
  135. It will also call _assert_validity() beforehand.
  136. """
  137. self._assert_validity()
  138. if self._exists == self.PAGE_MISSING:
  139. e = u"Page '{0}' does not exist.".format(self._title)
  140. raise exceptions.PageNotFoundError(e)
  141. def _load(self):
  142. """Call _load_attributes() and follows redirects if we're supposed to.
  143. This method will only follow redirects if follow_redirects=True was
  144. passed to __init__() (perhaps indirectly passed by site.get_page()).
  145. It avoids the API's &redirects param in favor of manual following,
  146. so we can act more realistically (we don't follow double redirects, and
  147. circular redirects don't break us).
  148. This will raise RedirectError if we have a problem following, but that
  149. is a bug and should NOT happen.
  150. If we're following a redirect, this will make a grand total of three
  151. API queries. It's a lot, but each one is quite small.
  152. """
  153. self._load_attributes()
  154. if self._keep_following and self._is_redirect:
  155. self._title = self.get_redirect_target()
  156. self._keep_following = False # don't follow double redirects
  157. self._content = None # reset the content we just loaded
  158. self._load_attributes()
  159. def _load_attributes(self, result=None):
  160. """Load various data from the API in a single query.
  161. Loads self._title, ._exists, ._is_redirect, ._pageid, ._fullurl,
  162. ._protection, ._namespace, ._is_talkpage, ._creator, ._lastrevid,
  163. ._token, and ._starttimestamp using the API. It will do a query of
  164. its own unless *result* is provided, in which case we'll pretend
  165. *result* is what the query returned.
  166. Assuming the API is sound, this should not raise any exceptions.
  167. """
  168. if not result:
  169. query = self.site.api_query
  170. result = query(action="query", rvprop="user", intoken="edit",
  171. prop="info|revisions", rvlimit=1, rvdir="newer",
  172. titles=self._title, inprop="protection|url")
  173. res = result["query"]["pages"].values()[0]
  174. # Normalize our pagename/title thing:
  175. self._title = res["title"]
  176. try:
  177. res["redirect"]
  178. except KeyError:
  179. self._is_redirect = False
  180. else:
  181. self._is_redirect = True
  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. hashed = md5(text).hexdigest() # Checksum to ensure text is correct
  284. params = {"action": "edit", "title": self._title, "text": text,
  285. "token": self._token, "summary": summary, "md5": hashed}
  286. if section:
  287. params["section"] = section
  288. if captcha_id and captcha_word:
  289. params["captchaid"] = captcha_id
  290. params["captchaword"] = captcha_word
  291. if minor:
  292. params["minor"] = "true"
  293. else:
  294. params["notminor"] = "true"
  295. if bot:
  296. params["bot"] = "true"
  297. if not force:
  298. params["starttimestamp"] = self._starttimestamp
  299. if self._basetimestamp:
  300. params["basetimestamp"] = self._basetimestamp
  301. if self._exists == self.PAGE_MISSING:
  302. # Page does not exist; don't edit if it already exists:
  303. params["createonly"] = "true"
  304. else:
  305. params["recreate"] = "true"
  306. return params
  307. def _handle_edit_errors(self, error, params, tries):
  308. """If our edit fails due to some error, try to handle it.
  309. We'll either raise an appropriate exception (for example, if the page
  310. is protected), or we'll try to fix it (for example, if we can't edit
  311. due to being logged out, we'll try to log in).
  312. """
  313. if error.code in ["noedit", "cantcreate", "protectedtitle",
  314. "noimageredirect"]:
  315. raise exceptions.PermissionsError(error.info)
  316. elif error.code in ["noedit-anon", "cantcreate-anon",
  317. "noimageredirect-anon"]:
  318. if not all(self.site._login_info):
  319. # Insufficient login info:
  320. raise exceptions.PermissionsError(error.info)
  321. if tries == 0:
  322. # We have login info; try to login:
  323. self.site._login(self.site._login_info)
  324. self._token = None # Need a new token; old one is invalid now
  325. return self._edit(params=params, tries=1)
  326. else:
  327. # We already tried to log in and failed!
  328. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  329. raise exceptions.LoginError(e)
  330. elif error.code in ["editconflict", "pagedeleted", "articleexists"]:
  331. # These attributes are now invalidated:
  332. self._content = None
  333. self._basetimestamp = None
  334. self._exists = self.PAGE_UNKNOWN
  335. raise exceptions.EditConflictError(error.info)
  336. elif error.code in ["emptypage", "emptynewsection"]:
  337. raise exceptions.NoContentError(error.info)
  338. elif error.code == "contenttoobig":
  339. raise exceptions.ContentTooBigError(error.info)
  340. elif error.code == "spamdetected":
  341. raise exceptions.SpamDetectedError(error.info)
  342. elif error.code == "filtered":
  343. raise exceptions.FilteredError(error.info)
  344. raise exceptions.EditError(": ".join((error.code, error.info)))
  345. def _handle_assert_edit(self, assertion, params, tries):
  346. """If we can't edit due to a failed AssertEdit assertion, handle that.
  347. If the assertion was 'user' and we have valid login information, try to
  348. log in. Otherwise, raise PermissionsError with details.
  349. """
  350. if assertion == "user":
  351. if not all(self.site._login_info):
  352. # Insufficient login info:
  353. e = "AssertEdit: user assertion failed, and no login info was provided."
  354. raise exceptions.PermissionsError(e)
  355. if tries == 0:
  356. # We have login info; try to login:
  357. self.site._login(self.site._login_info)
  358. self._token = None # Need a new token; old one is invalid now
  359. return self._edit(params=params, tries=1)
  360. else:
  361. # We already tried to log in and failed!
  362. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  363. raise exceptions.LoginError(e)
  364. elif assertion == "bot":
  365. e = "AssertEdit: bot assertion failed; we don't have a bot flag!"
  366. raise exceptions.PermissionsError(e)
  367. # Unknown assertion, maybe "true", "false", or "exists":
  368. e = "AssertEdit: assertion '{0}' failed.".format(assertion)
  369. raise exceptions.PermissionsError(e)
  370. @property
  371. def site(self):
  372. """The page's corresponding Site object."""
  373. return self._site
  374. @property
  375. def title(self):
  376. """The page's title, or "pagename".
  377. This won't do any API queries on its own. Any other attributes or
  378. methods that do API queries will reload the title, however, like
  379. :py:attr:`exists` and :py:meth:`get`, potentially "normalizing" it or
  380. following redirects if :py:attr:`self._follow_redirects` is ``True``.
  381. """
  382. return self._title
  383. @property
  384. def exists(self):
  385. """Whether or not the page exists.
  386. This will be a number; its value does not matter, but it will equal
  387. one of :py:attr:`self.PAGE_INVALID <PAGE_INVALID>`,
  388. :py:attr:`self.PAGE_MISSING <PAGE_MISSING>`, or
  389. :py:attr:`self.PAGE_EXISTS <PAGE_EXISTS>`.
  390. Makes an API query only if we haven't already made one.
  391. """
  392. if self._exists == self.PAGE_UNKNOWN:
  393. self._load()
  394. return self._exists
  395. @property
  396. def pageid(self):
  397. """An integer ID representing the page.
  398. Makes an API query only if we haven't already made one and the *pageid*
  399. parameter to :py:meth:`__init__` was left as ``None``, which should be
  400. true for all cases except when pages are returned by an SQL generator
  401. (like :py:meth:`category.get_members()
  402. <earwigbot.wiki.category.Category.get_members>`).
  403. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  404. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  405. invalid or the page does not exist, respectively.
  406. """
  407. if self._pageid:
  408. return self._pageid
  409. if self._exists == self.PAGE_UNKNOWN:
  410. self._load()
  411. self._assert_existence() # Missing pages do not have IDs
  412. return self._pageid
  413. @property
  414. def url(self):
  415. """The page's URL.
  416. Like :py:meth:`title`, this won't do any API queries on its own. If the
  417. API was never queried for this page, we will attempt to determine the
  418. URL ourselves based on the title.
  419. """
  420. if self._fullurl:
  421. return self._fullurl
  422. else:
  423. encoded = self._title.encode("utf8").replace(" ", "_")
  424. slug = quote(encoded, safe="/:")
  425. path = self.site._article_path.replace("$1", slug)
  426. return ''.join((self.site.url, path))
  427. @property
  428. def namespace(self):
  429. """The page's namespace ID (an integer).
  430. Like :py:meth:`title`, this won't do any API queries on its own. If the
  431. API was never queried for this page, we will attempt to determine the
  432. namespace ourselves based on the title.
  433. """
  434. return self._namespace
  435. @property
  436. def protection(self):
  437. """The page's current protection status.
  438. Makes an API query only if we haven't already made one.
  439. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` if the page
  440. name is invalid. Won't raise an error if the page is missing because
  441. those can still be create-protected.
  442. """
  443. if self._exists == self.PAGE_UNKNOWN:
  444. self._load()
  445. self._assert_validity() # Invalid pages cannot be protected
  446. return self._protection
  447. @property
  448. def is_talkpage(self):
  449. """``True`` if the page is a talkpage, otherwise ``False``.
  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
  452. whether it is a talkpage ourselves based on its namespace.
  453. """
  454. return self._is_talkpage
  455. @property
  456. def is_redirect(self):
  457. """``True`` if the page is a redirect, otherwise ``False``.
  458. Makes an API query only if we haven't already made one.
  459. We will return ``False`` even if the page does not exist or is invalid.
  460. """
  461. if self._exists == self.PAGE_UNKNOWN:
  462. self._load()
  463. return self._is_redirect
  464. def reload(self):
  465. """Forcibly reload the page's attributes.
  466. Emphasis on *reload*: this is only necessary if there is reason to
  467. believe they have changed.
  468. """
  469. self._load()
  470. if self._content is not None:
  471. # Only reload content if it has already been loaded:
  472. self._load_content()
  473. def toggle_talk(self, follow_redirects=None):
  474. """Return a content page's talk page, or vice versa.
  475. The title of the new page is determined by namespace logic, not API
  476. queries. We won't make any API queries on our own.
  477. If *follow_redirects* is anything other than ``None`` (the default), it
  478. will be passed to the new :py:class:`~earwigbot.wiki.page.Page`
  479. object's :py:meth:`__init__`. Otherwise, we'll use the value passed to
  480. our own :py:meth:`__init__`.
  481. Will raise :py:exc:`~earwigbot.exceptions.InvalidPageError` if we try
  482. to get the talk page of a special page (in the ``Special:`` or
  483. ``Media:`` namespaces), but we won't raise an exception if our page is
  484. otherwise missing or invalid.
  485. """
  486. if self._namespace < 0:
  487. ns = self.site.namespace_id_to_name(self._namespace)
  488. e = u"Pages in the {0} namespace can't have talk pages.".format(ns)
  489. raise exceptions.InvalidPageError(e)
  490. if self._is_talkpage:
  491. new_ns = self._namespace - 1
  492. else:
  493. new_ns = self._namespace + 1
  494. try:
  495. body = self._title.split(":", 1)[1]
  496. except IndexError:
  497. body = self._title
  498. new_prefix = self.site.namespace_id_to_name(new_ns)
  499. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  500. # but unnecessary), just do "Title":
  501. if new_prefix:
  502. new_title = u":".join((new_prefix, body))
  503. else:
  504. new_title = body
  505. if follow_redirects is None:
  506. follow_redirects = self._follow_redirects
  507. return Page(self.site, new_title, follow_redirects)
  508. def get(self):
  509. """Return page content, which is cached if you try to call get again.
  510. Raises InvalidPageError or PageNotFoundError if the page name is
  511. invalid or the page does not exist, respectively.
  512. """
  513. if self._exists == self.PAGE_UNKNOWN:
  514. # Kill two birds with one stone by doing an API query for both our
  515. # attributes and our page content:
  516. query = self.site.api_query
  517. result = query(action="query", rvlimit=1, titles=self._title,
  518. prop="info|revisions", inprop="protection|url",
  519. intoken="edit", rvprop="content|timestamp")
  520. self._load_attributes(result=result)
  521. self._assert_existence()
  522. self._load_content(result=result)
  523. # Follow redirects if we're told to:
  524. if self._keep_following and self._is_redirect:
  525. self._title = self.get_redirect_target()
  526. self._keep_following = False # Don't follow double redirects
  527. self._exists = self.PAGE_UNKNOWN # Force another API query
  528. self.get()
  529. return self._content
  530. # Make sure we're dealing with a real page here. This may be outdated
  531. # if the page was deleted since we last called self._load_attributes(),
  532. # but self._load_content() can handle that:
  533. self._assert_existence()
  534. if self._content is None:
  535. self._load_content()
  536. return self._content
  537. def get_redirect_target(self):
  538. """If the page is a redirect, return its destination.
  539. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  540. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  541. invalid or the page does not exist, respectively. Raises
  542. :py:exc:`~earwigbot.exceptions.RedirectError` if the page is not a
  543. redirect.
  544. """
  545. re_redirect = "^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  546. content = self.get()
  547. try:
  548. return re.findall(re_redirect, content, flags=re.I)[0]
  549. except IndexError:
  550. e = "The page does not appear to have a redirect target."
  551. raise exceptions.RedirectError(e)
  552. def get_creator(self):
  553. """Return the User object for the first person to edit the page.
  554. Makes an API query only if we haven't already made one. Normally, we
  555. can get the creator along with everything else (except content) in
  556. :py:meth:`_load_attributes`. However, due to a limitation in the API
  557. (can't get the editor of one revision and the content of another at
  558. both ends of the history), if our other attributes were only loaded
  559. through :py:meth:`get`, we'll have to do another API query.
  560. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  561. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  562. invalid or the page does not exist, respectively.
  563. """
  564. if self._exists == self.PAGE_UNKNOWN:
  565. self._load()
  566. self._assert_existence()
  567. if not self._creator:
  568. self._load()
  569. self._assert_existence()
  570. return self.site.get_user(self._creator)
  571. def parse(self):
  572. """Parse the page content for templates, links, etc.
  573. Actual parsing is handled by :py:mod:`mwparserfromhell`. Raises
  574. :py:exc:`ImportError` if :py:mod:`mwparserfromhell` isn't installed,
  575. and :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  576. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  577. invalid or the page does not exist, respectively.
  578. """
  579. if not mwparserfromhell:
  580. raise ImportError("mwparserfromhell")
  581. return mwparserfromhell.parse(self.get())
  582. def edit(self, text, summary, minor=False, bot=True, force=False):
  583. """Replace the page's content or creates a new page.
  584. *text* is the new page content, with *summary* as the edit summary.
  585. If *minor* is ``True``, the edit will be marked as minor. If *bot* is
  586. ``True``, the edit will be marked as a bot edit, but only if we
  587. actually have a bot flag.
  588. Use *force* to push the new content even if there's an edit conflict or
  589. the page was deleted/recreated between getting our edit token and
  590. editing our page. Be careful with this!
  591. """
  592. self._edit(text=text, summary=summary, minor=minor, bot=bot,
  593. force=force)
  594. def add_section(self, text, title, minor=False, bot=True, force=False):
  595. """Add a new section to the bottom of the page.
  596. The arguments for this are the same as those for :py:meth:`edit`, but
  597. instead of providing a summary, you provide a section title. Likewise,
  598. raised exceptions are the same as :py:meth:`edit`'s.
  599. This should create the page if it does not already exist, with just the
  600. new section as content.
  601. """
  602. self._edit(text=text, summary=title, minor=minor, bot=bot, force=force,
  603. section="new")
  604. def check_exclusion(self, username=None, optouts=None):
  605. """Check whether or not we are allowed to edit the page.
  606. Return ``True`` if we *are* allowed to edit this page, and ``False`` if
  607. we aren't.
  608. *username* is used to determine whether we are part of a specific list
  609. of allowed or disallowed bots (e.g. ``{{bots|allow=EarwigBot}}`` or
  610. ``{{bots|deny=FooBot,EarwigBot}}``). It's ``None`` by default, which
  611. will swipe our username from :py:meth:`site.get_user()
  612. <earwigbot.wiki.site.Site.get_user>`.\
  613. :py:attr:`~earwigbot.wiki.user.User.name`.
  614. *optouts* is a list of messages to consider this check as part of for
  615. the purpose of opt-out; it defaults to ``None``, which ignores the
  616. parameter completely. For example, if *optouts* is ``["nolicense"]``,
  617. we'll return ``False`` on ``{{bots|optout=nolicense}}`` or
  618. ``{{bots|optout=all}}``, but `True` on
  619. ``{{bots|optout=orfud,norationale,replaceable}}``.
  620. """
  621. def parse_param(template, param):
  622. value = template.get_param(param).value
  623. return [item.strip().lower() for item in value.split(",")]
  624. if not username:
  625. username = self.site.get_user().name
  626. # Lowercase everything:
  627. username = username.lower()
  628. optouts = [optout.lower() for optout in optouts] if optouts else []
  629. r_bots = "\{\{\s*(no)?bots\s*(\||\}\})"
  630. filter = self.parse().ifilter_templates(matches=r_bots, recursive=True)
  631. for template in filter:
  632. if template.has_param("deny"):
  633. denies = parse_param(template, "deny")
  634. if "all" in denies or username in denies:
  635. return False
  636. if template.has_param("allow"):
  637. allows = parse_param(template, "allow")
  638. if "all" in allows or username in allows:
  639. continue
  640. if optouts and template.has_param("optout"):
  641. tasks = parse_param(template, "optout")
  642. matches = [optout in tasks for optout in optouts]
  643. if "all" in tasks or any(matches):
  644. return False
  645. if template.name.strip().lower() == "nobots":
  646. return False
  647. return True