Development of an internal social media platform with personalised dashboards for students
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.

filter.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. filters.py - misc stuff for handling LDAP filter strings (see RFC2254)
  3. See https://www.python-ldap.org/ for details.
  4. Compatibility:
  5. - Tested with Python 2.0+
  6. """
  7. from ldap import __version__
  8. from ldap.functions import strf_secs
  9. import time
  10. def escape_filter_chars(assertion_value,escape_mode=0):
  11. """
  12. Replace all special characters found in assertion_value
  13. by quoted notation.
  14. escape_mode
  15. If 0 only special chars mentioned in RFC 4515 are escaped.
  16. If 1 all NON-ASCII chars are escaped.
  17. If 2 all chars are escaped.
  18. """
  19. if escape_mode:
  20. r = []
  21. if escape_mode==1:
  22. for c in assertion_value:
  23. if c < '0' or c > 'z' or c in "\\*()":
  24. c = "\\%02x" % ord(c)
  25. r.append(c)
  26. elif escape_mode==2:
  27. for c in assertion_value:
  28. r.append("\\%02x" % ord(c))
  29. else:
  30. raise ValueError('escape_mode must be 0, 1 or 2.')
  31. s = ''.join(r)
  32. else:
  33. s = assertion_value.replace('\\', r'\5c')
  34. s = s.replace(r'*', r'\2a')
  35. s = s.replace(r'(', r'\28')
  36. s = s.replace(r')', r'\29')
  37. s = s.replace('\x00', r'\00')
  38. return s
  39. def filter_format(filter_template,assertion_values):
  40. """
  41. filter_template
  42. String containing %s as placeholder for assertion values.
  43. assertion_values
  44. List or tuple of assertion values. Length must match
  45. count of %s in filter_template.
  46. """
  47. return filter_template % tuple(escape_filter_chars(v) for v in assertion_values)
  48. def time_span_filter(
  49. filterstr='',
  50. from_timestamp=0,
  51. until_timestamp=None,
  52. delta_attr='modifyTimestamp',
  53. ):
  54. """
  55. If last_run_timestr is non-zero filterstr will be extended
  56. """
  57. if until_timestamp is None:
  58. until_timestamp = time.time()
  59. if from_timestamp < 0:
  60. from_timestamp = until_timestamp + from_timestamp
  61. if from_timestamp > until_timestamp:
  62. raise ValueError('from_timestamp %r must not be greater than until_timestamp %r' % (
  63. from_timestamp, until_timestamp
  64. ))
  65. return (
  66. '(&'
  67. '{filterstr}'
  68. '({delta_attr}>={from_timestr})'
  69. '(!({delta_attr}>={until_timestr}))'
  70. ')'
  71. ).format(
  72. filterstr=filterstr,
  73. delta_attr=delta_attr,
  74. from_timestr=strf_secs(from_timestamp),
  75. until_timestr=strf_secs(until_timestamp),
  76. )
  77. # end of time_span_filter()