Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

806 lignes
35 KiB

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