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.

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