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.
 
 
 
 
 
 

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