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.

afc_statistics.py 29 KiB

11 年之前
11 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2013 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. def save(self, kwargs):
  98. """Save our local statistics to the wiki.
  99. After checking for emergency shutoff, the statistics chart is compiled,
  100. and then saved to self.pagename using self.summary iff it has changed
  101. since last save.
  102. """
  103. self.logger.info("Saving chart")
  104. if kwargs.get("fromIRC"):
  105. summary = self.summary + " (!earwigbot)"
  106. else:
  107. if self.shutoff_enabled():
  108. return
  109. summary = self.summary
  110. statistics = self.compile_charts()
  111. page = self.site.get_page(self.pagename)
  112. text = page.get()
  113. newtext = re.sub(u"<!-- stat begin -->(.*?)<!-- stat end -->",
  114. "<!-- stat begin -->\n" + statistics + "\n<!-- stat end -->",
  115. text, flags=re.DOTALL)
  116. if newtext == text:
  117. self.logger.info("Chart unchanged; not saving")
  118. return # Don't edit the page if we're not adding anything
  119. newtext = re.sub("<!-- sig begin -->(.*?)<!-- sig end -->",
  120. "<!-- sig begin -->~~~ at ~~~~~<!-- sig end -->",
  121. newtext)
  122. page.edit(newtext, summary, minor=True, bot=True)
  123. self.logger.info(u"Chart saved to [[{0}]]".format(page.title))
  124. def compile_charts(self):
  125. """Compile and return all statistics information from our local db."""
  126. stats = ""
  127. with self.conn.cursor() as cursor:
  128. cursor.execute("SELECT * FROM chart")
  129. for chart in cursor:
  130. stats += self.compile_chart(chart) + "\n"
  131. return stats[:-1] # Drop the last newline
  132. def compile_chart(self, chart_info):
  133. """Compile and return a single statistics chart."""
  134. chart_id, chart_title, special_title = chart_info
  135. chart = self.tl_header + "|" + chart_title
  136. if special_title:
  137. chart += "|" + special_title
  138. chart = "{{" + chart + "}}"
  139. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  140. with self.conn.cursor(oursql.DictCursor) as cursor:
  141. cursor.execute(query, (chart_id,))
  142. for page in cursor.fetchall():
  143. chart += "\n" + self.compile_chart_row(page)
  144. chart += "\n{{" + self.tl_footer + "}}"
  145. return chart
  146. def compile_chart_row(self, page):
  147. """Compile and return a single chart row.
  148. 'page' is a dict of page information, taken as a row from the page
  149. table, where keys are column names and values are their cell contents.
  150. """
  151. row = u"{0}|s={page_status}|t={page_title}|z={page_size}|"
  152. if page["page_special_oldid"]:
  153. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  154. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}"
  155. page["page_special_time"] = self.format_time(page["page_special_time"])
  156. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  157. if page["page_notes"]:
  158. row += "|n=1{page_notes}"
  159. return "{{" + row.format(self.tl_row, **page) + "}}"
  160. def format_time(self, dt):
  161. """Format a datetime into the standard MediaWiki timestamp format."""
  162. return dt.strftime("%H:%M, %d %b %Y")
  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.delete_old(cursor)
  185. self.logger.info("Sync completed")
  186. def update_tracked(self, cursor):
  187. """Update tracked submissions that have been changed since last sync.
  188. This is done by iterating through every page in our database and
  189. comparing our stored latest revision ID with the actual latest revision
  190. ID from an SQL query. If they differ, we will update our information
  191. about the page (self.update_page()).
  192. If the page does not exist, we will remove it from our database with
  193. self.untrack_page().
  194. """
  195. self.logger.debug("Updating tracked submissions")
  196. query = """SELECT s.page_id, s.page_title, s.page_modify_oldid,
  197. r.page_latest, r.page_title, r.page_namespace
  198. FROM page AS s
  199. LEFT JOIN {0}_p.page AS r ON s.page_id = r.page_id
  200. WHERE s.page_modify_oldid != r.page_latest
  201. OR r.page_id IS NULL"""
  202. cursor.execute(query.format(self.site.name))
  203. for pageid, title, oldid, real_oldid, real_title, real_ns in cursor:
  204. if not real_oldid:
  205. self.untrack_page(cursor, pageid)
  206. continue
  207. msg = u"Updating page [[{0}]] (id: {1}) @ {2}"
  208. self.logger.debug(msg.format(title, pageid, oldid))
  209. msg = u" {0}: oldid: {1} -> {2}"
  210. self.logger.debug(msg.format(pageid, oldid, real_oldid))
  211. real_title = real_title.decode("utf8").replace("_", " ")
  212. ns = self.site.namespace_id_to_name(real_ns)
  213. if ns:
  214. real_title = u":".join((ns, real_title))
  215. try:
  216. self.update_page(cursor, pageid, real_title)
  217. except Exception:
  218. e = u"Error updating page [[{0}]] (id: {1})"
  219. self.logger.exception(e.format(real_title, pageid))
  220. def add_untracked(self, cursor):
  221. """Add pending submissions that are not yet tracked.
  222. This is done by compiling a list of all currently tracked submissions
  223. and iterating through all members of self.pending_cat via SQL. If a
  224. page in the pending category is not tracked and is not in
  225. self.ignore_list, we will track it with self.track_page().
  226. """
  227. self.logger.debug("Adding untracked pending submissions")
  228. query = """SELECT r.page_id, r.page_title, r.page_namespace
  229. FROM {0}_p.page AS r
  230. INNER JOIN {0}_p.categorylinks AS c ON r.page_id = c.cl_from
  231. LEFT JOIN page AS s ON r.page_id = s.page_id
  232. WHERE s.page_id IS NULL AND c.cl_to = ?"""
  233. cursor.execute(query.format(self.site.name),
  234. (self.pending_cat.replace(" ", "_"),))
  235. for pageid, title, ns in cursor:
  236. title = title.decode("utf8").replace("_", " ")
  237. ns = self.site.namespace_id_to_name(ns)
  238. if ns:
  239. title = u":".join((ns, title))
  240. if title in self.ignore_list:
  241. continue
  242. msg = u"Tracking page [[{0}]] (id: {1})".format(title, pageid)
  243. self.logger.debug(msg)
  244. try:
  245. self.track_page(cursor, pageid, title)
  246. except Exception:
  247. e = u"Error tracking page [[{0}]] (id: {1})"
  248. self.logger.exception(e.format(title, pageid))
  249. def delete_old(self, cursor):
  250. """Remove old submissions from the database.
  251. "Old" is defined as a submission that has been declined or accepted
  252. more than 36 hours ago. Pending submissions cannot be "old".
  253. """
  254. self.logger.debug("Removing old submissions from chart")
  255. query = """DELETE FROM page, row USING page JOIN row
  256. ON page_id = row_id WHERE row_chart IN (?, ?)
  257. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  258. cursor.execute(query, (self.CHART_ACCEPT, self.CHART_DECLINE))
  259. def update(self, kwargs):
  260. """Update a page by name, regardless of whether anything has changed.
  261. Mainly intended as a command to be used via IRC, e.g.:
  262. !tasks start afc_statistics action=update page=Foobar
  263. """
  264. title = kwargs.get("page")
  265. if not title:
  266. return
  267. title = title.replace("_", " ").decode("utf8")
  268. query = "SELECT page_id, page_modify_oldid FROM page WHERE page_title = ?"
  269. with self.conn.cursor() as cursor:
  270. cursor.execute(query, (title,))
  271. try:
  272. pageid, oldid = cursor.fetchall()[0]
  273. except IndexError:
  274. msg = u"Page [[{0}]] not found in database".format(title)
  275. self.logger.error(msg)
  276. msg = u"Updating page [[{0}]] (id: {1}) @ {2}"
  277. self.logger.info(msg.format(title, pageid, oldid))
  278. self.update_page(cursor, pageid, title)
  279. def untrack_page(self, cursor, pageid):
  280. """Remove a page, given by ID, from our database."""
  281. self.logger.debug("Untracking page (id: {0})".format(pageid))
  282. query = """DELETE FROM page, row USING page JOIN row
  283. ON page_id = row_id WHERE page_id = ?"""
  284. cursor.execute(query, (pageid,))
  285. def track_page(self, cursor, pageid, title):
  286. """Update hook for when page is not in our database.
  287. A variety of SQL queries are used to gather information about the page,
  288. which is then saved to our database.
  289. """
  290. content = self.get_content(title)
  291. if content is None:
  292. msg = u"Could not get page content for [[{0}]]".format(title)
  293. self.logger.error(msg)
  294. return
  295. namespace = self.site.get_page(title).namespace
  296. status, chart = self.get_status_and_chart(content, namespace)
  297. if chart == self.CHART_NONE:
  298. msg = u"Could not find a status for [[{0}]]".format(title)
  299. self.logger.warn(msg)
  300. return
  301. m_user, m_time, m_id = self.get_modify(pageid)
  302. s_user, s_time, s_id = self.get_special(pageid, chart)
  303. notes = self.get_notes(chart, content, m_time, s_user)
  304. query1 = "INSERT INTO row VALUES (?, ?)"
  305. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  306. cursor.execute(query1, (pageid, chart))
  307. cursor.execute(query2, (pageid, status, title, len(content), notes,
  308. m_user, m_time, m_id, s_user, s_time, s_id))
  309. def update_page(self, cursor, pageid, title):
  310. """Update hook for when page is already in our database.
  311. A variety of SQL queries are used to gather information about the page,
  312. which is compared against our stored information. Differing information
  313. is then updated.
  314. """
  315. content = self.get_content(title)
  316. if content is None:
  317. msg = u"Could not get page content for [[{0}]]".format(title)
  318. self.logger.error(msg)
  319. return
  320. namespace = self.site.get_page(title).namespace
  321. status, chart = self.get_status_and_chart(content, namespace)
  322. if chart == self.CHART_NONE:
  323. self.untrack_page(cursor, pageid)
  324. return
  325. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  326. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  327. dict_cursor.execute(query, (pageid,))
  328. result = dict_cursor.fetchall()[0]
  329. m_user, m_time, m_id = self.get_modify(pageid)
  330. if title != result["page_title"]:
  331. self.update_page_title(cursor, result, pageid, title)
  332. if m_id != result["page_modify_oldid"]:
  333. self.update_page_modify(cursor, result, pageid, len(content),
  334. m_user, m_time, m_id)
  335. if status != result["page_status"]:
  336. special = self.update_page_status(cursor, result, pageid, status,
  337. chart)
  338. s_user = special[0]
  339. else:
  340. s_user = result["page_special_user"]
  341. notes = self.get_notes(chart, content, m_time, s_user)
  342. if notes != result["page_notes"]:
  343. self.update_page_notes(cursor, result, pageid, notes)
  344. def update_page_title(self, cursor, result, pageid, title):
  345. """Update the title of a page in our database."""
  346. query = "UPDATE page SET page_title = ? WHERE page_id = ?"
  347. cursor.execute(query, (title, pageid))
  348. msg = u" {0}: title: {1} -> {2}"
  349. self.logger.debug(msg.format(pageid, result["page_title"], title))
  350. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  351. """Update the last modified information of a page in our database."""
  352. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  353. page_modify_time = ?, page_modify_oldid = ?
  354. WHERE page_id = ?"""
  355. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  356. msg = u" {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  357. msg = msg.format(pageid, result["page_modify_user"],
  358. result["page_modify_time"],
  359. result["page_modify_oldid"], m_user, m_time, m_id)
  360. self.logger.debug(msg)
  361. def update_page_status(self, cursor, result, pageid, status, chart):
  362. """Update the status and "specialed" information of a page."""
  363. query1 = """UPDATE page JOIN row ON page_id = row_id
  364. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  365. query2 = """UPDATE page SET page_special_user = ?,
  366. page_special_time = ?, page_special_oldid = ?
  367. WHERE page_id = ?"""
  368. cursor.execute(query1, (status, chart, pageid))
  369. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  370. self.logger.debug(msg.format(pageid, result["page_status"],
  371. result["row_chart"], status, chart))
  372. s_user, s_time, s_id = self.get_special(pageid, chart)
  373. if s_id != result["page_special_oldid"]:
  374. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  375. msg = u" {0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  376. msg = msg.format(pageid, result["page_special_user"],
  377. result["page_special_time"],
  378. result["page_special_oldid"], s_user, s_time, s_id)
  379. self.logger.debug(msg)
  380. return s_user, s_time, s_id
  381. def update_page_notes(self, cursor, result, pageid, notes):
  382. """Update the notes (or warnings) of a page in our database."""
  383. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  384. cursor.execute(query, (notes, pageid))
  385. msg = " {0}: notes: {1} -> {2}"
  386. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  387. def get_content(self, title):
  388. """Get the current content of a page by title from the API.
  389. The page's current revision ID is retrieved from SQL, and then
  390. an API query is made to get its content. This is the only API query
  391. used in the task's code.
  392. """
  393. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  394. try:
  395. namespace, base = title.split(":", 1)
  396. except ValueError:
  397. base = title
  398. ns = wiki.NS_MAIN
  399. else:
  400. try:
  401. ns = self.site.namespace_name_to_id(namespace)
  402. except exceptions.NamespaceNotFoundError:
  403. base = title
  404. ns = wiki.NS_MAIN
  405. result = self.site.sql_query(query, (base.replace(" ", "_"), ns))
  406. try:
  407. revid = int(list(result)[0][0])
  408. except IndexError:
  409. return None
  410. return self.get_revision_content(revid)
  411. def get_revision_content(self, revid, tries=1):
  412. """Get the content of a revision by ID from the API."""
  413. if revid in self.revision_cache:
  414. return self.revision_cache[revid]
  415. res = self.site.api_query(action="query", prop="revisions",
  416. revids=revid, rvprop="content")
  417. try:
  418. content = res["query"]["pages"].values()[0]["revisions"][0]["*"]
  419. except KeyError:
  420. if tries > 0:
  421. sleep(5)
  422. return self.get_revision_content(revid, tries=tries - 1)
  423. self.revision_cache[revid] = content
  424. return content
  425. def get_status_and_chart(self, content, namespace):
  426. """Determine the status and chart number of an AFC submission.
  427. The methodology used here is the same one I've been using for years
  428. (see also commands.afc_report), but with the new draft system taken
  429. into account. The order here is important: if there is more than one
  430. {{AFC submission}} template on a page, we need to know which one to
  431. use (revision history search to find the most recent isn't a viable
  432. idea :P).
  433. """
  434. statuses = self.get_statuses(content)
  435. if namespace == wiki.NS_MAIN:
  436. if statuses:
  437. return None, self.CHART_MISPLACE
  438. return "a", self.CHART_ACCEPT
  439. elif "R" in statuses:
  440. return "r", self.CHART_REVIEW
  441. elif "P" in statuses:
  442. return "p", self.CHART_PEND
  443. elif "T" in statuses:
  444. return None, self.CHART_NONE
  445. elif "D" in statuses:
  446. return "d", self.CHART_DECLINE
  447. return None, self.CHART_NONE
  448. def get_statuses(self, content):
  449. """Return a list of all AFC submission statuses in a page's text."""
  450. valid = ["P", "R", "T", "D"]
  451. aliases = {
  452. "submit": "P",
  453. "afc submission/submit": "P",
  454. "afc submission/reviewing": "R",
  455. "afc submission/pending": "P",
  456. "afc submission/draft": "T",
  457. "afc submission/declined": "D"
  458. }
  459. statuses = []
  460. code = mwparserfromhell.parse(content)
  461. for template in code.filter_templates():
  462. name = template.name.strip().lower()
  463. if name == "afc submission":
  464. if template.has(1):
  465. status = template.get(1).value.strip().upper()
  466. statuses.append(status if status in valid else "P")
  467. else:
  468. statuses.append("P")
  469. elif name in aliases:
  470. statuses.append(aliases[name])
  471. return statuses
  472. def get_modify(self, pageid):
  473. """Return information about a page's last edit ("modification").
  474. This consists of the most recent editor, modification time, and the
  475. lastest revision ID.
  476. """
  477. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  478. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  479. result = self.site.sql_query(query, (pageid,))
  480. m_user, m_time, m_id = list(result)[0]
  481. timestamp = datetime.strptime(m_time, "%Y%m%d%H%M%S")
  482. return m_user.decode("utf8"), timestamp, m_id
  483. def get_special(self, pageid, chart):
  484. """Return information about a page's "special" edit.
  485. I tend to use the term "special" as a verb a lot, which is bound to
  486. cause confusion. It is merely a short way of saying "the edit in which
  487. a declined submission was declined, an accepted submission was
  488. accepted, a submission in review was set as such, a pending submission
  489. was submitted, and a "misplaced" submission was created."
  490. This "information" consists of the special edit's editor, its time, and
  491. its revision ID. If the page's status is not something that involves
  492. "special"-ing, we will return None for all three. The same will be
  493. returned if we cannot determine when the page was "special"-ed, or if
  494. it was "special"-ed more than 100 edits ago.
  495. """
  496. if chart == self.CHART_NONE:
  497. return None, None, None
  498. elif chart == self.CHART_MISPLACE:
  499. return self.get_create(pageid)
  500. elif chart == self.CHART_ACCEPT:
  501. search_with = []
  502. search_without = ["R", "P", "T", "D"]
  503. elif chart == self.CHART_PEND:
  504. search_with = ["P"]
  505. search_without = []
  506. elif chart == self.CHART_REVIEW:
  507. search_with = ["R"]
  508. search_without = []
  509. elif chart == self.CHART_DECLINE:
  510. search_with = ["D"]
  511. search_without = ["R", "P", "T"]
  512. return self.search_history(pageid, chart, search_with, search_without)
  513. def search_history(self, pageid, chart, search_with, search_without):
  514. """Search through a page's history to find when a status was set.
  515. Linear search backwards in time for the edit right after the most
  516. recent edit that fails the (pseudocode) test:
  517. ``status_set(any(search_with)) && !status_set(any(search_without))``
  518. """
  519. query = """SELECT rev_user_text, rev_timestamp, rev_id
  520. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  521. result = self.site.sql_query(query, (pageid,))
  522. counter = 0
  523. last = (None, None, None)
  524. for user, ts, revid in result:
  525. counter += 1
  526. if counter > 50:
  527. msg = "Exceeded 50 content lookups while searching history of page (id: {0}, chart: {1})"
  528. self.logger.warn(msg.format(pageid, chart))
  529. return None, None, None
  530. try:
  531. content = self.get_revision_content(revid)
  532. except exceptions.APIError:
  533. msg = "API error interrupted SQL query in search_history() for page (id: {0}, chart: {1})"
  534. self.logger.exception(msg.format(pageid, chart))
  535. return None, None, None
  536. statuses = self.get_statuses(content)
  537. req = search_with and not any([s in statuses for s in search_with])
  538. if any([s in statuses for s in search_without]) or req:
  539. return last
  540. timestamp = datetime.strptime(ts, "%Y%m%d%H%M%S")
  541. last = (user.decode("utf8"), timestamp, revid)
  542. return last
  543. def get_create(self, pageid):
  544. """Return information about a page's first edit ("creation").
  545. This consists of the page creator, creation time, and the earliest
  546. revision ID.
  547. """
  548. query = """SELECT rev_user_text, rev_timestamp, rev_id
  549. FROM revision WHERE rev_id =
  550. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  551. result = self.site.sql_query(query, (pageid,))
  552. c_user, c_time, c_id = list(result)[0]
  553. timestamp = datetime.strptime(c_time, "%Y%m%d%H%M%S")
  554. return c_user.decode("utf8"), timestamp, c_id
  555. def get_notes(self, chart, content, m_time, s_user):
  556. """Return any special notes or warnings about this page.
  557. copyvio: submission is a suspected copyright violation
  558. unsourced: submission lacks references completely
  559. no-inline: submission has no inline citations
  560. short: submission is less than a kilobyte in length
  561. resubmit: submission was resubmitted after a previous decline
  562. old: submission has not been touched in > 4 days
  563. blocked: submitter is currently blocked
  564. """
  565. notes = ""
  566. ignored_charts = [self.CHART_NONE, self.CHART_ACCEPT, self.CHART_DECLINE]
  567. if chart in ignored_charts:
  568. return notes
  569. copyvios = self.config.tasks.get("afc_copyvios", {})
  570. regex = "\{\{\s*" + copyvios.get("template", "AfC suspected copyvio")
  571. if re.search(regex, content):
  572. notes += "|nc=1" # Submission is a suspected copyvio
  573. if not re.search("\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I | re.S):
  574. regex = "(https?:)|\[//(?!{0})([^ \]\\t\\n\\r\\f\\v]+?)"
  575. sitedomain = re.escape(self.site.domain)
  576. if re.search(regex.format(sitedomain), content, re.I | re.S):
  577. notes += "|ni=1" # Submission has no inline citations
  578. else:
  579. notes += "|nu=1" # Submission is completely unsourced
  580. if len(content) < 1000:
  581. notes += "|ns=1" # Submission is short
  582. statuses = self.get_statuses(content)
  583. if "D" in statuses and chart != self.CHART_MISPLACE:
  584. notes += "|nr=1" # Submission was resubmitted
  585. time_since_modify = (datetime.utcnow() - m_time).total_seconds()
  586. max_time = 4 * 24 * 60 * 60
  587. if time_since_modify > max_time:
  588. notes += "|no=1" # Submission hasn't been touched in over 4 days
  589. if chart == self.CHART_PEND and s_user:
  590. submitter = self.site.get_user(s_user)
  591. try:
  592. if submitter.blockinfo:
  593. notes += "|nb=1" # Submitter is blocked
  594. except exceptions.UserNotFoundError: # Likely an IP
  595. pass
  596. return notes