A Python robot that edits Wikipedia and interacts with people over IRC 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.

682 line
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. status, chart = self.get_status_and_chart(content)
  253. if not status:
  254. msg = "Could not find a status for [[{0}]]".format(title)
  255. self.logger.warn(msg)
  256. return
  257. short = self.get_short_title(title)
  258. size = len(content)
  259. c_user, c_time, c_id = self.get_create(pageid)
  260. m_user, m_time, m_id = self.get_modify(pageid)
  261. s_user, s_time, s_id = self.get_special(pageid, chart)
  262. notes = self.get_notes(chart, content, m_time, c_user)
  263. query1 = "INSERT INTO row VALUES (?, ?)"
  264. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  265. cursor.execute(query1, (pageid, chart))
  266. cursor.execute(query2, (pageid, status, title.decode("utf8"),
  267. short.decode("utf8"), size, notes, c_user,
  268. c_time, c_id, m_user, m_time, m_id, s_user,
  269. s_time, s_id))
  270. def update_page(self, cursor, pageid, title):
  271. """Update hook for when page is already in our database.
  272. A variety of SQL queries are used to gather information about the page,
  273. which is compared against our stored information. Differing information
  274. is then updated.
  275. """
  276. content = self.get_content(title)
  277. if not content:
  278. msg = "Could not get page content for [[{0}]]".format(title)
  279. self.logger.error(msg)
  280. return
  281. namespace = self.site.get_page(title).namespace()
  282. status, chart = self.get_status_and_chart(content, namespace)
  283. if chart == CHART_NONE:
  284. self.untrack_page(cursor, pageid)
  285. return
  286. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  287. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  288. dict_cursor.execute(query, (pageid,))
  289. result = dict_cursor.fetchall()[0]
  290. size = len(content)
  291. m_user, m_time, m_id = self.get_modify(pageid)
  292. notes = self.get_notes(chart, content, m_time, result["page_create_user"])
  293. if title != result["page_title"]:
  294. self.update_page_title(cursor, result, pageid, title)
  295. if m_id != result["page_modify_oldid"]:
  296. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  297. if status != result["page_status"]:
  298. self.update_page_status(cursor, result, pageid, status, chart)
  299. if notes != result["page_notes"]:
  300. self.update_page_notes(cursor, result, pageid, notes)
  301. def update_page_title(self, cursor, result, pageid, title):
  302. """Update the title and short_title of a page in our database."""
  303. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  304. short = self.get_short_title(title)
  305. cursor.execute(query, (title.decode("utf8"), short.decode("utf8"),
  306. pageid))
  307. msg = " {0}: title: {1} -> {2}"
  308. self.logger.debug(msg.format(pageid, result["page_title"], title))
  309. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  310. """Update the last modified information of a page in our database."""
  311. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  312. page_modify_time = ?, page_modify_oldid = ?
  313. WHERE page_id = ?"""
  314. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  315. msg = " {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  316. msg = msg.format(pageid, result["page_modify_user"],
  317. result["page_modify_time"],
  318. result["page_modify_oldid"], m_user, m_time, m_id)
  319. self.logger.debug(msg)
  320. def update_page_status(self, cursor, result, pageid, status, chart):
  321. """Update the status and "specialed" information of a page."""
  322. query1 = """UPDATE page JOIN row ON page_id = row_id
  323. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  324. query2 = """UPDATE page SET page_special_user = ?,
  325. page_special_time = ?, page_special_oldid = ?
  326. WHERE page_id = ?"""
  327. cursor.execute(query1, (status, chart, pageid))
  328. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  329. self.logger.debug(msg.format(pageid, result["page_status"],
  330. result["row_chart"], status, chart))
  331. s_user, s_time, s_id = self.get_special(pageid, chart)
  332. if s_id != result["page_special_oldid"]:
  333. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  334. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  335. msg = msg.format(pageid, result["page_special_user"],
  336. result["page_special_time"],
  337. result["page_special_oldid"], s_user, s_time, s_id)
  338. self.logger.debug(msg)
  339. def update_page_notes(self, cursor, result, pageid, notes):
  340. """Update the notes (or warnings) of a page in our database."""
  341. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  342. cursor.execute(query, (notes, pageid))
  343. msg = " {0}: notes: {1} -> {2}"
  344. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  345. def get_content(self, title):
  346. """Get the current content of a page by title from the API.
  347. The page's current revision ID is retrieved from SQL, and then
  348. an API query is made to get its content. This is the only API query
  349. used in the task's code.
  350. """
  351. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  352. try:
  353. namespace, base = title.decode("utf8").split(":", 1)
  354. except ValueError:
  355. base = title.decode("utf8")
  356. ns = wiki.NS_MAIN
  357. else:
  358. try:
  359. ns = self.site.namespace_name_to_id(namespace)
  360. except wiki.NamespaceNotFoundError:
  361. base = title.decode("utf8")
  362. ns = wiki.NS_MAIN
  363. result = self.site.sql_query(query, (base.replace(" ", "_"), ns))
  364. revid = int(list(result)[0][0])
  365. return self.get_revision_content(revid)
  366. def get_revision_content(self, revid):
  367. """Get the content of a revision by ID from the API."""
  368. res = self.site.api_query(action="query", prop="revisions",
  369. revids=revid, rvprop="content")
  370. try:
  371. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  372. except KeyError:
  373. sleep(5)
  374. res = self.site.api_query(action="query", prop="revisions",
  375. revids=revid, rvprop="content")
  376. try:
  377. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  378. except KeyError:
  379. return None
  380. def get_status_and_chart(self, content, namespace):
  381. """Determine the status and chart number of an AFC submission.
  382. The methodology used here is the same one I've been using for years
  383. (see also commands.afc_report), but with the new draft system taken
  384. into account. The order here is important: if there is more than one
  385. {{AFC submission}} template on a page, we need to know which one to
  386. use (revision history search to find the most recent isn't a viable
  387. idea :P).
  388. """
  389. statuses = self.get_statuses(content)
  390. if "R" in statuses:
  391. status, chart = "r", CHART_REVIEW
  392. elif "H" in statuses:
  393. status, chart = "p", CHART_DRAFT
  394. elif "P" in statuses:
  395. status, chart = "p", CHART_PEND
  396. elif "T" in statuses:
  397. status, chart = None, CHART_MISPLACE
  398. elif "D" in statuses:
  399. status, chart = "d", CHART_DECLINE
  400. else:
  401. status, chart = None, CHART_NONE
  402. if namespace == wiki.NS_MAIN:
  403. if chart == CHART_NONE:
  404. status, chart = "a", CHART_ACCEPT
  405. else:
  406. status, chart = None, CHART_MISPLACE
  407. return status
  408. def get_statuses(self, content):
  409. """Return a list of all AFC submission statuses in a page's text."""
  410. re_has_templates = "\{\{[aA][fF][cC] submission\s*(\}\}|\||/)"
  411. re_template = "\{\{[aA][fF][cC] submission\s*(.*?)\}\}"
  412. re_remove_embed = "(\{\{[aA][fF][cC] submission\s*(.*?))\{\{(.*?)\}\}(.*?)\}\}"
  413. valid = ["R", "H", "P", "T", "D"]
  414. subtemps = {
  415. "/reviewing": "R",
  416. "/onhold": "H",
  417. "/pending": "P",
  418. "/draft": "T",
  419. "/declined": "D"
  420. }
  421. statuses = []
  422. while re.search(re_has_templates, content):
  423. status = "P"
  424. match = re.search(re_template, content, re.S)
  425. if not match:
  426. return statuses
  427. temp = match.group(1)
  428. limit = 0
  429. while "{{" in temp and limit < 50:
  430. content = re.sub(re_remove_embed, "\\1\\4}}", content, 1, re.S)
  431. match = re.search(re_template, content, re.S)
  432. temp = match.group(1)
  433. limit += 1
  434. params = temp.split("|")
  435. try:
  436. subtemp, params = params[0].strip(), params[1:]
  437. except IndexError:
  438. status = "P"
  439. params = []
  440. else:
  441. if subtemp:
  442. status = subtemps.get(subtemp)
  443. params = []
  444. for param in params:
  445. param = param.strip().upper()
  446. if "=" in param:
  447. key, value = param.split("=", 1)
  448. if key.strip() == "1":
  449. status = value if value in valid else "P"
  450. break
  451. else:
  452. status = param if param in valid else "P"
  453. break
  454. statuses.append(status)
  455. content = re.sub(re_template, "", content, 1, re.S)
  456. return statuses
  457. def get_short_title(self, title):
  458. """Shorten a title so we can display it in a chart using less space.
  459. Basically, this just means removing the "Wikipedia talk:Articles for
  460. creation" part from the beginning. If it is longer than 50 characters,
  461. we'll shorten it down to 47 and add an poor-man's ellipsis at the end.
  462. """
  463. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  464. if len(short) > 50:
  465. short = "".join((short[:47], "..."))
  466. return short
  467. def get_create(self, pageid):
  468. """Return information about a page's first edit ("creation").
  469. This consists of the page creator, creation time, and the earliest
  470. revision ID.
  471. """
  472. query = """SELECT rev_user_text, rev_timestamp, rev_id
  473. FROM revision WHERE rev_id =
  474. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  475. result = self.site.sql_query(query, (pageid,))
  476. c_user, c_time, c_id = list(result)[0]
  477. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  478. def get_modify(self, pageid):
  479. """Return information about a page's last edit ("modification").
  480. This consists of the most recent editor, modification time, and the
  481. lastest revision ID.
  482. """
  483. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  484. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  485. result = self.site.sql_query(query, (pageid,))
  486. m_user, m_time, m_id = list(result)[0]
  487. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  488. def get_special(self, pageid, chart):
  489. """Return information about a page's "special" edit.
  490. I tend to use the term "special" as a verb a lot, which is bound to
  491. cause confusion. It is merely a short way of saying "the edit in which
  492. a declined submission was declined, an accepted submission was
  493. accepted, a submission in review was set as such, and a pending draft
  494. was submitted."
  495. This "information" consists of the special edit's editor, its time, and
  496. its revision ID. If the page's status is not something that involves
  497. "special"-ing, we will return None for all three. The same will be
  498. returned if we cannot determine when the page was "special"-ed, or if
  499. it was "special"-ed more than 250 edits ago.
  500. """
  501. if chart in [CHART_NONE, CHART_MISPLACE]:
  502. return None, None, None
  503. elif chart == CHART_ACCEPT:
  504. search_for = None
  505. search_not = ["R", "H", "P", "T", "D"]
  506. elif chart == CHART_DRAFT:
  507. search_for = "H"
  508. search_not = []
  509. elif chart == CHART_PEND:
  510. search_for = "P"
  511. search_not = []
  512. elif chart == CHART_REVIEW:
  513. search_for = "R"
  514. search_not = []
  515. elif chart == CHART_DECLINE:
  516. search_for = "D"
  517. search_not = ["R", "H", "P", "T"]
  518. query = """SELECT rev_user_text, rev_timestamp, rev_id
  519. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  520. result = self.site.sql_query(query, (pageid,))
  521. counter = 0
  522. last = (None, None, None)
  523. for user, ts, revid in result:
  524. counter += 1
  525. if counter > 100:
  526. msg = "Exceeded 100 content lookups while determining special for page (id: {0}, chart: {1})"
  527. self.logger.warn(msg.format(pageid, chart))
  528. return None, None, None
  529. content = self.get_revision_content(revid)
  530. statuses = self.get_statuses(content)
  531. matches = [s in statuses for s in search_not]
  532. if search_for:
  533. if search_for not in statuses or any(matches):
  534. return last
  535. else:
  536. if any(matches):
  537. return last
  538. last = (user, datetime.strptime(ts, "%Y%m%d%H%M%S"), revid)
  539. return last
  540. def get_notes(self, chart, content, m_time, c_user):
  541. """Return any special notes or warnings about this page.
  542. resubmit: submission was resubmitted after a previous decline
  543. short: submission is fewer than 500 bytes
  544. no-inline: submission has no inline citations
  545. unsourced: submission lacks references completely
  546. old: submission has not been touched in > 4 days
  547. blocked: submitter is currently blocked
  548. """
  549. notes = ""
  550. ignored_charts = [CHART_ACCEPT, CHART_DECLINE]
  551. if chart in ignored_charts:
  552. return notes
  553. statuses = self.get_statuses(content)
  554. if "D" in statuses:
  555. notes += "|nr=1" # Submission was resubmitted
  556. if len(content) < 500:
  557. notes += "|ns=1" # Submission is short
  558. if not re.search("\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I|re.S):
  559. if re.search("https?:\/\/(.*?)\.", content, re.I|re.S):
  560. notes += "|ni=1" # Submission has no inline citations
  561. else:
  562. notes += "|nu=1" # Submission is completely unsourced
  563. time_since_modify = (datetime.now() - m_time).seconds
  564. max_time = 4 * 24 * 60 * 60
  565. if time_since_modify > max_time:
  566. notes += "|no=1" # Submission hasn't been touched in over 4 days
  567. creator = self.site.get_user(c_user)
  568. try:
  569. if creator.blockinfo():
  570. notes += "|nb=1" # Submitter is blocked
  571. except wiki.UserNotFoundError: # Likely an IP
  572. pass
  573. return notes