A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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