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.
 
 
 
 
 

203 regels
7.7 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. cache_possible_miss
  115. FROM cache
  116. WHERE cache_id = ?"""
  117. query3 = """SELECT cdata_url, cdata_confidence, cdata_skipped, cdata_excluded
  118. FROM cache_data
  119. WHERE cdata_cache_id = ?"""
  120. cache_id = buffer(sha256(mode + page.get().encode("utf8")).digest())
  121. with conn.cursor() as cursor:
  122. cursor.execute(query1)
  123. cursor.execute(query2, (cache_id,))
  124. results = cursor.fetchall()
  125. if not results:
  126. return None
  127. cache_time, queries, check_time, possible_miss = results[0]
  128. if possible_miss and noskip:
  129. return None
  130. cursor.execute(query3, (cache_id,))
  131. data = cursor.fetchall()
  132. if not data: # TODO: do something less hacky for this edge case
  133. article_chain = MarkovChain(ArticleTextParser(page.get()).strip())
  134. result = CopyvioCheckResult(False, [], queries, check_time,
  135. article_chain, possible_miss)
  136. result.cached = True
  137. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  138. result.cache_age = _format_date(cache_time)
  139. return result
  140. url, confidence, skipped, excluded = data.pop(0)
  141. if skipped: # Should be impossible: data must be bad; run a new check
  142. return None
  143. result = page.copyvio_compare(url, min_confidence=T_SUSPECT, max_time=30)
  144. if abs(result.confidence - confidence) >= 0.0001:
  145. return None
  146. for url, confidence, skipped, excluded in data:
  147. if noskip and skipped:
  148. return None
  149. source = CopyvioSource(None, url)
  150. source.confidence = confidence
  151. source.skipped = bool(skipped)
  152. source.excluded = bool(excluded)
  153. result.sources.append(source)
  154. result.queries = queries
  155. result.time = check_time
  156. result.possible_miss = possible_miss
  157. result.cached = True
  158. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  159. result.cache_age = _format_date(cache_time)
  160. return result
  161. def _format_date(cache_time):
  162. format = lambda n, w: "{0} {1}{2}".format(n, w, "" if n == 1 else "s")
  163. diff = datetime.utcnow() - cache_time
  164. if diff.seconds > 3600:
  165. return format(diff.seconds / 3600, "hour")
  166. if diff.seconds > 60:
  167. return format(diff.seconds / 60, "minute")
  168. return format(diff.seconds, "second")
  169. def _cache_result(page, result, conn, mode):
  170. query1 = "DELETE FROM cache WHERE cache_id = ?"
  171. query2 = "INSERT INTO cache VALUES (?, DEFAULT, ?, ?, ?)"
  172. query3 = "INSERT INTO cache_data VALUES (DEFAULT, ?, ?, ?, ?, ?)"
  173. cache_id = buffer(sha256(mode + page.get().encode("utf8")).digest())
  174. data = [(cache_id, source.url[:1024], source.confidence, source.skipped,
  175. source.excluded)
  176. for source in result.sources]
  177. with conn.cursor() as cursor:
  178. cursor.execute("START TRANSACTION")
  179. cursor.execute(query1, (cache_id,))
  180. cursor.execute(query2, (cache_id, result.queries, result.time,
  181. result.possible_miss))
  182. cursor.executemany(query3, data)
  183. cursor.execute("COMMIT")