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.

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