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.

697 regels
29 KiB

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