Additional IRC commands and bot tasks for EarwigBot 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.

afc_statistics.py 29 KiB

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