A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

719 líneas
30 KiB

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