text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import gzip
  2. import re
  3. import secrets
  4. import unicodedata
  5. from gzip import GzipFile
  6. from gzip import compress as gzip_compress
  7. from io import BytesIO
  8. from django.core.exceptions import SuspiciousFileOperation
  9. from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
  10. from django.utils.regex_helper import _lazy_re_compile
  11. from django.utils.translation import gettext as _
  12. from django.utils.translation import gettext_lazy, pgettext
  13. @keep_lazy_text
  14. def capfirst(x):
  15. """Capitalize the first letter of a string."""
  16. if not x:
  17. return x
  18. if not isinstance(x, str):
  19. x = str(x)
  20. return x[0].upper() + x[1:]
  21. # Set up regular expressions
  22. re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S)
  23. re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S)
  24. re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S)
  25. re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
  26. re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
  27. @keep_lazy_text
  28. def wrap(text, width):
  29. """
  30. A word-wrap function that preserves existing line breaks. Expects that
  31. existing line breaks are posix newlines.
  32. Preserve all white space except added line breaks consume the space on
  33. which they break the line.
  34. Don't wrap long words, thus the output text may have lines longer than
  35. ``width``.
  36. """
  37. def _generator():
  38. for line in text.splitlines(True): # True keeps trailing linebreaks
  39. max_width = min((line.endswith("\n") and width + 1 or width), width)
  40. while len(line) > max_width:
  41. space = line[: max_width + 1].rfind(" ") + 1
  42. if space == 0:
  43. space = line.find(" ") + 1
  44. if space == 0:
  45. yield line
  46. line = ""
  47. break
  48. yield "%s\n" % line[: space - 1]
  49. line = line[space:]
  50. max_width = min((line.endswith("\n") and width + 1 or width), width)
  51. if line:
  52. yield line
  53. return "".join(_generator())
  54. def add_truncation_text(text, truncate=None):
  55. if truncate is None:
  56. truncate = pgettext(
  57. "String to return when truncating text", "%(truncated_text)s…"
  58. )
  59. if "%(truncated_text)s" in truncate:
  60. return truncate % {"truncated_text": text}
  61. # The truncation text didn't contain the %(truncated_text)s string
  62. # replacement argument so just append it to the text.
  63. if text.endswith(truncate):
  64. # But don't append the truncation text if the current text already ends
  65. # in this.
  66. return text
  67. return f"{text}{truncate}"
  68. class Truncator(SimpleLazyObject):
  69. """
  70. An object used to truncate text, either by characters or words.
  71. When truncating HTML text (either chars or words), input will be limited to
  72. at most `MAX_LENGTH_HTML` characters.
  73. """
  74. # 5 million characters are approximately 4000 text pages or 3 web pages.
  75. MAX_LENGTH_HTML = 5_000_000
  76. def __init__(self, text):
  77. super().__init__(lambda: str(text))
  78. def chars(self, num, truncate=None, html=False):
  79. """
  80. Return the text truncated to be no longer than the specified number
  81. of characters.
  82. `truncate` specifies what should be used to notify that the string has
  83. been truncated, defaulting to a translatable string of an ellipsis.
  84. """
  85. self._setup()
  86. length = int(num)
  87. text = unicodedata.normalize("NFC", self._wrapped)
  88. # Calculate the length to truncate to (max length - end_text length)
  89. truncate_len = length
  90. for char in add_truncation_text("", truncate):
  91. if not unicodedata.combining(char):
  92. truncate_len -= 1
  93. if truncate_len == 0:
  94. break
  95. if html:
  96. return self._truncate_html(length, truncate, text, truncate_len, False)
  97. return self._text_chars(length, truncate, text, truncate_len)
  98. def _text_chars(self, length, truncate, text, truncate_len):
  99. """Truncate a string after a certain number of chars."""
  100. s_len = 0
  101. end_index = None
  102. for i, char in enumerate(text):
  103. if unicodedata.combining(char):
  104. # Don't consider combining characters
  105. # as adding to the string length
  106. continue
  107. s_len += 1
  108. if end_index is None and s_len > truncate_len:
  109. end_index = i
  110. if s_len > length:
  111. # Return the truncated string
  112. return add_truncation_text(text[: end_index or 0], truncate)
  113. # Return the original string since no truncation was necessary
  114. return text
  115. def words(self, num, truncate=None, html=False):
  116. """
  117. Truncate a string after a certain number of words. `truncate` specifies
  118. what should be used to notify that the string has been truncated,
  119. defaulting to ellipsis.
  120. """
  121. self._setup()
  122. length = int(num)
  123. if html:
  124. return self._truncate_html(length, truncate, self._wrapped, length, True)
  125. return self._text_words(length, truncate)
  126. def _text_words(self, length, truncate):
  127. """
  128. Truncate a string after a certain number of words.
  129. Strip newlines in the string.
  130. """
  131. words = self._wrapped.split()
  132. if len(words) > length:
  133. words = words[:length]
  134. return add_truncation_text(" ".join(words), truncate)
  135. return " ".join(words)
  136. def _truncate_html(self, length, truncate, text, truncate_len, words):
  137. """
  138. Truncate HTML to a certain number of chars (not counting tags and
  139. comments), or, if words is True, then to a certain number of words.
  140. Close opened tags if they were correctly closed in the given HTML.
  141. Preserve newlines in the HTML.
  142. """
  143. if words and length <= 0:
  144. return ""
  145. size_limited = False
  146. if len(text) > self.MAX_LENGTH_HTML:
  147. text = text[: self.MAX_LENGTH_HTML]
  148. size_limited = True
  149. html4_singlets = (
  150. "br",
  151. "col",
  152. "link",
  153. "base",
  154. "img",
  155. "param",
  156. "area",
  157. "hr",
  158. "input",
  159. )
  160. # Count non-HTML chars/words and keep note of open tags
  161. pos = 0
  162. end_text_pos = 0
  163. current_len = 0
  164. open_tags = []
  165. regex = re_words if words else re_chars
  166. while current_len <= length:
  167. m = regex.search(text, pos)
  168. if not m:
  169. # Checked through whole string
  170. break
  171. pos = m.end(0)
  172. if m[1]:
  173. # It's an actual non-HTML word or char
  174. current_len += 1
  175. if current_len == truncate_len:
  176. end_text_pos = pos
  177. continue
  178. # Check for tag
  179. tag = re_tag.match(m[0])
  180. if not tag or current_len >= truncate_len:
  181. # Don't worry about non tags or tags after our truncate point
  182. continue
  183. closing_tag, tagname, self_closing = tag.groups()
  184. # Element names are always case-insensitive
  185. tagname = tagname.lower()
  186. if self_closing or tagname in html4_singlets:
  187. pass
  188. elif closing_tag:
  189. # Check for match in open tags list
  190. try:
  191. i = open_tags.index(tagname)
  192. except ValueError:
  193. pass
  194. else:
  195. # SGML: An end tag closes, back to the matching start tag,
  196. # all unclosed intervening start tags with omitted end tags
  197. open_tags = open_tags[i + 1 :]
  198. else:
  199. # Add it to the start of the open tags list
  200. open_tags.insert(0, tagname)
  201. truncate_text = add_truncation_text("", truncate)
  202. if current_len <= length:
  203. if size_limited and truncate_text:
  204. text += truncate_text
  205. return text
  206. out = text[:end_text_pos]
  207. if truncate_text:
  208. out += truncate_text
  209. # Close any tags still open
  210. for tag in open_tags:
  211. out += "</%s>" % tag
  212. # Return string
  213. return out
  214. @keep_lazy_text
  215. def get_valid_filename(name):
  216. """
  217. Return the given string converted to a string that can be used for a clean
  218. filename. Remove leading and trailing spaces; convert other spaces to
  219. underscores; and remove anything that is not an alphanumeric, dash,
  220. underscore, or dot.
  221. >>> get_valid_filename("john's portrait in 2004.jpg")
  222. 'johns_portrait_in_2004.jpg'
  223. """
  224. s = str(name).strip().replace(" ", "_")
  225. s = re.sub(r"(?u)[^-\w.]", "", s)
  226. if s in {"", ".", ".."}:
  227. raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
  228. return s
  229. @keep_lazy_text
  230. def get_text_list(list_, last_word=gettext_lazy("or")):
  231. """
  232. >>> get_text_list(['a', 'b', 'c', 'd'])
  233. 'a, b, c or d'
  234. >>> get_text_list(['a', 'b', 'c'], 'and')
  235. 'a, b and c'
  236. >>> get_text_list(['a', 'b'], 'and')
  237. 'a and b'
  238. >>> get_text_list(['a'])
  239. 'a'
  240. >>> get_text_list([])
  241. ''
  242. """
  243. if not list_:
  244. return ""
  245. if len(list_) == 1:
  246. return str(list_[0])
  247. return "%s %s %s" % (
  248. # Translators: This string is used as a separator between list elements
  249. _(", ").join(str(i) for i in list_[:-1]),
  250. str(last_word),
  251. str(list_[-1]),
  252. )
  253. @keep_lazy_text
  254. def normalize_newlines(text):
  255. """Normalize CRLF and CR newlines to just LF."""
  256. return re_newlines.sub("\n", str(text))
  257. @keep_lazy_text
  258. def phone2numeric(phone):
  259. """Convert a phone number with letters into its numeric equivalent."""
  260. char2number = {
  261. "a": "2",
  262. "b": "2",
  263. "c": "2",
  264. "d": "3",
  265. "e": "3",
  266. "f": "3",
  267. "g": "4",
  268. "h": "4",
  269. "i": "4",
  270. "j": "5",
  271. "k": "5",
  272. "l": "5",
  273. "m": "6",
  274. "n": "6",
  275. "o": "6",
  276. "p": "7",
  277. "q": "7",
  278. "r": "7",
  279. "s": "7",
  280. "t": "8",
  281. "u": "8",
  282. "v": "8",
  283. "w": "9",
  284. "x": "9",
  285. "y": "9",
  286. "z": "9",
  287. }
  288. return "".join(char2number.get(c, c) for c in phone.lower())
  289. def _get_random_filename(max_random_bytes):
  290. return b"a" * secrets.randbelow(max_random_bytes)
  291. def compress_string(s, *, max_random_bytes=None):
  292. compressed_data = gzip_compress(s, compresslevel=6, mtime=0)
  293. if not max_random_bytes:
  294. return compressed_data
  295. compressed_view = memoryview(compressed_data)
  296. header = bytearray(compressed_view[:10])
  297. header[3] = gzip.FNAME
  298. filename = _get_random_filename(max_random_bytes) + b"\x00"
  299. return bytes(header) + filename + compressed_view[10:]
  300. class StreamingBuffer(BytesIO):
  301. def read(self):
  302. ret = self.getvalue()
  303. self.seek(0)
  304. self.truncate()
  305. return ret
  306. # Like compress_string, but for iterators of strings.
  307. def compress_sequence(sequence, *, max_random_bytes=None):
  308. buf = StreamingBuffer()
  309. filename = _get_random_filename(max_random_bytes) if max_random_bytes else None
  310. with GzipFile(
  311. filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0
  312. ) as zfile:
  313. # Output headers...
  314. yield buf.read()
  315. for item in sequence:
  316. zfile.write(item)
  317. data = buf.read()
  318. if data:
  319. yield data
  320. yield buf.read()
  321. # Expression to match some_token and some_token="with spaces" (and similarly
  322. # for single-quoted strings).
  323. smart_split_re = _lazy_re_compile(
  324. r"""
  325. ((?:
  326. [^\s'"]*
  327. (?:
  328. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  329. [^\s'"]*
  330. )+
  331. ) | \S+)
  332. """,
  333. re.VERBOSE,
  334. )
  335. def smart_split(text):
  336. r"""
  337. Generator that splits a string by spaces, leaving quoted phrases together.
  338. Supports both single and double quotes, and supports escaping quotes with
  339. backslashes. In the output, strings will keep their initial and trailing
  340. quote marks and escaped quotes will remain escaped (the results can then
  341. be further processed with unescape_string_literal()).
  342. >>> list(smart_split(r'This is "a person\'s" test.'))
  343. ['This', 'is', '"a person\\\'s"', 'test.']
  344. >>> list(smart_split(r"Another 'person\'s' test."))
  345. ['Another', "'person\\'s'", 'test.']
  346. >>> list(smart_split(r'A "\"funky\" style" test.'))
  347. ['A', '"\\"funky\\" style"', 'test.']
  348. """
  349. for bit in smart_split_re.finditer(str(text)):
  350. yield bit[0]
  351. @keep_lazy_text
  352. def unescape_string_literal(s):
  353. r"""
  354. Convert quoted string literals to unquoted strings with escaped quotes and
  355. backslashes unquoted::
  356. >>> unescape_string_literal('"abc"')
  357. 'abc'
  358. >>> unescape_string_literal("'abc'")
  359. 'abc'
  360. >>> unescape_string_literal('"a \"bc\""')
  361. 'a "bc"'
  362. >>> unescape_string_literal("'\'ab\' c'")
  363. "'ab' c"
  364. """
  365. if not s or s[0] not in "\"'" or s[-1] != s[0]:
  366. raise ValueError("Not a string literal: %r" % s)
  367. quote = s[0]
  368. return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
  369. @keep_lazy_text
  370. def slugify(value, allow_unicode=False):
  371. """
  372. Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
  373. dashes to single dashes. Remove characters that aren't alphanumerics,
  374. underscores, or hyphens. Convert to lowercase. Also strip leading and
  375. trailing whitespace, dashes, and underscores.
  376. """
  377. value = str(value)
  378. if allow_unicode:
  379. value = unicodedata.normalize("NFKC", value)
  380. else:
  381. value = (
  382. unicodedata.normalize("NFKD", value)
  383. .encode("ascii", "ignore")
  384. .decode("ascii")
  385. )
  386. value = re.sub(r"[^\w\s-]", "", value.lower())
  387. return re.sub(r"[-\s]+", "-", value).strip("-_")
  388. def camel_case_to_spaces(value):
  389. """
  390. Split CamelCase and convert to lowercase. Strip surrounding whitespace.
  391. """
  392. return re_camel_case.sub(r" \1", value).strip().lower()
  393. def _format_lazy(format_string, *args, **kwargs):
  394. """
  395. Apply str.format() on 'format_string' where format_string, args,
  396. and/or kwargs might be lazy.
  397. """
  398. return format_string.format(*args, **kwargs)
  399. format_lazy = lazy(_format_lazy, str)