Additional IRC commands and bot tasks for EarwigBot 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.

851 lines
35 KiB

  1. # Copyright (C) 2009-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import re
  21. from collections import OrderedDict
  22. from datetime import datetime
  23. from os.path import expanduser
  24. from threading import Lock
  25. from time import sleep
  26. import mwparserfromhell
  27. import pymysql
  28. import pymysql.cursors
  29. from earwigbot import exceptions, wiki
  30. from earwigbot.tasks import Task
  31. _DEFAULT_PAGE_TEXT = """<noinclude><!-- You can edit anything on this page \
  32. except for content inside of <!-- stat begin/end -> and <!-- sig begin/end -> \
  33. without causing problems. Most of the chart can be modified by editing the \
  34. templates it uses, documented in [[Template:AfC statistics/doc]]. -->
  35. {{NOINDEX}}</noinclude>\
  36. <!-- stat begin --><!-- stat end -->
  37. <span style="font-style: italic; font-size: 85%%;">Last updated by \
  38. <!-- sig begin --><!-- sig end --></span>\
  39. <noinclude>{{Documentation|Template:%(pageroot)s/doc}}</noinclude>
  40. """
  41. _PER_CHART_LIMIT = 1000
  42. class AfCStatistics(Task):
  43. """A task to generate statistics for WikiProject Articles for Creation.
  44. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  45. accessed with pymysql. Statistics are synchronied with the live database
  46. every four minutes and saved once an hour, on the hour, to subpages of
  47. self.pageroot. In the live bot, this is "Template:AfC statistics".
  48. """
  49. name = "afc_statistics"
  50. number = 2
  51. # Chart status number constants:
  52. CHART_NONE = 0
  53. CHART_PEND = 1
  54. CHART_REVIEW = 3
  55. CHART_ACCEPT = 4
  56. CHART_DECLINE = 5
  57. CHART_MISPLACE = 6
  58. def setup(self):
  59. self.cfg = cfg = self.config.tasks.get(self.name, {})
  60. self.site = self.bot.wiki.get_site()
  61. self.revision_cache = {}
  62. # Set some wiki-related attributes:
  63. self.pageroot = cfg.get("page", "Template:AfC statistics")
  64. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  65. self.ignore_list = cfg.get("ignoreList", [])
  66. default_summary = (
  67. "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  68. )
  69. self.summary = self.make_summary(cfg.get("summary", default_summary))
  70. # Templates used in chart generation:
  71. templates = cfg.get("templates", {})
  72. self.tl_header = templates.get("header", "AfC statistics/header")
  73. self.tl_row = templates.get("row", "#invoke:AfC|row")
  74. self.tl_footer = templates.get("footer", "AfC statistics/footer")
  75. # Connection data for our SQL database:
  76. kwargs = cfg.get("sql", {})
  77. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  78. self.conn_data = kwargs
  79. self.db_access_lock = Lock()
  80. def run(self, **kwargs):
  81. """Entry point for a task event.
  82. Depending on the kwargs passed, we will either synchronize our local
  83. statistics database with the site (self.sync()) or save it to the wiki
  84. (self.save()). We will additionally create an SQL connection with our
  85. local database.
  86. """
  87. action = kwargs.get("action")
  88. if not self.db_access_lock.acquire(False): # Non-blocking
  89. if action == "sync":
  90. self.logger.info("A sync is already ongoing; aborting")
  91. return
  92. self.logger.info("Waiting for database access lock")
  93. self.db_access_lock.acquire()
  94. try:
  95. self.site = self.bot.wiki.get_site()
  96. self.conn = pymysql.connect(**self.conn_data)
  97. self.revision_cache = {}
  98. try:
  99. if action == "save":
  100. self.save(kwargs)
  101. elif action == "sync":
  102. self.sync(kwargs)
  103. finally:
  104. self.conn.close()
  105. finally:
  106. self.db_access_lock.release()
  107. #################### CHART BUILDING AND SAVING METHODS ####################
  108. def save(self, kwargs):
  109. """Save our local statistics to the wiki.
  110. After checking for emergency shutoff, the statistics chart is compiled,
  111. and then saved to subpages of self.pageroot using self.summary iff it
  112. has changed since last save.
  113. """
  114. self.logger.info("Saving chart")
  115. if kwargs.get("fromIRC"):
  116. summary = self.summary + " (!earwigbot)"
  117. else:
  118. if self.shutoff_enabled():
  119. return
  120. summary = self.summary
  121. statistics = self._compile_charts()
  122. for name, chart in statistics.items():
  123. self._save_page(name, chart, summary)
  124. def _save_page(self, name, chart, summary):
  125. """Save a statistics chart to a single page."""
  126. page = self.site.get_page(f"{self.pageroot}/{name}")
  127. try:
  128. text = page.get()
  129. except exceptions.PageNotFoundError:
  130. text = _DEFAULT_PAGE_TEXT % {"pageroot": self.pageroot}
  131. newtext = re.sub(
  132. "<!-- stat begin -->(.*?)<!-- stat end -->",
  133. "<!-- stat begin -->" + chart + "<!-- stat end -->",
  134. text,
  135. flags=re.DOTALL,
  136. )
  137. if newtext == text:
  138. self.logger.info(f"Chart for {name} unchanged; not saving")
  139. return
  140. newtext = re.sub(
  141. "<!-- sig begin -->(.*?)<!-- sig end -->",
  142. "<!-- sig begin -->~~~ at ~~~~~<!-- sig end -->",
  143. newtext,
  144. )
  145. page.edit(newtext, summary, minor=True, bot=True)
  146. self.logger.info(f"Chart for {name} saved to [[{page.title}]]")
  147. def _compile_charts(self):
  148. """Compile and return all statistics information from our local db."""
  149. stats = OrderedDict()
  150. with self.conn.cursor(pymysql.cursors.DictCursor) as cursor:
  151. cursor.execute("SELECT * FROM chart")
  152. for chart in cursor:
  153. name = chart["chart_name"]
  154. stats[name] = self._compile_chart(chart)
  155. return stats
  156. def _compile_chart(self, chart_info):
  157. """Compile and return a single statistics chart."""
  158. chart = self.tl_header + "|" + chart_info["chart_title"]
  159. if chart_info["chart_special_title"]:
  160. chart += "|" + chart_info["chart_special_title"]
  161. chart = "{{" + chart + "}}"
  162. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  163. with self.conn.cursor(pymysql.cursors.DictCursor) as cursor:
  164. cursor.execute(query, (chart_info["chart_id"],))
  165. rows = cursor.fetchall()
  166. skipped = max(0, len(rows) - _PER_CHART_LIMIT)
  167. rows = rows[:_PER_CHART_LIMIT]
  168. for page in rows:
  169. chart += "\n" + self._compile_chart_row(page)
  170. footer = "{{" + self.tl_footer
  171. if skipped:
  172. footer += f"|skip={skipped}"
  173. footer += "}}"
  174. chart += "\n" + footer + "\n"
  175. return chart
  176. def _compile_chart_row(self, page):
  177. """Compile and return a single chart row.
  178. 'page' is a dict of page information, taken as a row from the page
  179. table, where keys are column names and values are their cell contents.
  180. """
  181. row = "{0}|s={page_status}|t={page_title}|z={page_size}|"
  182. if page["page_special_oldid"]:
  183. row += (
  184. "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  185. )
  186. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}"
  187. page["page_special_time"] = self._fmt_time(page["page_special_time"])
  188. page["page_modify_time"] = self._fmt_time(page["page_modify_time"])
  189. if page["page_notes"]:
  190. row += "|n=1{page_notes}"
  191. return "{{" + row.format(self.tl_row, **page) + "}}"
  192. def _fmt_time(self, date):
  193. """Format a datetime into the standard MediaWiki timestamp format."""
  194. return date.strftime("%H:%M, %d %b %Y")
  195. ######################## PRIMARY SYNC ENTRY POINTS ########################
  196. def sync(self, kwargs):
  197. """Synchronize our local statistics database with the site.
  198. Syncing involves, in order, updating tracked submissions that have
  199. been changed since last sync (self._update_tracked()), adding pending
  200. submissions that are not tracked (self._add_untracked()), and removing
  201. old submissions from the database (self._delete_old()).
  202. The sync will be canceled if SQL replication lag is greater than 600
  203. seconds, because this will lead to potential problems and outdated
  204. data, not to mention putting demand on an already overloaded server.
  205. Giving sync the kwarg "ignore_replag" will go around this restriction.
  206. """
  207. self.logger.info("Starting sync")
  208. replag = self.site.get_replag()
  209. self.logger.debug(f"Server replag is {replag}")
  210. if replag > 600 and not kwargs.get("ignore_replag"):
  211. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes"
  212. self.logger.warn(msg.format(replag))
  213. return
  214. with self.conn.cursor() as cursor:
  215. self._update_tracked(cursor)
  216. self._add_untracked(cursor)
  217. self._update_stale(cursor)
  218. self._delete_old(cursor)
  219. self.logger.info("Sync completed")
  220. def _update_tracked(self, cursor):
  221. """Update tracked submissions that have been changed since last sync.
  222. This is done by iterating through every page in our database and
  223. comparing our stored latest revision ID with the actual latest revision
  224. ID from an SQL query. If they differ, we will update our information
  225. about the page (self._update_page()).
  226. If the page does not exist, we will remove it from our database with
  227. self._untrack_page().
  228. """
  229. self.logger.debug("Updating tracked submissions")
  230. query1 = """SELECT page_id, page_title, page_modify_oldid
  231. FROM page"""
  232. query2 = """SELECT page_latest, page_title, page_namespace
  233. FROM page WHERE page_id = ?"""
  234. cursor.execute(query1)
  235. for pageid, title, oldid in cursor.fetchall():
  236. result = list(self.site.sql_query(query2, (pageid,)))
  237. if not result:
  238. self._untrack_page(cursor, pageid)
  239. continue
  240. real_oldid, real_title, real_ns = result[0]
  241. if oldid == real_oldid:
  242. continue
  243. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  244. self.logger.debug(msg.format(title, pageid, oldid))
  245. msg = " {0}: oldid: {1} -> {2}"
  246. self.logger.debug(msg.format(pageid, oldid, real_oldid))
  247. real_title = real_title.decode("utf8").replace("_", " ")
  248. ns = self.site.namespace_id_to_name(real_ns)
  249. if ns:
  250. real_title = ":".join((ns, real_title))
  251. try:
  252. self._update_page(cursor, pageid, real_title)
  253. except Exception:
  254. e = "Error updating page [[{0}]] (id: {1})"
  255. self.logger.exception(e.format(real_title, pageid))
  256. def _add_untracked(self, cursor):
  257. """Add pending submissions that are not yet tracked.
  258. This is done by compiling a list of all currently tracked submissions
  259. and iterating through all members of self.pending_cat via SQL. If a
  260. page in the pending category is not tracked and is not in
  261. self.ignore_list, we will track it with self._track_page().
  262. """
  263. self.logger.debug("Adding untracked pending submissions")
  264. query1 = "SELECT page_id FROM page"
  265. query2 = """SELECT page_id, page_title, page_namespace
  266. FROM page
  267. INNER JOIN categorylinks ON page_id = cl_from
  268. WHERE cl_to = ?"""
  269. cursor.execute(query1)
  270. tracked = [pid for (pid,) in cursor.fetchall()]
  271. pend_cat = self.pending_cat.replace(" ", "_")
  272. for pageid, title, ns in self.site.sql_query(query2, (pend_cat,)):
  273. if pageid in tracked:
  274. continue
  275. title = title.decode("utf8").replace("_", " ")
  276. ns_name = self.site.namespace_id_to_name(ns)
  277. if ns_name:
  278. title = ":".join((ns_name, title))
  279. if title in self.ignore_list or ns == wiki.NS_CATEGORY:
  280. continue
  281. msg = f"Tracking page [[{title}]] (id: {pageid})"
  282. self.logger.debug(msg)
  283. try:
  284. self._track_page(cursor, pageid, title)
  285. except Exception:
  286. e = "Error tracking page [[{0}]] (id: {1})"
  287. self.logger.exception(e.format(title, pageid))
  288. def _update_stale(self, cursor):
  289. """Update submissions that haven't been updated in a long time.
  290. This is intended to update notes that change without typical update
  291. triggers, like when submitters are blocked. It also resolves conflicts
  292. when pages are tracked during high replag, potentially causing data to
  293. be inaccurate (like a missed decline). It updates no more than the ten
  294. stalest pages that haven't been updated in two days.
  295. """
  296. self.logger.debug("Updating stale submissions")
  297. query = """SELECT page_id, page_title, page_modify_oldid
  298. FROM page JOIN updatelog ON page_id = update_id
  299. WHERE ADDTIME(update_time, '48:00:00') < NOW()
  300. ORDER BY update_time ASC LIMIT 10"""
  301. cursor.execute(query)
  302. for pageid, title, oldid in cursor:
  303. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  304. self.logger.debug(msg.format(title, pageid, oldid))
  305. try:
  306. self._update_page(cursor, pageid, title)
  307. except Exception:
  308. e = "Error updating page [[{0}]] (id: {1})"
  309. self.logger.exception(e.format(title, pageid))
  310. def _delete_old(self, cursor):
  311. """Remove old submissions from the database.
  312. "Old" is defined as a submission that has been declined or accepted
  313. more than 36 hours ago. Pending submissions cannot be "old".
  314. """
  315. self.logger.debug("Removing old submissions from chart")
  316. query = """DELETE FROM page, row, updatelog USING page JOIN row
  317. ON page_id = row_id JOIN updatelog ON page_id = update_id
  318. WHERE row_chart IN (?, ?)
  319. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  320. cursor.execute(query, (self.CHART_ACCEPT, self.CHART_DECLINE))
  321. ######################## PRIMARY PAGE ENTRY POINTS ########################
  322. def _untrack_page(self, cursor, pageid):
  323. """Remove a page, given by ID, from our database."""
  324. self.logger.debug(f"Untracking page (id: {pageid})")
  325. query = """DELETE FROM page, row, updatelog USING page JOIN row
  326. ON page_id = row_id JOIN updatelog ON page_id = update_id
  327. WHERE page_id = ?"""
  328. cursor.execute(query, (pageid,))
  329. def _track_page(self, cursor, pageid, title):
  330. """Update hook for when page is not in our database.
  331. A variety of SQL queries are used to gather information about the page,
  332. which is then saved to our database.
  333. """
  334. content = self._get_content(pageid)
  335. if content is None:
  336. msg = f"Could not get page content for [[{title}]]"
  337. self.logger.error(msg)
  338. return
  339. namespace = self.site.get_page(title).namespace
  340. status, chart = self._get_status_and_chart(content, namespace)
  341. if chart == self.CHART_NONE:
  342. msg = f"Could not find a status for [[{title}]]"
  343. self.logger.warn(msg)
  344. return
  345. m_user, m_time, m_id = self._get_modify(pageid)
  346. s_user, s_time, s_id = self._get_special(pageid, content, chart)
  347. notes = self._get_notes(chart, content, m_time, s_user)
  348. query1 = "INSERT INTO row VALUES (?, ?)"
  349. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  350. query3 = "INSERT INTO updatelog VALUES (?, ?)"
  351. cursor.execute(query1, (pageid, chart))
  352. cursor.execute(
  353. query2,
  354. (
  355. pageid,
  356. status,
  357. title,
  358. len(content),
  359. notes,
  360. m_user,
  361. m_time,
  362. m_id,
  363. s_user,
  364. s_time,
  365. s_id,
  366. ),
  367. )
  368. cursor.execute(query3, (pageid, datetime.utcnow()))
  369. def _update_page(self, cursor, pageid, title):
  370. """Update hook for when page is already in our database.
  371. A variety of SQL queries are used to gather information about the page,
  372. which is compared against our stored information. Differing information
  373. is then updated.
  374. """
  375. content = self._get_content(pageid)
  376. if content is None:
  377. msg = f"Could not get page content for [[{title}]]"
  378. self.logger.error(msg)
  379. return
  380. namespace = self.site.get_page(title).namespace
  381. status, chart = self._get_status_and_chart(content, namespace)
  382. if chart == self.CHART_NONE:
  383. self._untrack_page(cursor, pageid)
  384. return
  385. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  386. with self.conn.cursor(pymysql.cursors.DictCursor) as dict_cursor:
  387. dict_cursor.execute(query, (pageid,))
  388. result = dict_cursor.fetchall()[0]
  389. m_user, m_time, m_id = self._get_modify(pageid)
  390. if title != result["page_title"]:
  391. self._update_page_title(cursor, result, pageid, title)
  392. if m_id != result["page_modify_oldid"]:
  393. self._update_page_modify(
  394. cursor, result, pageid, len(content), m_user, m_time, m_id
  395. )
  396. if status != result["page_status"]:
  397. special = self._update_page_status(
  398. cursor, result, pageid, content, status, chart
  399. )
  400. s_user = special[0]
  401. else:
  402. s_user = result["page_special_user"]
  403. notes = self._get_notes(chart, content, m_time, s_user)
  404. if notes != result["page_notes"]:
  405. self._update_page_notes(cursor, result, pageid, notes)
  406. query = "UPDATE updatelog SET update_time = ? WHERE update_id = ?"
  407. cursor.execute(query, (datetime.utcnow(), pageid))
  408. ###################### PAGE ATTRIBUTE UPDATE METHODS ######################
  409. def _update_page_title(self, cursor, result, pageid, title):
  410. """Update the title of a page in our database."""
  411. query = "UPDATE page SET page_title = ? WHERE page_id = ?"
  412. cursor.execute(query, (title, pageid))
  413. msg = " {0}: title: {1} -> {2}"
  414. self.logger.debug(msg.format(pageid, result["page_title"], title))
  415. def _update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  416. """Update the last modified information of a page in our database."""
  417. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  418. page_modify_time = ?, page_modify_oldid = ?
  419. WHERE page_id = ?"""
  420. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  421. msg = " {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  422. msg = msg.format(
  423. pageid,
  424. result["page_modify_user"],
  425. result["page_modify_time"],
  426. result["page_modify_oldid"],
  427. m_user,
  428. m_time,
  429. m_id,
  430. )
  431. self.logger.debug(msg)
  432. def _update_page_status(self, cursor, result, pageid, content, status, chart):
  433. """Update the status and "specialed" information of a page."""
  434. query1 = """UPDATE page JOIN row ON page_id = row_id
  435. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  436. query2 = """UPDATE page SET page_special_user = ?,
  437. page_special_time = ?, page_special_oldid = ?
  438. WHERE page_id = ?"""
  439. cursor.execute(query1, (status, chart, pageid))
  440. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  441. self.logger.debug(
  442. msg.format(
  443. pageid, result["page_status"], result["row_chart"], status, chart
  444. )
  445. )
  446. s_user, s_time, s_id = self._get_special(pageid, content, chart)
  447. if s_id != result["page_special_oldid"]:
  448. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  449. msg = " {0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  450. msg = msg.format(
  451. pageid,
  452. result["page_special_user"],
  453. result["page_special_time"],
  454. result["page_special_oldid"],
  455. s_user,
  456. s_time,
  457. s_id,
  458. )
  459. self.logger.debug(msg)
  460. return s_user, s_time, s_id
  461. def _update_page_notes(self, cursor, result, pageid, notes):
  462. """Update the notes (or warnings) of a page in our database."""
  463. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  464. cursor.execute(query, (notes, pageid))
  465. msg = " {0}: notes: {1} -> {2}"
  466. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  467. ###################### DATA RETRIEVAL HELPER METHODS ######################
  468. def _get_content(self, pageid):
  469. """Get the current content of a page by ID from the API.
  470. The page's current revision ID is retrieved from SQL, and then
  471. an API query is made to get its content. This is the only API query
  472. used in the task's code.
  473. """
  474. query = "SELECT page_latest FROM page WHERE page_id = ?"
  475. result = self.site.sql_query(query, (pageid,))
  476. try:
  477. revid = int(list(result)[0][0])
  478. except IndexError:
  479. return None
  480. return self._get_revision_content(revid)
  481. def _get_revision_content(self, revid, tries=1):
  482. """Get the content of a revision by ID from the API."""
  483. if revid in self.revision_cache:
  484. return self.revision_cache[revid]
  485. res = self.site.api_query(
  486. action="query",
  487. prop="revisions",
  488. rvprop="content",
  489. rvslots="main",
  490. revids=revid,
  491. )
  492. try:
  493. revision = res["query"]["pages"].values()[0]["revisions"][0]
  494. content = revision["slots"]["main"]["*"]
  495. except KeyError:
  496. if tries == 0:
  497. raise
  498. sleep(5)
  499. return self._get_revision_content(revid, tries=tries - 1)
  500. self.revision_cache[revid] = content
  501. return content
  502. def _get_status_and_chart(self, content, namespace):
  503. """Determine the status and chart number of an AfC submission.
  504. The methodology used here is the same one I've been using for years
  505. (see also commands.afc_report), but with the new draft system taken
  506. into account. The order here is important: if there is more than one
  507. {{AfC submission}} template on a page, we need to know which one to
  508. use (revision history search to find the most recent isn't a viable
  509. idea :P).
  510. """
  511. statuses = self.get_statuses(content)
  512. if namespace == wiki.NS_MAIN:
  513. if statuses:
  514. return None, self.CHART_MISPLACE
  515. return "a", self.CHART_ACCEPT
  516. elif "R" in statuses:
  517. return "r", self.CHART_REVIEW
  518. elif "P" in statuses:
  519. return "p", self.CHART_PEND
  520. elif "T" in statuses:
  521. return None, self.CHART_NONE
  522. elif "D" in statuses:
  523. return "d", self.CHART_DECLINE
  524. return None, self.CHART_NONE
  525. def get_statuses(self, content):
  526. """Return a list of all AfC submission statuses in a page's text."""
  527. valid = ["P", "R", "T", "D"]
  528. aliases = {
  529. "submit": "P",
  530. "afc submission/submit": "P",
  531. "afc submission/reviewing": "R",
  532. "afc submission/pending": "P",
  533. "afc submission/draft": "T",
  534. "afc submission/declined": "D",
  535. }
  536. statuses = []
  537. code = mwparserfromhell.parse(content)
  538. for template in code.filter_templates():
  539. name = template.name.strip().lower()
  540. if name == "afc submission":
  541. if template.has(1, ignore_empty=True):
  542. status = template.get(1).value.strip().upper()
  543. statuses.append(status if status in valid else "P")
  544. else:
  545. statuses.append("P")
  546. elif name in aliases:
  547. statuses.append(aliases[name])
  548. return statuses
  549. def _get_modify(self, pageid):
  550. """Return information about a page's last edit ("modification").
  551. This consists of the most recent editor, modification time, and the
  552. lastest revision ID.
  553. """
  554. query = """SELECT actor_name, rev_timestamp, rev_id
  555. FROM revision
  556. JOIN page ON rev_id = page_latest
  557. JOIN actor ON rev_actor = actor_id
  558. WHERE page_id = ?"""
  559. result = self.site.sql_query(query, (pageid,))
  560. m_user, m_time, m_id = list(result)[0]
  561. timestamp = datetime.strptime(m_time, "%Y%m%d%H%M%S")
  562. return m_user.decode("utf8"), timestamp, m_id
  563. def _get_special(self, pageid, content, chart):
  564. """Return information about a page's "special" edit.
  565. I tend to use the term "special" as a verb a lot, which is bound to
  566. cause confusion. It is merely a short way of saying "the edit in which
  567. a declined submission was declined, an accepted submission was
  568. accepted, a submission in review was set as such, a pending submission
  569. was submitted, and a "misplaced" submission was created."
  570. This "information" consists of the special edit's editor, its time, and
  571. its revision ID. If the page's status is not something that involves
  572. "special"-ing, we will return None for all three. The same will be
  573. returned if we cannot determine when the page was "special"-ed.
  574. """
  575. charts = {
  576. self.CHART_NONE: (lambda pageid, content: None, None, None),
  577. self.CHART_MISPLACE: self.get_create,
  578. self.CHART_ACCEPT: self.get_accepted,
  579. self.CHART_REVIEW: self.get_reviewing,
  580. self.CHART_PEND: self.get_pending,
  581. self.CHART_DECLINE: self.get_decline,
  582. }
  583. return charts[chart](pageid, content)
  584. def get_create(self, pageid, content=None):
  585. """Return (creator, create_ts, create_revid) for the given page."""
  586. query = """SELECT actor_name, rev_timestamp, rev_id
  587. FROM revision
  588. JOIN actor ON rev_actor = actor_id
  589. WHERE rev_id = (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  590. result = self.site.sql_query(query, (pageid,))
  591. c_user, c_time, c_id = list(result)[0]
  592. timestamp = datetime.strptime(c_time, "%Y%m%d%H%M%S")
  593. return c_user.decode("utf8"), timestamp, c_id
  594. def get_accepted(self, pageid, content=None):
  595. """Return (acceptor, accept_ts, accept_revid) for the given page."""
  596. query = """SELECT actor_name, rev_timestamp, rev_id
  597. FROM revision
  598. JOIN actor ON rev_actor = actor_id
  599. JOIN comment ON rev_comment_id = comment_id
  600. WHERE rev_page = ?
  601. AND comment_text LIKE "% moved page [[%]] to [[%]]%"
  602. ORDER BY rev_timestamp DESC LIMIT 1"""
  603. result = self.site.sql_query(query, (pageid,))
  604. try:
  605. a_user, a_time, a_id = list(result)[0]
  606. except IndexError:
  607. return None, None, None
  608. timestamp = datetime.strptime(a_time, "%Y%m%d%H%M%S")
  609. return a_user.decode("utf8"), timestamp, a_id
  610. def get_reviewing(self, pageid, content=None):
  611. """Return (reviewer, review_ts, review_revid) for the given page."""
  612. return self._search_history(pageid, self.CHART_REVIEW, ["R"], [])
  613. def get_pending(self, pageid, content):
  614. """Return (submitter, submit_ts, submit_revid) for the given page."""
  615. res = self._get_status_helper(pageid, content, ("P", ""), ("u", "ts"))
  616. return res or self._search_history(pageid, self.CHART_PEND, ["P"], [])
  617. def get_decline(self, pageid, content):
  618. """Return (decliner, decline_ts, decline_revid) for the given page."""
  619. params = ("decliner", "declinets")
  620. res = self._get_status_helper(pageid, content, ("D"), params)
  621. return res or self._search_history(
  622. pageid, self.CHART_DECLINE, ["D"], ["R", "P", "T"]
  623. )
  624. def _get_status_helper(self, pageid, content, statuses, params):
  625. """Helper function for get_pending() and get_decline()."""
  626. submits = []
  627. code = mwparserfromhell.parse(content)
  628. for tmpl in code.filter_templates():
  629. status = tmpl.get(1).value.strip().upper() if tmpl.has(1) else "P"
  630. if tmpl.name.strip().lower() == "afc submission":
  631. if all([tmpl.has(par, ignore_empty=True) for par in params]):
  632. if status in statuses:
  633. data = [str(tmpl.get(par).value) for par in params]
  634. submits.append(data)
  635. if not submits:
  636. return None
  637. user, stamp = max(submits, key=lambda pair: pair[1])
  638. query = """SELECT rev_id
  639. FROM revision_userindex
  640. JOIN actor ON rev_actor = actor_id
  641. WHERE rev_page = ? AND actor_name = ? AND ABS(rev_timestamp - ?) <= 60
  642. ORDER BY ABS(rev_timestamp - ?) ASC LIMIT 1"""
  643. result = self.site.sql_query(query, (pageid, user, stamp, stamp))
  644. try:
  645. dtime = datetime.strptime(stamp, "%Y%m%d%H%M%S")
  646. return user, dtime, list(result)[0][0]
  647. except (ValueError, IndexError):
  648. return None
  649. def _search_history(self, pageid, chart, search_with, search_without):
  650. """Search through a page's history to find when a status was set.
  651. Linear search backwards in time for the edit right after the most
  652. recent edit that fails the (pseudocode) test:
  653. ``status_set(any(search_with)) && !status_set(any(search_without))``
  654. """
  655. query = """SELECT actor_name, rev_timestamp, rev_id
  656. FROM revision
  657. JOIN actor ON rev_actor = actor_id
  658. WHERE rev_page = ? ORDER BY rev_id DESC"""
  659. result = self.site.sql_query(query, (pageid,))
  660. counter = 0
  661. last = (None, None, None)
  662. for user, ts, revid in result:
  663. counter += 1
  664. if counter > 50:
  665. msg = "Exceeded 50 content lookups while searching history of page (id: {0}, chart: {1})"
  666. self.logger.warn(msg.format(pageid, chart))
  667. return None, None, None
  668. try:
  669. content = self._get_revision_content(revid)
  670. except exceptions.APIError:
  671. msg = "API error interrupted SQL query in _search_history() for page (id: {0}, chart: {1})"
  672. self.logger.exception(msg.format(pageid, chart))
  673. return None, None, None
  674. statuses = self.get_statuses(content)
  675. req = search_with and not any([s in statuses for s in search_with])
  676. if any([s in statuses for s in search_without]) or req:
  677. return last
  678. timestamp = datetime.strptime(ts, "%Y%m%d%H%M%S")
  679. last = (user.decode("utf8"), timestamp, revid)
  680. return last
  681. def _get_notes(self, chart, content, m_time, s_user):
  682. """Return any special notes or warnings about this page.
  683. copyvio: submission is a suspected copyright violation
  684. unsourced: submission lacks references completely
  685. no-inline: submission has no inline citations
  686. short: submission is less than a kilobyte in length
  687. resubmit: submission was resubmitted after a previous decline
  688. old: submission has not been touched in > 4 days
  689. rejected: submission was rejected, a more severe form of declined
  690. blocked: submitter is currently blocked
  691. """
  692. notes = ""
  693. ignored_charts = [self.CHART_NONE, self.CHART_ACCEPT]
  694. if chart in ignored_charts:
  695. return notes
  696. if chart == self.CHART_DECLINE:
  697. # Decline is special, as only the rejected note is meaningful
  698. code = mwparserfromhell.parse(content)
  699. for tmpl in code.filter_templates():
  700. if tmpl.name.strip().lower() == "afc submission":
  701. if tmpl.has("reject") and tmpl.get("reject").value:
  702. notes += "|nj=1" # Submission was rejected
  703. break
  704. return notes
  705. copyvios = self.config.tasks.get("afc_copyvios", {})
  706. regex = r"\{\{s*" + copyvios.get("template", "AfC suspected copyvio")
  707. if re.search(regex, content):
  708. notes += "|nc=1" # Submission is a suspected copyvio
  709. if not re.search(r"\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I | re.S):
  710. regex = r"(https?:)|\[//(?!{0})([^ \]\t\n\r\f\v]+?)"
  711. sitedomain = re.escape(self.site.domain)
  712. if re.search(regex.format(sitedomain), content, re.I | re.S):
  713. notes += "|ni=1" # Submission has no inline citations
  714. else:
  715. notes += "|nu=1" # Submission is completely unsourced
  716. if len(content) < 1000:
  717. notes += "|ns=1" # Submission is short
  718. statuses = self.get_statuses(content)
  719. if "D" in statuses and chart != self.CHART_MISPLACE:
  720. notes += "|nr=1" # Submission was resubmitted
  721. time_since_modify = (datetime.utcnow() - m_time).total_seconds()
  722. max_time = 4 * 24 * 60 * 60
  723. if time_since_modify > max_time:
  724. notes += "|no=1" # Submission hasn't been touched in over 4 days
  725. if chart == self.CHART_PEND and s_user:
  726. submitter = self.site.get_user(s_user)
  727. try:
  728. if submitter.blockinfo:
  729. notes += "|nb=1" # Submitter is blocked
  730. except exceptions.UserNotFoundError: # Likely an IP
  731. pass
  732. return notes