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.

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