A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

afc_statistics.py 25 KiB

13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
13 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. finally:
  63. self.conn.close()
  64. def save(self, **kwargs):
  65. """Save our local statistics to the wiki.
  66. After checking for emergency shutoff, the statistics chart is compiled,
  67. and then saved to self.pagename using self.summary iff it has changed
  68. since last save.
  69. """
  70. self.logger.info("Saving chart")
  71. if kwargs.get("fromIRC"):
  72. summary = " ".join((self.summary, "(!earwigbot)"))
  73. else:
  74. if self.shutoff_enabled():
  75. return
  76. summary = self.summary
  77. statistics = self.compile_charts().encode("utf8")
  78. page = self.site.get_page(self.pagename)
  79. text = page.get().encode("utf8")
  80. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  81. statistics.join(("\\1\n", "\n\\3")), text,
  82. flags=re.DOTALL)
  83. if newtext == text:
  84. self.logger.info("Chart unchanged; not saving")
  85. return # Don't edit the page if we're not adding anything
  86. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  87. "\\1~~~ at ~~~~~\\3", newtext)
  88. page.edit(newtext, summary, minor=True, bot=True)
  89. self.logger.info("Chart saved to [[{0}]]".format(page.title()))
  90. def compile_charts(self):
  91. """Compile and return all statistics information from our local db."""
  92. stats = ""
  93. with self.conn.cursor() as cursor:
  94. cursor.execute("SELECT * FROM chart")
  95. for chart in cursor:
  96. stats += self.compile_chart(chart) + "\n"
  97. return stats[:-1] # Drop the last newline
  98. def compile_chart(self, chart_info):
  99. """Compile and return a single statistics chart."""
  100. chart_id, chart_title, special_title = chart_info
  101. chart = "|".join((self.tl_header, chart_title))
  102. if special_title:
  103. chart += "".join(("|", special_title))
  104. chart = "".join(("{{", chart, "}}"))
  105. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  106. with self.conn.cursor(oursql.DictCursor) as cursor:
  107. cursor.execute(query, (chart_id,))
  108. for page in cursor:
  109. chart += "\n" + self.compile_chart_row(page).decode("utf8")
  110. chart += "".join(("\n{{", self.tl_footer, "}}"))
  111. return chart
  112. def compile_chart_row(self, page):
  113. """Compile and return a single chart row.
  114. 'page' is a dict of page information, taken as a row from the page
  115. table, where keys are column names and values are their cell contents.
  116. """
  117. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  118. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  119. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  120. page["page_create_time"] = self.format_time(page["page_create_time"])
  121. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  122. if page["page_special_user"]:
  123. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  124. page["page_special_time"] = self.format_time(page["page_special_time"])
  125. if page["page_notes"]:
  126. row += "n=1{page_notes}"
  127. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  128. def format_time(self, timestamp):
  129. """Format a datetime into the standard MediaWiki timestamp format."""
  130. return timestamp.strftime("%H:%M, %d %B %Y")
  131. def sync(self, **kwargs):
  132. """Synchronize our local statistics database with the site.
  133. Syncing involves, in order, updating tracked submissions that have
  134. been changed since last sync (self.update_tracked()), adding pending
  135. submissions that are not tracked (self.add_untracked()), and removing
  136. old submissions from the database (self.delete_old()).
  137. The sync will be canceled if SQL replication lag is greater than 600
  138. seconds, because this will lead to potential problems and outdated
  139. data, not to mention putting demand on an already overloaded server.
  140. Giving sync the kwarg "ignore_replag" will go around this restriction.
  141. """
  142. self.logger.info("Starting sync")
  143. replag = self.site.get_replag()
  144. self.logger.debug("Server replag is {0}".format(replag))
  145. if replag > 600 and not kwargs.get("ignore_replag"):
  146. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes."
  147. self.logger.warn(msg.format(replag))
  148. with self.conn.cursor() as cursor:
  149. self.update_tracked(cursor)
  150. self.add_untracked(cursor)
  151. self.delete_old(cursor)
  152. self.logger.info("Sync completed")
  153. def update_tracked(self, cursor):
  154. """Update tracked submissions that have been changed since last sync.
  155. This is done by iterating through every page in our database and
  156. comparing our stored latest revision ID with the actual latest revision
  157. ID from an SQL query. If they differ, we will update our information
  158. about the page (self.update_page()).
  159. If the page does not exist, we will remove it from our database with
  160. self.untrack_page().
  161. """
  162. self.logger.debug("Updating tracked submissions")
  163. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  164. query2 = """SELECT page_latest, page_title, page_namespace FROM page
  165. WHERE page_id = ?"""
  166. cursor.execute(query1)
  167. for pageid, title, oldid in cursor:
  168. result = list(self.site.sql_query(query2, (pageid,)))
  169. if not result:
  170. self.untrack_page(cursor, pageid)
  171. continue
  172. real_oldid = result[0][0]
  173. if oldid != real_oldid:
  174. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  175. self.logger.debug(msg.format(title, pageid, oldid))
  176. self.logger.debug(" {0} -> {1}".format(oldid, real_oldid))
  177. body = result[0][1].replace("_", " ")
  178. ns = self.site.namespace_id_to_name(result[0][2])
  179. if ns:
  180. real_title = ":".join((str(ns), body))
  181. else:
  182. real_title = body
  183. self.update_page(cursor, pageid, real_title)
  184. def add_untracked(self, cursor):
  185. """Add pending submissions that are not yet tracked.
  186. This is done by compiling a list of all currently tracked submissions
  187. and iterating through all members of self.pending_cat via SQL. If a
  188. page in the pending category is not tracked and is not in
  189. self.ignore_list, we will track it with self.track_page().
  190. """
  191. self.logger.debug("Adding untracked pending submissions")
  192. cursor.execute("SELECT page_id FROM page")
  193. tracked = [i[0] for i in cursor.fetchall()]
  194. category = self.site.get_category(self.pending_cat)
  195. pending = category.members(use_sql=True)
  196. for title, pageid in pending:
  197. if title.decode("utf8") in self.ignore_list:
  198. continue
  199. if pageid not in tracked:
  200. msg = "Tracking page [[{0}]] (id: {1})".format(title, pageid)
  201. self.logger.debug(msg)
  202. self.track_page(cursor, pageid, title)
  203. def delete_old(self, cursor):
  204. """Remove old submissions from the database.
  205. "Old" is defined as a submission that has been declined or accepted
  206. more than 36 hours ago. Pending submissions cannot be "old".
  207. """
  208. self.logger.debug("Removing old submissions from chart")
  209. query = """DELETE FROM page, row USING page JOIN row
  210. ON page_id = row_id WHERE row_chart IN (?, ?)
  211. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  212. cursor.execute(query, (CHART_ACCEPT, CHART_DECLINE))
  213. def untrack_page(self, cursor, pageid):
  214. """Remove a page, given by ID, from our database."""
  215. self.logger.debug("Untracking page (id: {0})".format(pageid))
  216. query = """DELETE FROM page, row USING page JOIN row
  217. ON page_id = row_id WHERE page_id = ?"""
  218. cursor.execute(query, (pageid,))
  219. def track_page(self, cursor, pageid, title):
  220. """Update hook for when page is not in our database.
  221. A variety of SQL queries are used to gather information about the page,
  222. which are then saved to our database.
  223. """
  224. content = self.get_content(title)
  225. if not content:
  226. msg = "Could not get page content for [[{0}]]".format(title)
  227. self.logger.error(msg)
  228. return
  229. status, chart = self.get_status_and_chart(content)
  230. if not status:
  231. msg = "Could not find a status for [[{0}]]".format(title)
  232. self.logger.error(msg)
  233. return
  234. short = self.get_short_title(title)
  235. size = len(content)
  236. c_user, c_time, c_id = self.get_create(pageid)
  237. m_user, m_time, m_id = self.get_modify(pageid)
  238. s_user, s_time, s_id = self.get_special(pageid, chart)
  239. notes = self.get_notes(content, m_time, c_user)
  240. query1 = "INSERT INTO row VALUES (?, ?)"
  241. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  242. cursor.execute(query1, (pageid, chart))
  243. cursor.execute(query2, (pageid, status, title.decode("utf8"),
  244. short.decode("utf8"), size, notes, c_user,
  245. c_time, c_id, m_user, m_time, m_id, s_user,
  246. s_time, s_id))
  247. def update_page(self, cursor, pageid, title):
  248. """Update hook for when page is already in our database.
  249. A variety of SQL queries are used to gather information about the page,
  250. which is compared against our stored information. Differing information
  251. is then updated.
  252. If our page is now a redirect, we will determine the namespace it was
  253. moved to. If it was moved to the mainspace or template space, we will
  254. set the sub's status as accepted. If it was to the Project: or Project
  255. talk: namespaces, we'll merely update our stored title (this is likely
  256. to occur if a submission was moved from the userspace to the project
  257. space). If it was moved to another namespace, something unusual has
  258. happened, and we'll untrack the submission.
  259. """
  260. content = self.get_content(title)
  261. if not content:
  262. msg = "Could not get page content for [[{0}]]".format(title)
  263. self.logger.error(msg)
  264. return
  265. try:
  266. redirect_regex = wiki.Page.re_redirect
  267. target_title = re.findall(redirect_regex, content, flags=re.I)[0]
  268. except IndexError:
  269. status, chart = self.get_status_and_chart(content)
  270. if not status:
  271. self.untrack_page(cursor, pageid)
  272. return
  273. else:
  274. target_ns = self.site.get_page(target_title).namespace()
  275. if target_ns in [wiki.NS_MAIN, wiki.NS_TEMPLATE]:
  276. status, chart = "a", CHART_ACCEPT
  277. elif target_ns in [wiki.NS_PROJECT, wiki.NS_PROJECT_TALK]:
  278. title = target_title
  279. content = self.get_content(title)
  280. status, chart = self.get_status_and_chart(content)
  281. if not status:
  282. self.untrack_page(cursor, pageid)
  283. return
  284. else:
  285. msg = " Page has moved to namespace {0}".format(target_ns)
  286. self.logger.debug(msg)
  287. self.untrack_page(cursor, pageid)
  288. return
  289. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  290. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  291. dict_cursor.execute(query, (pageid,))
  292. result = dict_cursor.fetchall()[0]
  293. size = len(content)
  294. m_user, m_time, m_id = self.get_modify(pageid)
  295. notes = self.get_notes(content, m_time, result["page_create_user"])
  296. if title != result["page_title"]:
  297. self.update_page_title(cursor, result, pageid, title)
  298. if m_id != result["page_modify_oldid"]:
  299. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  300. if status != result["page_status"]:
  301. self.update_page_status(cursor, result, pageid, status, chart)
  302. if notes != result["page_notes"]:
  303. self.update_page_notes(cursor, result, pageid, notes)
  304. def update_page_title(self, cursor, result, pageid, title):
  305. """Update the title and short_title of a page in our database."""
  306. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  307. short = self.get_short_title(title)
  308. cursor.execute(query, (title.decode("utf8"), short.decode("utf8"),
  309. pageid))
  310. msg = " {0}: title: {1} -> {2}"
  311. self.logger.debug(msg.format(pageid, result["page_title"], title))
  312. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  313. """Update the last modified information of a page in our database."""
  314. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  315. page_modify_time = ?, page_modify_oldid = ?
  316. WHERE page_id = ?"""
  317. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  318. msg = " {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  319. msg = msg.format(pageid, result["page_modify_user"],
  320. result["page_modify_time"],
  321. result["page_modify_oldid"], m_user, m_time, m_id)
  322. self.logger.debug(msg)
  323. def update_page_status(self, cursor, result, pageid, status, chart):
  324. """Update the status and "specialed" information of a page."""
  325. query1 = """UPDATE page JOIN row ON page_id = row_id
  326. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  327. query2 = """UPDATE page SET page_special_user = ?,
  328. page_special_time = ?, page_special_oldid = ?
  329. WHERE page_id = ?"""
  330. cursor.execute(query1, (status, chart, pageid))
  331. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  332. self.logger.debug(msg.format(pageid, result["page_status"],
  333. result["row_chart"], status, chart))
  334. s_user, s_time, s_id = self.get_special(pageid, chart)
  335. if s_id != result["page_special_oldid"]:
  336. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  337. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  338. msg = msg.format(pageid, result["page_special_user"],
  339. result["page_special_time"],
  340. result["page_special_oldid"], s_user, s_time, s_id)
  341. self.logger.debug(msg)
  342. def update_page_notes(self, cursor, result, pageid, notes):
  343. """Update the notes (or warnings) of a page in our database."""
  344. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  345. cursor.execute(query, (notes, pageid))
  346. msg = " {0}: notes: {1} -> {2}"
  347. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  348. def get_content(self, title):
  349. """Get the current content of a page by title from the API.
  350. The page's current revision ID is retrieved from SQL, and then
  351. an API query is made to get its content. This is the only API query
  352. used in the task's code.
  353. """
  354. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  355. try:
  356. namespace, base = title.decode("utf8").split(":", 1)
  357. except ValueError:
  358. base = title.decode("utf8")
  359. ns = wiki.NS_MAIN
  360. else:
  361. try:
  362. ns = self.site.namespace_name_to_id(namespace)
  363. except wiki.NamespaceNotFoundError:
  364. base = title.decode("utf8")
  365. ns = wiki.NS_MAIN
  366. result = self.site.sql_query(query, (base.replace(" ", "_"), ns))
  367. revid = int(list(result)[0][0])
  368. return self.get_revision_content(revid)
  369. def get_revision_content(self, revid):
  370. """Get the content of a revision by ID from the API."""
  371. res = self.site.api_query(action="query", prop="revisions",
  372. revids=revid, rvprop="content")
  373. try:
  374. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  375. except KeyError:
  376. sleep(5)
  377. res = self.site.api_query(action="query", prop="revisions",
  378. revids=revid, rvprop="content")
  379. try:
  380. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  381. except KeyError:
  382. return None
  383. def get_status_and_chart(self, content):
  384. """Determine the status and chart number of an AFC submission.
  385. The methodology used here is the same one I've been using for years
  386. (see also commands.afc_report), but with the new draft system taken
  387. into account. The order here is important: if there is more than one
  388. {{AFC submission}} template on a page, we need to know which one to
  389. use (revision history search to find the most recent isn't a viable
  390. idea :P).
  391. """
  392. if re.search("\{\{afc submission\|r\|(.*?)\}\}", content, re.I):
  393. return "r", CHART_REVIEW
  394. elif re.search("\{\{afc submission\|h\|(.*?)\}\}", content, re.I):
  395. return "p", CHART_DRAFT
  396. elif re.search("\{\{afc submission\|\|(.*?)\}\}", content, re.I):
  397. return "p", CHART_PEND
  398. elif re.search("\{\{afc submission\|t\|(.*?)\}\}", content, re.I):
  399. return None, CHART_NONE
  400. elif re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I):
  401. return "d", CHART_DECLINE
  402. return None, CHART_NONE
  403. def get_short_title(self, title):
  404. """Shorten a title so we can display it in a chart using less space.
  405. Basically, this just means removing the "Wikipedia talk:Articles for
  406. creation" part from the beginning. If it is longer than 50 characters,
  407. we'll shorten it down to 47 and add an poor-man's ellipsis at the end.
  408. """
  409. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  410. if len(short) > 50:
  411. short = "".join((short[:47], "..."))
  412. return short
  413. def get_create(self, pageid):
  414. """Return information about a page's first edit ("creation").
  415. This consists of the page creator, creation time, and the earliest
  416. revision ID.
  417. """
  418. query = """SELECT rev_user_text, rev_timestamp, rev_id
  419. FROM revision WHERE rev_id =
  420. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  421. result = self.site.sql_query(query, (pageid,))
  422. c_user, c_time, c_id = list(result)[0]
  423. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  424. def get_modify(self, pageid):
  425. """Return information about a page's last edit ("modification").
  426. This consists of the most recent editor, modification time, and the
  427. lastest revision ID.
  428. """
  429. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  430. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  431. result = self.site.sql_query(query, (pageid,))
  432. m_user, m_time, m_id = list(result)[0]
  433. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  434. def get_special(self, pageid, chart):
  435. """Return information about a page's "special" edit.
  436. I tend to use the term "special" as a verb a lot, which is bound to
  437. cause confusion. It is merely a short way of saying "the edit in which
  438. a declined submission was declined, an accepted submission was
  439. accepted, a submission in review was set as such, and a pending draft
  440. was submitted."
  441. This "information" consists of the special edit's editor, its time, and
  442. its revision ID. If the page's status is not something that involves
  443. "special"-ing, we will return None for all three. The same will be
  444. returned if we cannot determine when the page was "special"-ed, or if
  445. it was "special"-ed more than 250 edits ago.
  446. """
  447. if chart in [CHART_NONE, CHART_PEND]:
  448. return None, None, None
  449. elif chart == CHART_ACCEPT:
  450. return self.get_create(pageid)
  451. elif chart == CHART_DRAFT:
  452. search = "\{\{afc submission\|h\|(.*?)\}\}"
  453. elif chart == CHART_REVIEW:
  454. search = "\{\{afc submission\|r\|(.*?)\}\}"
  455. elif chart == CHART_DECLINE:
  456. search = "\{\{afc submission\|d\|(.*?)\}\}"
  457. query = """SELECT rev_user_text, rev_timestamp, rev_id
  458. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  459. result = self.site.sql_query(query, (pageid,))
  460. counter = 0
  461. last = (None, None, None)
  462. for user, ts, revid in result:
  463. counter += 1
  464. if counter > 250:
  465. msg = "Exceeded 250 content lookups while determining special for page (id: {0}, chart: {1})"
  466. self.logger.warn(msg.format(pageid, chart))
  467. return None, None, None
  468. content = self.get_revision_content(revid)
  469. if content and not re.search(search, content, re.I):
  470. return last
  471. last = (user, datetime.strptime(ts, "%Y%m%d%H%M%S"), revid)
  472. return last
  473. def get_notes(self, content, m_time, c_user):
  474. """Return any special notes or warnings about this page.
  475. Currently unimplemented, so always returns None.
  476. """
  477. # accepted subs
  478. # rebuild action
  479. # resubmit submission was resubmitted after a previous decline
  480. # re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I)
  481. # short submission is less than X bytes
  482. # len(content) < X
  483. # no-inline submission has no inline citations
  484. # not re.search("\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I|re.S)
  485. # unsourced submission lacks references completely
  486. # not re.search(references, content, re.I|re.S) and search(hyperlinks)
  487. # old submission has not been touched in > 4 days
  488. # m_time < now - 4 hours
  489. # blocked submitter is currently blocked
  490. # c_user is blocked via API
  491. return ""