A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
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.
 
 
 
 
 

195 line
7.3 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from hashlib import sha256
  4. from urlparse import urlparse
  5. from earwigbot import exceptions
  6. from earwigbot.wiki.copyvios.markov import EMPTY, MarkovChain
  7. from earwigbot.wiki.copyvios.parsers import ArticleTextParser
  8. from earwigbot.wiki.copyvios.result import CopyvioSource, CopyvioCheckResult
  9. from .misc import Query, get_db
  10. from .sites import get_site
  11. __all__ = ["do_check", "T_POSSIBLE", "T_SUSPECT"]
  12. T_POSSIBLE = 0.4
  13. T_SUSPECT = 0.75
  14. def _coerce_bool(val):
  15. return val and val not in ("0", "false")
  16. def do_check(query=None):
  17. if not query:
  18. query = Query()
  19. if query.lang:
  20. query.lang = query.orig_lang = query.lang.lower()
  21. if "::" in query.lang:
  22. query.lang, query.name = query.lang.split("::", 1)
  23. if query.project:
  24. query.project = query.project.lower()
  25. query.submitted = query.project and query.lang and (query.title or query.oldid)
  26. if query.submitted:
  27. query.site = get_site(query)
  28. if query.site:
  29. _get_results(query, follow=not _coerce_bool(query.noredirect))
  30. return query
  31. def _get_results(query, follow=True):
  32. if query.oldid:
  33. page = query.page = _get_page_by_revid(query.site, query.oldid)
  34. if not page:
  35. return
  36. else:
  37. page = query.page = query.site.get_page(query.title)
  38. try:
  39. page.get() # Make sure that the page exists before we check it!
  40. except (exceptions.PageNotFoundError, exceptions.InvalidPageError):
  41. return
  42. if page.is_redirect and follow:
  43. try:
  44. query.title = page.get_redirect_target()
  45. except exceptions.RedirectError:
  46. pass # Something's wrong. Continue checking the original page.
  47. else:
  48. query.redirected_from = page
  49. return _get_results(query, follow=False)
  50. if not query.action:
  51. query.action = "compare" if query.url else "search"
  52. if query.action == "search":
  53. conn = get_db()
  54. use_engine = 0 if query.use_engine in ("0", "false") else 1
  55. use_links = 0 if query.use_links in ("0", "false") else 1
  56. if not use_engine and not use_links:
  57. query.error = "no search method"
  58. return
  59. mode = "{0}:{1}:".format(use_engine, use_links)
  60. if not _coerce_bool(query.nocache):
  61. query.result = _get_cached_results(
  62. page, conn, mode, _coerce_bool(query.noskip))
  63. if not query.result:
  64. try:
  65. query.result = page.copyvio_check(
  66. min_confidence=T_SUSPECT, max_queries=10, max_time=45,
  67. no_searches=not use_engine, no_links=not use_links,
  68. short_circuit=not query.noskip)
  69. except exceptions.SearchQueryError as exc:
  70. query.error = "search error"
  71. query.exception = exc
  72. return
  73. query.result.cached = False
  74. _cache_result(page, query.result, conn, mode)
  75. elif query.action == "compare":
  76. if not query.url:
  77. query.error = "no URL"
  78. return
  79. scheme = urlparse(query.url).scheme
  80. if not scheme and query.url[0] not in ":/":
  81. query.url = "http://" + query.url
  82. elif scheme not in ["http", "https"]:
  83. query.error = "bad URI"
  84. return
  85. result = page.copyvio_compare(query.url, min_confidence=T_SUSPECT,
  86. max_time=30)
  87. if result.best.chains[0] is EMPTY:
  88. query.error = "timeout" if result.time > 30 else "no data"
  89. return
  90. query.result = result
  91. query.result.cached = False
  92. else:
  93. query.error = "bad action"
  94. def _get_page_by_revid(site, revid):
  95. res = site.api_query(action="query", prop="info|revisions", revids=revid,
  96. rvprop="content|timestamp", inprop="protection|url")
  97. try:
  98. page_data = res["query"]["pages"].values()[0]
  99. title = page_data["title"]
  100. page_data["revisions"][0]["*"] # Only need to check that these exist
  101. page_data["revisions"][0]["timestamp"]
  102. except KeyError:
  103. return
  104. page = site.get_page(title)
  105. # EarwigBot doesn't understand old revisions of pages, so we use a somewhat
  106. # dirty hack to make this work:
  107. page._load_attributes(res)
  108. page._load_content(res)
  109. return page
  110. def _get_cached_results(page, conn, mode, noskip):
  111. query1 = """DELETE FROM cache
  112. WHERE cache_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 3 DAY)"""
  113. query2 = """SELECT cache_time, cache_queries, cache_process_time
  114. FROM cache
  115. WHERE cache_id = ?"""
  116. query3 = """SELECT cdata_url, cdata_confidence, cdata_skipped
  117. FROM cache_data
  118. WHERE cdata_cache_id = ?"""
  119. cache_id = buffer(sha256(mode + page.get().encode("utf8")).digest())
  120. with conn.cursor() as cursor:
  121. cursor.execute(query1)
  122. cursor.execute(query2, (cache_id,))
  123. results = cursor.fetchall()
  124. if not results:
  125. return None
  126. cache_time, queries, check_time = results[0]
  127. cursor.execute(query3, (cache_id,))
  128. data = cursor.fetchall()
  129. if not data: # TODO: do something less hacky for this edge case
  130. artchain = MarkovChain(ArticleTextParser(page.get()).strip())
  131. result = CopyvioCheckResult(False, [], queries, check_time, artchain)
  132. result.cached = True
  133. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  134. result.cache_age = _format_date(cache_time)
  135. return result
  136. url, confidence, skipped = data.pop(0)
  137. if skipped: # Should be impossible: data must be bad; run a new check
  138. return None
  139. result = page.copyvio_compare(url, min_confidence=T_SUSPECT, max_time=30)
  140. if abs(result.confidence - confidence) >= 0.0001:
  141. return None
  142. for url, confidence, skipped in data:
  143. if noskip and skipped:
  144. return None
  145. source = CopyvioSource(None, url)
  146. source.confidence = confidence
  147. source.skipped = bool(skipped)
  148. result.sources.append(source)
  149. result.queries = queries
  150. result.time = check_time
  151. result.cached = True
  152. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  153. result.cache_age = _format_date(cache_time)
  154. return result
  155. def _format_date(cache_time):
  156. format = lambda n, w: "{0} {1}{2}".format(n, w, "" if n == 1 else "s")
  157. diff = datetime.utcnow() - cache_time
  158. if diff.seconds > 3600:
  159. return format(diff.seconds / 3600, "hour")
  160. if diff.seconds > 60:
  161. return format(diff.seconds / 60, "minute")
  162. return format(diff.seconds, "second")
  163. def _cache_result(page, result, conn, mode):
  164. query1 = "DELETE FROM cache WHERE cache_id = ?"
  165. query2 = "INSERT INTO cache VALUES (?, DEFAULT, ?, ?)"
  166. query3 = "INSERT INTO cache_data VALUES (DEFAULT, ?, ?, ?, ?)"
  167. cache_id = buffer(sha256(mode + page.get().encode("utf8")).digest())
  168. data = [(cache_id, source.url[:1024], source.confidence, source.skipped)
  169. for source in result.sources]
  170. with conn.cursor() as cursor:
  171. cursor.execute("START TRANSACTION")
  172. cursor.execute(query1, (cache_id,))
  173. cursor.execute(query2, (cache_id, result.queries, result.time))
  174. cursor.executemany(query3, data)
  175. cursor.execute("COMMIT")