A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

687 linhas
28 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. import logging
  4. import re
  5. from os.path import expanduser
  6. from threading import Lock
  7. from time import sleep
  8. import oursql
  9. from classes import BaseTask
  10. import config
  11. import wiki
  12. # Chart status number constants:
  13. CHART_NONE = 0
  14. CHART_PEND = 1
  15. CHART_DRAFT = 2
  16. CHART_REVIEW = 3
  17. CHART_ACCEPT = 4
  18. CHART_DECLINE = 5
  19. CHART_MISPLACE = 6
  20. class Task(BaseTask):
  21. """A task to generate statistics for WikiProject Articles for Creation.
  22. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  23. accessed with oursql. Statistics are synchronied with the live database
  24. every four minutes and saved once an hour, on the hour, to self.pagename.
  25. In the live bot, this is "Template:AFC statistics".
  26. """
  27. name = "afc_statistics"
  28. number = 2
  29. def __init__(self):
  30. self.cfg = cfg = config.tasks.get(self.name, {})
  31. # Set some wiki-related attributes:
  32. self.pagename = cfg.get("page", "Template:AFC statistics")
  33. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  34. self.ignore_list = cfg.get("ignore_list", [])
  35. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  36. self.summary = self.make_summary(cfg.get("summary", default_summary))
  37. # Templates used in chart generation:
  38. templates = cfg.get("templates", {})
  39. self.tl_header = templates.get("header", "AFC statistics/header")
  40. self.tl_row = templates.get("row", "AFC statistics/row")
  41. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  42. # Connection data for our SQL database:
  43. kwargs = cfg.get("sql", {})
  44. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  45. self.conn_data = kwargs
  46. self.db_access_lock = Lock()
  47. def run(self, **kwargs):
  48. """Entry point for a task event.
  49. Depending on the kwargs passed, we will either synchronize our local
  50. statistics database with the site (self.sync()) or save it to the wiki
  51. (self.save()). We will additionally create an SQL connection with our
  52. local database.
  53. """
  54. self.site = wiki.get_site()
  55. with self.db_access_lock:
  56. self.conn = oursql.connect(**self.conn_data)
  57. action = kwargs.get("action")
  58. try:
  59. if action == "save":
  60. self.save(**kwargs)
  61. elif action == "sync":
  62. self.sync(**kwargs)
  63. elif action == "update":
  64. self.update(**kwargs)
  65. finally:
  66. self.conn.close()
  67. def save(self, **kwargs):
  68. """Save our local statistics to the wiki.
  69. After checking for emergency shutoff, the statistics chart is compiled,
  70. and then saved to self.pagename using self.summary iff it has changed
  71. since last save.
  72. """
  73. self.logger.info("Saving chart")
  74. if kwargs.get("fromIRC"):
  75. summary = " ".join((self.summary, "(!earwigbot)"))
  76. else:
  77. if self.shutoff_enabled():
  78. return
  79. summary = self.summary
  80. statistics = self.compile_charts().encode("utf8")
  81. page = self.site.get_page(self.pagename)
  82. text = page.get().encode("utf8")
  83. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  84. statistics.join(("\\1\n", "\n\\3")), text,
  85. flags=re.DOTALL)
  86. if newtext == text:
  87. self.logger.info("Chart unchanged; not saving")
  88. return # Don't edit the page if we're not adding anything
  89. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  90. "\\1~~~ at ~~~~~\\3", newtext)
  91. page.edit(newtext, summary, minor=True, bot=True)
  92. self.logger.info("Chart saved to [[{0}]]".format(page.title()))
  93. def compile_charts(self):
  94. """Compile and return all statistics information from our local db."""
  95. stats = ""
  96. with self.conn.cursor() as cursor:
  97. cursor.execute("SELECT * FROM chart")
  98. for chart in cursor:
  99. stats += self.compile_chart(chart) + "\n"
  100. return stats[:-1] # Drop the last newline
  101. def compile_chart(self, chart_info):
  102. """Compile and return a single statistics chart."""
  103. chart_id, chart_title, special_title = chart_info
  104. chart = "|".join((self.tl_header, chart_title))
  105. if special_title:
  106. chart += "".join(("|", special_title))
  107. chart = "".join(("{{", chart, "}}"))
  108. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  109. with self.conn.cursor(oursql.DictCursor) as cursor:
  110. cursor.execute(query, (chart_id,))
  111. for page in cursor:
  112. chart += "\n" + self.compile_chart_row(page).decode("utf8")
  113. chart += "".join(("\n{{", self.tl_footer, "}}"))
  114. return chart
  115. def compile_chart_row(self, page):
  116. """Compile and return a single chart row.
  117. 'page' is a dict of page information, taken as a row from the page
  118. table, where keys are column names and values are their cell contents.
  119. """
  120. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  121. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  122. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  123. page["page_create_time"] = self.format_time(page["page_create_time"])
  124. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  125. if page["page_special_user"]:
  126. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  127. page["page_special_time"] = self.format_time(page["page_special_time"])
  128. if page["page_notes"]:
  129. row += "n=1{page_notes}"
  130. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  131. def format_time(self, timestamp):
  132. """Format a datetime into the standard MediaWiki timestamp format."""
  133. return timestamp.strftime("%H:%M, %d %b %Y")
  134. def sync(self, **kwargs):
  135. """Synchronize our local statistics database with the site.
  136. Syncing involves, in order, updating tracked submissions that have
  137. been changed since last sync (self.update_tracked()), adding pending
  138. submissions that are not tracked (self.add_untracked()), and removing
  139. old submissions from the database (self.delete_old()).
  140. The sync will be canceled if SQL replication lag is greater than 600
  141. seconds, because this will lead to potential problems and outdated
  142. data, not to mention putting demand on an already overloaded server.
  143. Giving sync the kwarg "ignore_replag" will go around this restriction.
  144. """
  145. self.logger.info("Starting sync")
  146. replag = self.site.get_replag()
  147. self.logger.debug("Server replag is {0}".format(replag))
  148. if replag > 600 and not kwargs.get("ignore_replag"):
  149. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes."
  150. self.logger.warn(msg.format(replag))
  151. with self.conn.cursor() as cursor:
  152. self.update_tracked(cursor)
  153. self.add_untracked(cursor)
  154. self.delete_old(cursor)
  155. self.logger.info("Sync completed")
  156. def update_tracked(self, cursor):
  157. """Update tracked submissions that have been changed since last sync.
  158. This is done by iterating through every page in our database and
  159. comparing our stored latest revision ID with the actual latest revision
  160. ID from an SQL query. If they differ, we will update our information
  161. about the page (self.update_page()).
  162. If the page does not exist, we will remove it from our database with
  163. self.untrack_page().
  164. """
  165. self.logger.debug("Updating tracked submissions")
  166. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  167. query2 = """SELECT page_latest, page_title, page_namespace FROM page
  168. WHERE page_id = ?"""
  169. cursor.execute(query1)
  170. for pageid, title, oldid in cursor:
  171. result = list(self.site.sql_query(query2, (pageid,)))
  172. if not result:
  173. self.untrack_page(cursor, pageid)
  174. continue
  175. real_oldid = result[0][0]
  176. if oldid != real_oldid:
  177. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  178. self.logger.debug(msg.format(title, pageid, oldid))
  179. self.logger.debug(" {0} -> {1}".format(oldid, real_oldid))
  180. body = result[0][1].replace("_", " ")
  181. ns = self.site.namespace_id_to_name(result[0][2])
  182. if ns:
  183. real_title = ":".join((str(ns), body))
  184. else:
  185. real_title = body
  186. self.update_page(cursor, pageid, real_title)
  187. def add_untracked(self, cursor):
  188. """Add pending submissions that are not yet tracked.
  189. This is done by compiling a list of all currently tracked submissions
  190. and iterating through all members of self.pending_cat via SQL. If a
  191. page in the pending category is not tracked and is not in
  192. self.ignore_list, we will track it with self.track_page().
  193. """
  194. self.logger.debug("Adding untracked pending submissions")
  195. cursor.execute("SELECT page_id FROM page")
  196. tracked = [i[0] for i in cursor.fetchall()]
  197. category = self.site.get_category(self.pending_cat)
  198. pending = category.members(use_sql=True)
  199. for title, pageid in pending:
  200. if title.decode("utf8") in self.ignore_list:
  201. continue
  202. if pageid not in tracked:
  203. msg = "Tracking page [[{0}]] (id: {1})".format(title, pageid)
  204. self.logger.debug(msg)
  205. self.track_page(cursor, pageid, title)
  206. def delete_old(self, cursor):
  207. """Remove old submissions from the database.
  208. "Old" is defined as a submission that has been declined or accepted
  209. more than 36 hours ago. Pending submissions cannot be "old".
  210. """
  211. self.logger.debug("Removing old submissions from chart")
  212. query = """DELETE FROM page, row USING page JOIN row
  213. ON page_id = row_id WHERE row_chart IN (?, ?)
  214. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  215. cursor.execute(query, (CHART_ACCEPT, CHART_DECLINE))
  216. def update(self, **kwargs):
  217. """Update a page by name, regardless of whether anything has changed.
  218. Mainly intended as a command to be used via IRC, e.g.:
  219. !tasks start afc_statistics action=update page=Foobar
  220. """
  221. title = kwargs.get("page")
  222. if not title:
  223. return
  224. title = title.replace("_", " ")
  225. query = "SELECT page_id, page_modify_oldid FROM page WHERE page_title = ?"
  226. with self.conn.cursor() as cursor:
  227. cursor.execute(query, (title,))
  228. try:
  229. pageid, oldid = cursor.fetchall()[0]
  230. except IndexError:
  231. msg = "Page [[{0}]] not found in database".format(title)
  232. self.logger.error(msg)
  233. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  234. self.logger.info(msg.format(title, pageid, oldid))
  235. self.update_page(cursor, pageid, title)
  236. def untrack_page(self, cursor, pageid):
  237. """Remove a page, given by ID, from our database."""
  238. self.logger.debug("Untracking page (id: {0})".format(pageid))
  239. query = """DELETE FROM page, row USING page JOIN row
  240. ON page_id = row_id WHERE page_id = ?"""
  241. cursor.execute(query, (pageid,))
  242. def track_page(self, cursor, pageid, title):
  243. """Update hook for when page is not in our database.
  244. A variety of SQL queries are used to gather information about the page,
  245. which are then saved to our database.
  246. """
  247. content = self.get_content(title)
  248. if not content:
  249. msg = "Could not get page content for [[{0}]]".format(title)
  250. self.logger.error(msg)
  251. return
  252. namespace = self.site.get_page(title).namespace()
  253. status, chart = self.get_status_and_chart(content, namespace)
  254. if chart == CHART_NONE:
  255. msg = "Could not find a status for [[{0}]]".format(title)
  256. self.logger.warn(msg)
  257. return
  258. short = self.get_short_title(title)
  259. size = self.get_size(content)
  260. c_user, c_time, c_id = self.get_create(pageid)
  261. m_user, m_time, m_id = self.get_modify(pageid)
  262. s_user, s_time, s_id = self.get_special(pageid, chart)
  263. notes = self.get_notes(chart, content, m_time, c_user)
  264. query1 = "INSERT INTO row VALUES (?, ?)"
  265. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  266. cursor.execute(query1, (pageid, chart))
  267. cursor.execute(query2, (pageid, status, title.decode("utf8"),
  268. short.decode("utf8"), size, notes, c_user,
  269. c_time, c_id, m_user, m_time, m_id, s_user,
  270. s_time, s_id))
  271. def update_page(self, cursor, pageid, title):
  272. """Update hook for when page is already in our database.
  273. A variety of SQL queries are used to gather information about the page,
  274. which is compared against our stored information. Differing information
  275. is then updated.
  276. """
  277. content = self.get_content(title)
  278. if not content:
  279. msg = "Could not get page content for [[{0}]]".format(title)
  280. self.logger.error(msg)
  281. return
  282. namespace = self.site.get_page(title).namespace()
  283. status, chart = self.get_status_and_chart(content, namespace)
  284. if chart == CHART_NONE:
  285. self.untrack_page(cursor, pageid)
  286. return
  287. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  288. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  289. dict_cursor.execute(query, (pageid,))
  290. result = dict_cursor.fetchall()[0]
  291. size = self.get_size(content)
  292. m_user, m_time, m_id = self.get_modify(pageid)
  293. notes = self.get_notes(chart, content, m_time, result["page_create_user"])
  294. if title != result["page_title"]:
  295. self.update_page_title(cursor, result, pageid, title)
  296. if m_id != result["page_modify_oldid"]:
  297. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  298. if status != result["page_status"]:
  299. self.update_page_status(cursor, result, pageid, status, chart)
  300. if notes != result["page_notes"]:
  301. self.update_page_notes(cursor, result, pageid, notes)
  302. def update_page_title(self, cursor, result, pageid, title):
  303. """Update the title and short_title of a page in our database."""
  304. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  305. short = self.get_short_title(title)
  306. cursor.execute(query, (title.decode("utf8"), short.decode("utf8"),
  307. pageid))
  308. msg = " {0}: title: {1} -> {2}"
  309. self.logger.debug(msg.format(pageid, result["page_title"], title))
  310. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  311. """Update the last modified information of a page in our database."""
  312. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  313. page_modify_time = ?, page_modify_oldid = ?
  314. WHERE page_id = ?"""
  315. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  316. msg = " {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  317. msg = msg.format(pageid, result["page_modify_user"],
  318. result["page_modify_time"],
  319. result["page_modify_oldid"], m_user, m_time, m_id)
  320. self.logger.debug(msg)
  321. def update_page_status(self, cursor, result, pageid, status, chart):
  322. """Update the status and "specialed" information of a page."""
  323. query1 = """UPDATE page JOIN row ON page_id = row_id
  324. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  325. query2 = """UPDATE page SET page_special_user = ?,
  326. page_special_time = ?, page_special_oldid = ?
  327. WHERE page_id = ?"""
  328. cursor.execute(query1, (status, chart, pageid))
  329. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  330. self.logger.debug(msg.format(pageid, result["page_status"],
  331. result["row_chart"], status, chart))
  332. s_user, s_time, s_id = self.get_special(pageid, chart)
  333. if s_id != result["page_special_oldid"]:
  334. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  335. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  336. msg = msg.format(pageid, result["page_special_user"],
  337. result["page_special_time"],
  338. result["page_special_oldid"], s_user, s_time, s_id)
  339. self.logger.debug(msg)
  340. def update_page_notes(self, cursor, result, pageid, notes):
  341. """Update the notes (or warnings) of a page in our database."""
  342. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  343. cursor.execute(query, (notes, pageid))
  344. msg = " {0}: notes: {1} -> {2}"
  345. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  346. def get_content(self, title):
  347. """Get the current content of a page by title from the API.
  348. The page's current revision ID is retrieved from SQL, and then
  349. an API query is made to get its content. This is the only API query
  350. used in the task's code.
  351. """
  352. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  353. try:
  354. namespace, base = title.decode("utf8").split(":", 1)
  355. except ValueError:
  356. base = title.decode("utf8")
  357. ns = wiki.NS_MAIN
  358. else:
  359. try:
  360. ns = self.site.namespace_name_to_id(namespace)
  361. except wiki.NamespaceNotFoundError:
  362. base = title.decode("utf8")
  363. ns = wiki.NS_MAIN
  364. result = self.site.sql_query(query, (base.replace(" ", "_"), ns))
  365. revid = int(list(result)[0][0])
  366. return self.get_revision_content(revid)
  367. def get_revision_content(self, revid):
  368. """Get the content of a revision by ID from the API."""
  369. res = self.site.api_query(action="query", prop="revisions",
  370. revids=revid, rvprop="content")
  371. try:
  372. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  373. except KeyError:
  374. sleep(5)
  375. res = self.site.api_query(action="query", prop="revisions",
  376. revids=revid, rvprop="content")
  377. try:
  378. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  379. except KeyError:
  380. return None
  381. def get_status_and_chart(self, content, namespace):
  382. """Determine the status and chart number of an AFC submission.
  383. The methodology used here is the same one I've been using for years
  384. (see also commands.afc_report), but with the new draft system taken
  385. into account. The order here is important: if there is more than one
  386. {{AFC submission}} template on a page, we need to know which one to
  387. use (revision history search to find the most recent isn't a viable
  388. idea :P).
  389. """
  390. statuses = self.get_statuses(content)
  391. if "R" in statuses:
  392. status, chart = "r", CHART_REVIEW
  393. elif "H" in statuses:
  394. status, chart = "p", CHART_DRAFT
  395. elif "P" in statuses:
  396. status, chart = "p", CHART_PEND
  397. elif "T" in statuses:
  398. status, chart = None, CHART_MISPLACE
  399. elif "D" in statuses:
  400. status, chart = "d", CHART_DECLINE
  401. else:
  402. status, chart = None, CHART_NONE
  403. if namespace == wiki.NS_MAIN:
  404. if chart == CHART_NONE:
  405. status, chart = "a", CHART_ACCEPT
  406. else:
  407. status, chart = None, CHART_MISPLACE
  408. return status, chart
  409. def get_statuses(self, content):
  410. """Return a list of all AFC submission statuses in a page's text."""
  411. re_has_templates = "\{\{[aA][fF][cC] submission\s*(\}\}|\||/)"
  412. re_template = "\{\{[aA][fF][cC] submission\s*(.*?)\}\}"
  413. re_remove_embed = "(\{\{[aA][fF][cC] submission\s*(.*?))\{\{(.*?)\}\}(.*?)\}\}"
  414. valid = ["R", "H", "P", "T", "D"]
  415. subtemps = {
  416. "/reviewing": "R",
  417. "/onhold": "H",
  418. "/pending": "P",
  419. "/draft": "T",
  420. "/declined": "D"
  421. }
  422. statuses = []
  423. while re.search(re_has_templates, content):
  424. status = "P"
  425. match = re.search(re_template, content, re.S)
  426. if not match:
  427. return statuses
  428. temp = match.group(1)
  429. limit = 0
  430. while "{{" in temp and limit < 50:
  431. content = re.sub(re_remove_embed, "\\1\\4}}", content, 1, re.S)
  432. match = re.search(re_template, content, re.S)
  433. temp = match.group(1)
  434. limit += 1
  435. params = temp.split("|")
  436. try:
  437. subtemp, params = params[0].strip(), params[1:]
  438. except IndexError:
  439. status = "P"
  440. params = []
  441. else:
  442. if subtemp:
  443. status = subtemps.get(subtemp)
  444. params = []
  445. for param in params:
  446. param = param.strip().upper()
  447. if "=" in param:
  448. key, value = param.split("=", 1)
  449. if key.strip() == "1":
  450. status = value if value in valid else "P"
  451. break
  452. else:
  453. status = param if param in valid else "P"
  454. break
  455. statuses.append(status)
  456. content = re.sub(re_template, "", content, 1, re.S)
  457. return statuses
  458. def get_short_title(self, title):
  459. """Shorten a title so we can display it in a chart using less space.
  460. Basically, this just means removing the "Wikipedia talk:Articles for
  461. creation" part from the beginning. If it is longer than 50 characters,
  462. we'll shorten it down to 47 and add an poor-man's ellipsis at the end.
  463. """
  464. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  465. if len(short) > 50:
  466. short = "".join((short[:47], "..."))
  467. return short
  468. def get_size(self, content):
  469. """Return a page's size in a short, pretty format."""
  470. return "{0} kB".format(round(len(content) / 1000.0, 2))
  471. def get_create(self, pageid):
  472. """Return information about a page's first edit ("creation").
  473. This consists of the page creator, creation time, and the earliest
  474. revision ID.
  475. """
  476. query = """SELECT rev_user_text, rev_timestamp, rev_id
  477. FROM revision WHERE rev_id =
  478. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  479. result = self.site.sql_query(query, (pageid,))
  480. c_user, c_time, c_id = list(result)[0]
  481. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  482. def get_modify(self, pageid):
  483. """Return information about a page's last edit ("modification").
  484. This consists of the most recent editor, modification time, and the
  485. lastest revision ID.
  486. """
  487. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  488. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  489. result = self.site.sql_query(query, (pageid,))
  490. m_user, m_time, m_id = list(result)[0]
  491. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  492. def get_special(self, pageid, 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, and a pending draft
  498. was submitted."
  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, or if
  503. it was "special"-ed more than 250 edits ago.
  504. """
  505. if chart in [CHART_NONE, CHART_MISPLACE]:
  506. return None, None, None
  507. elif chart == CHART_ACCEPT:
  508. search_for = None
  509. search_not = ["R", "H", "P", "T", "D"]
  510. elif chart == CHART_DRAFT:
  511. search_for = "H"
  512. search_not = []
  513. elif chart == CHART_PEND:
  514. search_for = "P"
  515. search_not = []
  516. elif chart == CHART_REVIEW:
  517. search_for = "R"
  518. search_not = []
  519. elif chart == CHART_DECLINE:
  520. search_for = "D"
  521. search_not = ["R", "H", "P", "T"]
  522. query = """SELECT rev_user_text, rev_timestamp, rev_id
  523. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  524. result = self.site.sql_query(query, (pageid,))
  525. counter = 0
  526. last = (None, None, None)
  527. for user, ts, revid in result:
  528. counter += 1
  529. if counter > 100:
  530. msg = "Exceeded 100 content lookups while determining special for page (id: {0}, chart: {1})"
  531. self.logger.warn(msg.format(pageid, chart))
  532. return None, None, None
  533. content = self.get_revision_content(revid)
  534. statuses = self.get_statuses(content)
  535. matches = [s in statuses for s in search_not]
  536. if search_for:
  537. if search_for not in statuses or any(matches):
  538. return last
  539. else:
  540. if any(matches):
  541. return last
  542. last = (user, datetime.strptime(ts, "%Y%m%d%H%M%S"), revid)
  543. return last
  544. def get_notes(self, chart, content, m_time, c_user):
  545. """Return any special notes or warnings about this page.
  546. resubmit: submission was resubmitted after a previous decline
  547. short: submission is fewer than 500 bytes
  548. no-inline: submission has no inline citations
  549. unsourced: submission lacks references completely
  550. old: submission has not been touched in > 4 days
  551. blocked: submitter is currently blocked
  552. """
  553. notes = ""
  554. ignored_charts = [CHART_ACCEPT, CHART_DECLINE]
  555. if chart in ignored_charts:
  556. return notes
  557. statuses = self.get_statuses(content)
  558. if "D" in statuses:
  559. notes += "|nr=1" # Submission was resubmitted
  560. if len(content) < 500:
  561. notes += "|ns=1" # Submission is short
  562. if not re.search("\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I|re.S):
  563. if re.search("https?:\/\/(.*?)\.", content, re.I|re.S):
  564. notes += "|ni=1" # Submission has no inline citations
  565. else:
  566. notes += "|nu=1" # Submission is completely unsourced
  567. time_since_modify = (datetime.now() - m_time).seconds
  568. max_time = 4 * 24 * 60 * 60
  569. if time_since_modify > max_time:
  570. notes += "|no=1" # Submission hasn't been touched in over 4 days
  571. creator = self.site.get_user(c_user)
  572. try:
  573. if creator.blockinfo():
  574. notes += "|nb=1" # Submitter is blocked
  575. except wiki.UserNotFoundError: # Likely an IP
  576. pass
  577. return notes