Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

857 рядки
24 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. # IMPORTANT: only import safe functions as this module will be included in jinja environment
  5. import frappe
  6. import operator
  7. import re, urllib, datetime, math, time
  8. import babel.dates
  9. from babel.core import UnknownLocaleError
  10. from dateutil import parser
  11. from num2words import num2words
  12. from six.moves import html_parser as HTMLParser
  13. from six.moves.urllib.parse import quote, urljoin
  14. from html2text import html2text
  15. from six import iteritems, text_type, string_types, integer_types
  16. DATE_FORMAT = "%Y-%m-%d"
  17. TIME_FORMAT = "%H:%M:%S.%f"
  18. DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT
  19. # datetime functions
  20. def getdate(string_date=None):
  21. """
  22. Coverts string date (yyyy-mm-dd) to datetime.date object
  23. """
  24. if not string_date:
  25. return get_datetime().date()
  26. if isinstance(string_date, datetime.datetime):
  27. return string_date.date()
  28. elif isinstance(string_date, datetime.date):
  29. return string_date
  30. # dateutil parser does not agree with dates like 0000-00-00
  31. if not string_date or string_date=="0000-00-00":
  32. return None
  33. return parser.parse(string_date).date()
  34. def get_datetime(datetime_str=None):
  35. if not datetime_str:
  36. return now_datetime()
  37. if isinstance(datetime_str, (datetime.datetime, datetime.timedelta)):
  38. return datetime_str
  39. elif isinstance(datetime_str, (list, tuple)):
  40. return datetime.datetime(datetime_str)
  41. elif isinstance(datetime_str, datetime.date):
  42. return datetime.datetime.combine(datetime_str, datetime.time())
  43. # dateutil parser does not agree with dates like 0000-00-00
  44. if not datetime_str or (datetime_str or "").startswith("0000-00-00"):
  45. return None
  46. try:
  47. return datetime.datetime.strptime(datetime_str, DATETIME_FORMAT)
  48. except ValueError:
  49. return parser.parse(datetime_str)
  50. def to_timedelta(time_str):
  51. if isinstance(time_str, string_types):
  52. t = parser.parse(time_str)
  53. return datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
  54. else:
  55. return time_str
  56. def add_to_date(date, years=0, months=0, days=0, hours=0, as_string=False, as_datetime=False):
  57. """Adds `days` to the given date"""
  58. from dateutil.relativedelta import relativedelta
  59. if date==None:
  60. date = now_datetime()
  61. if hours:
  62. as_datetime = True
  63. if isinstance(date, string_types):
  64. as_string = True
  65. if " " in date:
  66. as_datetime = True
  67. date = parser.parse(date)
  68. date = date + relativedelta(years=years, months=months, days=days, hours=hours)
  69. if as_string:
  70. if as_datetime:
  71. return date.strftime(DATETIME_FORMAT)
  72. else:
  73. return date.strftime(DATE_FORMAT)
  74. else:
  75. return date
  76. def add_days(date, days):
  77. return add_to_date(date, days=days)
  78. def add_months(date, months):
  79. return add_to_date(date, months=months)
  80. def add_years(date, years):
  81. return add_to_date(date, years=years)
  82. def date_diff(string_ed_date, string_st_date):
  83. return (getdate(string_ed_date) - getdate(string_st_date)).days
  84. def time_diff(string_ed_date, string_st_date):
  85. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  86. def time_diff_in_seconds(string_ed_date, string_st_date):
  87. return time_diff(string_ed_date, string_st_date).total_seconds()
  88. def time_diff_in_hours(string_ed_date, string_st_date):
  89. return round(float(time_diff(string_ed_date, string_st_date).total_seconds()) / 3600, 6)
  90. def now_datetime():
  91. dt = convert_utc_to_user_timezone(datetime.datetime.utcnow())
  92. return dt.replace(tzinfo=None)
  93. def get_timestamp(date):
  94. return time.mktime(getdate(date).timetuple())
  95. def get_eta(from_time, percent_complete):
  96. diff = time_diff(now_datetime(), from_time).total_seconds()
  97. return str(datetime.timedelta(seconds=(100 - percent_complete) / percent_complete * diff))
  98. def _get_time_zone():
  99. return frappe.db.get_system_setting('time_zone') or 'Asia/Kolkata'
  100. def get_time_zone():
  101. if frappe.local.flags.in_test:
  102. return _get_time_zone()
  103. return frappe.cache().get_value("time_zone", _get_time_zone)
  104. def convert_utc_to_user_timezone(utc_timestamp):
  105. from pytz import timezone, UnknownTimeZoneError
  106. utcnow = timezone('UTC').localize(utc_timestamp)
  107. try:
  108. return utcnow.astimezone(timezone(get_time_zone()))
  109. except UnknownTimeZoneError:
  110. return utcnow
  111. def now():
  112. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  113. if frappe.flags.current_date:
  114. return getdate(frappe.flags.current_date).strftime(DATE_FORMAT) + " " + \
  115. now_datetime().strftime(TIME_FORMAT)
  116. else:
  117. return now_datetime().strftime(DATETIME_FORMAT)
  118. def nowdate():
  119. """return current date as yyyy-mm-dd"""
  120. return now_datetime().strftime(DATE_FORMAT)
  121. def today():
  122. return nowdate()
  123. def nowtime():
  124. """return current time in hh:mm"""
  125. return now_datetime().strftime(TIME_FORMAT)
  126. def get_first_day(dt, d_years=0, d_months=0):
  127. """
  128. Returns the first day of the month for the date specified by date object
  129. Also adds `d_years` and `d_months` if specified
  130. """
  131. dt = getdate(dt)
  132. # d_years, d_months are "deltas" to apply to dt
  133. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  134. year = dt.year + d_years + overflow_years
  135. return datetime.date(year, month + 1, 1)
  136. def get_last_day(dt):
  137. """
  138. Returns last day of the month using:
  139. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  140. """
  141. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  142. def get_time(time_str):
  143. if isinstance(time_str, datetime.datetime):
  144. return time_str.time()
  145. elif isinstance(time_str, datetime.time):
  146. return time_str
  147. else:
  148. if isinstance(time_str, datetime.timedelta):
  149. time_str = str(time_str)
  150. return parser.parse(time_str).time()
  151. def get_datetime_str(datetime_obj):
  152. if isinstance(datetime_obj, string_types):
  153. datetime_obj = get_datetime(datetime_obj)
  154. return datetime_obj.strftime(DATETIME_FORMAT)
  155. def get_user_format():
  156. if getattr(frappe.local, "user_format", None) is None:
  157. frappe.local.user_format = frappe.db.get_default("date_format")
  158. return frappe.local.user_format or "yyyy-mm-dd"
  159. def formatdate(string_date=None, format_string=None):
  160. """
  161. Convers the given string date to :data:`user_format`
  162. User format specified in defaults
  163. Examples:
  164. * dd-mm-yyyy
  165. * mm-dd-yyyy
  166. * dd/mm/yyyy
  167. """
  168. if not string_date:
  169. return ''
  170. date = getdate(string_date)
  171. if not format_string:
  172. format_string = get_user_format().replace("mm", "MM")
  173. try:
  174. formatted_date = babel.dates.format_date(date, format_string, locale=(frappe.local.lang or "").replace("-", "_"))
  175. except UnknownLocaleError:
  176. formatted_date = date.strftime("%Y-%m-%d")
  177. return formatted_date
  178. def format_time(txt):
  179. try:
  180. formatted_time = babel.dates.format_time(get_time(txt), locale=(frappe.local.lang or "").replace("-", "_"))
  181. except UnknownLocaleError:
  182. formatted_time = get_time(txt).strftime("%H:%M:%S")
  183. return formatted_time
  184. def format_datetime(datetime_string, format_string=None):
  185. if not datetime_string:
  186. return
  187. datetime = get_datetime(datetime_string)
  188. if not format_string:
  189. format_string = get_user_format().replace("mm", "MM") + " HH:mm:ss"
  190. try:
  191. formatted_datetime = babel.dates.format_datetime(datetime, format_string, locale=(frappe.local.lang or "").replace("-", "_"))
  192. except UnknownLocaleError:
  193. formatted_datetime = datetime.strftime('%Y-%m-%d %H:%M:%S')
  194. return formatted_datetime
  195. def global_date_format(date):
  196. """returns localized date in the form of January 1, 2012"""
  197. date = getdate(date)
  198. formatted_date = babel.dates.format_date(date, locale=(frappe.local.lang or "en").replace("-", "_"), format="long")
  199. return formatted_date
  200. def has_common(l1, l2):
  201. """Returns truthy value if there are common elements in lists l1 and l2"""
  202. return set(l1) & set(l2)
  203. def flt(s, precision=None):
  204. """Convert to float (ignore commas)"""
  205. if isinstance(s, string_types):
  206. s = s.replace(',','')
  207. try:
  208. num = float(s)
  209. if precision is not None:
  210. num = rounded(num, precision)
  211. except Exception:
  212. num = 0
  213. return num
  214. def cint(s):
  215. """Convert to integer"""
  216. try: num = int(float(s))
  217. except: num = 0
  218. return num
  219. def cstr(s, encoding='utf-8'):
  220. return frappe.as_unicode(s, encoding)
  221. def rounded(num, precision=0):
  222. """round method for round halfs to nearest even algorithm aka banker's rounding - compatible with python3"""
  223. precision = cint(precision)
  224. multiplier = 10 ** precision
  225. # avoid rounding errors
  226. num = round(num * multiplier if precision else num, 8)
  227. floor = math.floor(num)
  228. decimal_part = num - floor
  229. if not precision and decimal_part == 0.5:
  230. num = floor if (floor % 2 == 0) else floor + 1
  231. else:
  232. num = round(num)
  233. return (num / multiplier) if precision else num
  234. def remainder(numerator, denominator, precision=2):
  235. precision = cint(precision)
  236. multiplier = 10 ** precision
  237. if precision:
  238. _remainder = ((numerator * multiplier) % (denominator * multiplier)) / multiplier
  239. else:
  240. _remainder = numerator % denominator
  241. return flt(_remainder, precision);
  242. def round_based_on_smallest_currency_fraction(value, currency, precision=2):
  243. smallest_currency_fraction_value = flt(frappe.db.get_value("Currency",
  244. currency, "smallest_currency_fraction_value"))
  245. if smallest_currency_fraction_value:
  246. remainder_val = remainder(value, smallest_currency_fraction_value, precision)
  247. if remainder_val > (smallest_currency_fraction_value / 2):
  248. value += smallest_currency_fraction_value - remainder_val
  249. else:
  250. value -= remainder_val
  251. else:
  252. value = rounded(value)
  253. return flt(value, precision)
  254. def encode(obj, encoding="utf-8"):
  255. if isinstance(obj, list):
  256. out = []
  257. for o in obj:
  258. if isinstance(o, text_type):
  259. out.append(o.encode(encoding))
  260. else:
  261. out.append(o)
  262. return out
  263. elif isinstance(obj, text_type):
  264. return obj.encode(encoding)
  265. else:
  266. return obj
  267. def parse_val(v):
  268. """Converts to simple datatypes from SQL query results"""
  269. if isinstance(v, (datetime.date, datetime.datetime)):
  270. v = text_type(v)
  271. elif isinstance(v, datetime.timedelta):
  272. v = ":".join(text_type(v).split(":")[:2])
  273. elif isinstance(v, integer_types):
  274. v = int(v)
  275. return v
  276. def fmt_money(amount, precision=None, currency=None):
  277. """
  278. Convert to string with commas for thousands, millions etc
  279. """
  280. number_format = frappe.db.get_default("number_format") or "#,###.##"
  281. if precision is None:
  282. precision = cint(frappe.db.get_default('currency_precision')) or None
  283. decimal_str, comma_str, number_format_precision = get_number_format_info(number_format)
  284. if precision is None:
  285. precision = number_format_precision
  286. # 40,000 -> 40,000.00
  287. # 40,000.00000 -> 40,000.00
  288. # 40,000.23000 -> 40,000.23
  289. if decimal_str:
  290. parts = str(amount).split(decimal_str)
  291. decimals = parts[1] if len(parts) > 1 else ''
  292. if precision > 2:
  293. if len(decimals) < 3:
  294. precision = 2
  295. elif len(decimals) < precision:
  296. precision = len(decimals)
  297. amount = '%.*f' % (precision, flt(amount))
  298. if amount.find('.') == -1:
  299. decimals = ''
  300. else:
  301. decimals = amount.split('.')[1]
  302. parts = []
  303. minus = ''
  304. if flt(amount) < 0:
  305. minus = '-'
  306. amount = cstr(abs(flt(amount))).split('.')[0]
  307. if len(amount) > 3:
  308. parts.append(amount[-3:])
  309. amount = amount[:-3]
  310. val = number_format=="#,##,###.##" and 2 or 3
  311. while len(amount) > val:
  312. parts.append(amount[-val:])
  313. amount = amount[:-val]
  314. parts.append(amount)
  315. parts.reverse()
  316. amount = comma_str.join(parts) + ((precision and decimal_str) and (decimal_str + decimals) or "")
  317. amount = minus + amount
  318. if currency and frappe.defaults.get_global_default("hide_currency_symbol") != "Yes":
  319. symbol = frappe.db.get_value("Currency", currency, "symbol") or currency
  320. amount = symbol + " " + amount
  321. return amount
  322. number_format_info = {
  323. "#,###.##": (".", ",", 2),
  324. "#.###,##": (",", ".", 2),
  325. "# ###.##": (".", " ", 2),
  326. "# ###,##": (",", " ", 2),
  327. "#'###.##": (".", "'", 2),
  328. "#, ###.##": (".", ", ", 2),
  329. "#,##,###.##": (".", ",", 2),
  330. "#,###.###": (".", ",", 3),
  331. "#.###": ("", ".", 0),
  332. "#,###": ("", ",", 0)
  333. }
  334. def get_number_format_info(format):
  335. return number_format_info.get(format) or (".", ",", 2)
  336. #
  337. # convet currency to words
  338. #
  339. def money_in_words(number, main_currency = None, fraction_currency=None):
  340. """
  341. Returns string in words with currency and fraction currency.
  342. """
  343. from frappe.utils import get_defaults
  344. _ = frappe._
  345. try:
  346. # note: `flt` returns 0 for invalid input and we don't want that
  347. number = float(number)
  348. except ValueError:
  349. return ""
  350. number = flt(number)
  351. if number < 0:
  352. return ""
  353. d = get_defaults()
  354. if not main_currency:
  355. main_currency = d.get('currency', 'INR')
  356. if not fraction_currency:
  357. fraction_currency = frappe.db.get_value("Currency", main_currency, "fraction") or _("Cent")
  358. number_format = frappe.db.get_value("Currency", main_currency, "number_format", cache=True) or \
  359. frappe.db.get_default("number_format") or "#,###.##"
  360. fraction_length = get_number_format_info(number_format)[2]
  361. n = "%.{0}f".format(fraction_length) % number
  362. numbers = n.split('.')
  363. main, fraction = numbers if len(numbers) > 1 else [n, '00']
  364. if len(fraction) < fraction_length:
  365. zeros = '0' * (fraction_length - len(fraction))
  366. fraction += zeros
  367. in_million = True
  368. if number_format == "#,##,###.##": in_million = False
  369. # 0.00
  370. if main == '0' and fraction in ['00', '000']:
  371. out = "{0} {1}".format(main_currency, _('Zero'))
  372. # 0.XX
  373. elif main == '0':
  374. out = _(in_words(fraction, in_million).title()) + ' ' + fraction_currency
  375. else:
  376. out = main_currency + ' ' + _(in_words(main, in_million).title())
  377. if cint(fraction):
  378. out = out + ' ' + _('and') + ' ' + _(in_words(fraction, in_million).title()) + ' ' + fraction_currency
  379. return out + ' ' + _('only.')
  380. #
  381. # convert number to words
  382. #
  383. def in_words(integer, in_million=True):
  384. """
  385. Returns string in words for the given integer.
  386. """
  387. locale = 'en_IN' if not in_million else frappe.local.lang
  388. integer = int(integer)
  389. try:
  390. ret = num2words(integer, lang=locale)
  391. except NotImplementedError:
  392. ret = num2words(integer, lang='en')
  393. return ret.replace('-', ' ')
  394. def is_html(text):
  395. out = False
  396. for key in ["<br>", "<p", "<img", "<div"]:
  397. if key in text:
  398. out = True
  399. break
  400. return out
  401. # from Jinja2 code
  402. _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
  403. def strip_html(text):
  404. """removes anything enclosed in and including <>"""
  405. return _striptags_re.sub("", text)
  406. def escape_html(text):
  407. html_escape_table = {
  408. "&": "&amp;",
  409. '"': "&quot;",
  410. "'": "&apos;",
  411. ">": "&gt;",
  412. "<": "&lt;",
  413. }
  414. return "".join(html_escape_table.get(c,c) for c in text)
  415. def pretty_date(iso_datetime):
  416. """
  417. Takes an ISO time and returns a string representing how
  418. long ago the date represents.
  419. Ported from PrettyDate by John Resig
  420. """
  421. from frappe import _
  422. if not iso_datetime: return ''
  423. import math
  424. if isinstance(iso_datetime, string_types):
  425. iso_datetime = datetime.datetime.strptime(iso_datetime, DATETIME_FORMAT)
  426. now_dt = datetime.datetime.strptime(now(), DATETIME_FORMAT)
  427. dt_diff = now_dt - iso_datetime
  428. # available only in python 2.7+
  429. # dt_diff_seconds = dt_diff.total_seconds()
  430. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  431. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  432. # differnt cases
  433. if dt_diff_seconds < 60.0:
  434. return _('just now')
  435. elif dt_diff_seconds < 120.0:
  436. return _('1 minute ago')
  437. elif dt_diff_seconds < 3600.0:
  438. return _('{0} minutes ago').format(cint(math.floor(dt_diff_seconds / 60.0)))
  439. elif dt_diff_seconds < 7200.0:
  440. return _('1 hour ago')
  441. elif dt_diff_seconds < 86400.0:
  442. return _('{0} hours ago').format(cint(math.floor(dt_diff_seconds / 3600.0)))
  443. elif dt_diff_days == 1.0:
  444. return _('Yesterday')
  445. elif dt_diff_days < 7.0:
  446. return _('{0} days ago').format(cint(dt_diff_days))
  447. elif dt_diff_days < 12:
  448. return _('1 weeks ago')
  449. elif dt_diff_days < 31.0:
  450. return _('{0} weeks ago').format(cint(math.ceil(dt_diff_days / 7.0)))
  451. elif dt_diff_days < 46:
  452. return _('1 month ago')
  453. elif dt_diff_days < 365.0:
  454. return _('{0} months ago').format(cint(math.ceil(dt_diff_days / 30.0)))
  455. elif dt_diff_days < 550.0:
  456. return _('1 year ago')
  457. else:
  458. return '{0} years ago'.format(cint(math.floor(dt_diff_days / 365.0)))
  459. def comma_or(some_list):
  460. return comma_sep(some_list, frappe._("{0} or {1}"))
  461. def comma_and(some_list):
  462. return comma_sep(some_list, frappe._("{0} and {1}"))
  463. def comma_sep(some_list, pattern):
  464. if isinstance(some_list, (list, tuple)):
  465. # list(some_list) is done to preserve the existing list
  466. some_list = [text_type(s) for s in list(some_list)]
  467. if not some_list:
  468. return ""
  469. elif len(some_list) == 1:
  470. return some_list[0]
  471. else:
  472. some_list = ["'%s'" % s for s in some_list]
  473. return pattern.format(", ".join(frappe._(s) for s in some_list[:-1]), some_list[-1])
  474. else:
  475. return some_list
  476. def new_line_sep(some_list):
  477. if isinstance(some_list, (list, tuple)):
  478. # list(some_list) is done to preserve the existing list
  479. some_list = [text_type(s) for s in list(some_list)]
  480. if not some_list:
  481. return ""
  482. elif len(some_list) == 1:
  483. return some_list[0]
  484. else:
  485. some_list = ["%s" % s for s in some_list]
  486. return format("\n ".join(some_list))
  487. else:
  488. return some_list
  489. def filter_strip_join(some_list, sep):
  490. """given a list, filter None values, strip spaces and join"""
  491. return (cstr(sep)).join((cstr(a).strip() for a in filter(None, some_list)))
  492. def get_url(uri=None, full_address=False):
  493. """get app url from request"""
  494. host_name = frappe.local.conf.host_name or frappe.local.conf.hostname
  495. if uri and (uri.startswith("http://") or uri.startswith("https://")):
  496. return uri
  497. if not host_name:
  498. if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host:
  499. protocol = 'https://' if 'https' == frappe.get_request_header('X-Forwarded-Proto', "") else 'http://'
  500. host_name = protocol + frappe.local.request.host
  501. elif frappe.local.site:
  502. protocol = 'http://'
  503. if frappe.local.conf.ssl_certificate:
  504. protocol = 'https://'
  505. elif frappe.local.conf.wildcard:
  506. domain = frappe.local.conf.wildcard.get('domain')
  507. if domain and frappe.local.site.endswith(domain) and frappe.local.conf.wildcard.get('ssl_certificate'):
  508. protocol = 'https://'
  509. host_name = protocol + frappe.local.site
  510. else:
  511. host_name = frappe.db.get_value("Website Settings", "Website Settings",
  512. "subdomain")
  513. if not host_name:
  514. host_name = "http://localhost"
  515. if host_name and not (host_name.startswith("http://") or host_name.startswith("https://")):
  516. host_name = "http://" + host_name
  517. if not uri and full_address:
  518. uri = frappe.get_request_header("REQUEST_URI", "")
  519. if frappe.conf.http_port:
  520. host_name = host_name + ':' + str(frappe.conf.http_port)
  521. url = urljoin(host_name, uri) if uri else host_name
  522. return url
  523. def get_host_name():
  524. return get_url().rsplit("//", 1)[-1]
  525. def get_link_to_form(doctype, name, label=None):
  526. if not label: label = name
  527. return """<a href="{0}">{1}</a>""".format(get_url_to_form(doctype, name), label)
  528. def get_url_to_form(doctype, name):
  529. return get_url(uri = "desk#Form/{0}/{1}".format(quoted(doctype), quoted(name)))
  530. def get_url_to_list(doctype):
  531. return get_url(uri = "desk#List/{0}".format(quoted(doctype)))
  532. def get_url_to_report(name, report_type = None, doctype = None):
  533. if report_type == "Report Builder":
  534. return get_url(uri = "desk#Report/{0}/{1}".format(quoted(doctype), quoted(name)))
  535. else:
  536. return get_url(uri = "desk#query-report/{0}".format(quoted(name)))
  537. operator_map = {
  538. # startswith
  539. "^": lambda a, b: (a or "").startswith(b),
  540. # in or not in a list
  541. "in": lambda a, b: operator.contains(b, a),
  542. "not in": lambda a, b: not operator.contains(b, a),
  543. # comparison operators
  544. "=": lambda a, b: operator.eq(a, b),
  545. "!=": lambda a, b: operator.ne(a, b),
  546. ">": lambda a, b: operator.gt(a, b),
  547. "<": lambda a, b: operator.lt(a, b),
  548. ">=": lambda a, b: operator.ge(a, b),
  549. "<=": lambda a, b: operator.le(a, b),
  550. "not None": lambda a, b: a and True or False,
  551. "None": lambda a, b: (not a) and True or False
  552. }
  553. def evaluate_filters(doc, filters):
  554. '''Returns true if doc matches filters'''
  555. if isinstance(filters, dict):
  556. for key, value in iteritems(filters):
  557. f = get_filter(None, {key:value})
  558. if not compare(doc.get(f.fieldname), f.operator, f.value):
  559. return False
  560. elif isinstance(filters, (list, tuple)):
  561. for d in filters:
  562. f = get_filter(None, d)
  563. if not compare(doc.get(f.fieldname), f.operator, f.value):
  564. return False
  565. return True
  566. def compare(val1, condition, val2):
  567. ret = False
  568. if condition in operator_map:
  569. ret = operator_map[condition](val1, val2)
  570. return ret
  571. def get_filter(doctype, f):
  572. """Returns a _dict like
  573. {
  574. "doctype":
  575. "fieldname":
  576. "operator":
  577. "value":
  578. }
  579. """
  580. from frappe.model import default_fields, optional_fields
  581. if isinstance(f, dict):
  582. key, value = next(iter(f.items()))
  583. f = make_filter_tuple(doctype, key, value)
  584. if not isinstance(f, (list, tuple)):
  585. frappe.throw(frappe._("Filter must be a tuple or list (in a list)"))
  586. if len(f) == 3:
  587. f = (doctype, f[0], f[1], f[2])
  588. elif len(f) != 4:
  589. frappe.throw(frappe._("Filter must have 4 values (doctype, fieldname, operator, value): {0}").format(str(f)))
  590. f = frappe._dict(doctype=f[0], fieldname=f[1], operator=f[2], value=f[3])
  591. if not f.operator:
  592. # if operator is missing
  593. f.operator = "="
  594. valid_operators = ("=", "!=", ">", "<", ">=", "<=", "like", "not like", "in", "not in", "between")
  595. if f.operator.lower() not in valid_operators:
  596. frappe.throw(frappe._("Operator must be one of {0}").format(", ".join(valid_operators)))
  597. if f.doctype and (f.fieldname not in default_fields + optional_fields):
  598. # verify fieldname belongs to the doctype
  599. meta = frappe.get_meta(f.doctype)
  600. if not meta.has_field(f.fieldname):
  601. # try and match the doctype name from child tables
  602. for df in meta.get_table_fields():
  603. if frappe.get_meta(df.options).has_field(f.fieldname):
  604. f.doctype = df.options
  605. break
  606. return f
  607. def make_filter_tuple(doctype, key, value):
  608. '''return a filter tuple like [doctype, key, operator, value]'''
  609. if isinstance(value, (list, tuple)):
  610. return [doctype, key, value[0], value[1]]
  611. else:
  612. return [doctype, key, "=", value]
  613. def make_filter_dict(filters):
  614. '''convert this [[doctype, key, operator, value], ..]
  615. to this { key: (operator, value), .. }
  616. '''
  617. _filter = frappe._dict()
  618. for f in filters:
  619. _filter[f[1]] = (f[2], f[3])
  620. return _filter
  621. def scrub_urls(html):
  622. html = expand_relative_urls(html)
  623. # encoding should be responsibility of the composer
  624. # html = quote_urls(html)
  625. return html
  626. def expand_relative_urls(html):
  627. # expand relative urls
  628. url = get_url()
  629. if url.endswith("/"): url = url[:-1]
  630. def _expand_relative_urls(match):
  631. to_expand = list(match.groups())
  632. if not to_expand[2].startswith('mailto') and not to_expand[2].startswith('data:'):
  633. if not to_expand[2].startswith("/"):
  634. to_expand[2] = "/" + to_expand[2]
  635. to_expand.insert(2, url)
  636. if 'url' in to_expand[0] and to_expand[1].startswith('(') and to_expand[-1].endswith(')'):
  637. # background-image: url('/assets/...') - workaround for wkhtmltopdf print-media-type
  638. to_expand.append(' !important')
  639. return "".join(to_expand)
  640. html = re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)', _expand_relative_urls, html)
  641. # background-image: url('/assets/...')
  642. html = re.sub('(:[\s]?url)(\([\'"]?)([^\)]*)([\'"]?\))', _expand_relative_urls, html)
  643. return html
  644. def quoted(url):
  645. return cstr(quote(encode(url), safe=b"~@#$&()*!+=:;,.?/'"))
  646. def quote_urls(html):
  647. def _quote_url(match):
  648. groups = list(match.groups())
  649. groups[2] = quoted(groups[2])
  650. return "".join(groups)
  651. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?:http)[^\'">]+)([\'"]?)',
  652. _quote_url, html)
  653. def unique(seq):
  654. """use this instead of list(set()) to preserve order of the original list.
  655. Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
  656. seen = set()
  657. seen_add = seen.add
  658. return [ x for x in seq if not (x in seen or seen_add(x)) ]
  659. def strip(val, chars=None):
  660. # \ufeff is no-width-break, \u200b is no-width-space
  661. return (val or "").replace("\ufeff", "").replace("\u200b", "").strip(chars)
  662. def to_markdown(html):
  663. text = None
  664. try:
  665. text = html2text(html)
  666. except HTMLParser.HTMLParseError:
  667. pass
  668. return text