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.

766 lines
33 KiB

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