Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

740 lines
30 KiB

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