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.
 
 
 
 
 
 

929 lines
23 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. # util __init__.py
  4. from __future__ import unicode_literals
  5. from webnotes import conf
  6. import webnotes
  7. no_value_fields = ['Section Break', 'Column Break', 'HTML', 'Table', 'FlexTable',
  8. 'Button', 'Image', 'Graph']
  9. default_fields = ['doctype', 'name', 'owner', 'creation', 'modified', 'modified_by',
  10. 'parent', 'parentfield', 'parenttype', 'idx', 'docstatus']
  11. # used in import_docs.py
  12. # TODO: deprecate it
  13. def getCSVelement(v):
  14. """
  15. Returns the CSV value of `v`, For example:
  16. * apple becomes "apple"
  17. * hi"there becomes "hi""there"
  18. """
  19. v = cstr(v)
  20. if not v: return ''
  21. if (',' in v) or ('\n' in v) or ('"' in v):
  22. if '"' in v: v = v.replace('"', '""')
  23. return '"'+v+'"'
  24. else: return v or ''
  25. def get_fullname(profile):
  26. """get the full name (first name + last name) of the user from Profile"""
  27. p = webnotes.conn.sql("""select first_name, last_name from `tabProfile`
  28. where name=%s""", profile, as_dict=1)
  29. if p:
  30. profile = " ".join(filter(None,
  31. [p[0].get('first_name'), p[0].get('last_name')])) or profile
  32. return profile
  33. def get_formatted_email(user):
  34. """get email id of user formatted as: John Doe <johndoe@example.com>"""
  35. if user == "Administrator":
  36. return user
  37. from email.utils import formataddr
  38. fullname = get_fullname(user)
  39. return formataddr((fullname, user))
  40. def extract_email_id(email):
  41. """fetch only the email part of the email id"""
  42. from email.utils import parseaddr
  43. fullname, email_id = parseaddr(email)
  44. if isinstance(email_id, basestring) and not isinstance(email_id, unicode):
  45. email_id = email_id.decode("utf-8", "ignore")
  46. return email_id
  47. def validate_email_add(email_str):
  48. """Validates the email string"""
  49. email = extract_email_id(email_str)
  50. import re
  51. return re.match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email.lower())
  52. def get_request_site_address(full_address=False):
  53. """get app url from request"""
  54. import os
  55. host_name = conf.host_name
  56. if not host_name:
  57. if webnotes.request:
  58. protocol = 'https' == webnotes.get_request_header('X-Forwarded-Proto', "") and 'https://' or 'http://'
  59. host_name = protocol + webnotes.request.host
  60. else:
  61. return "http://localhost"
  62. if full_address:
  63. return host_name + webnotes.get_request_header("REQUEST_URI", "")
  64. else:
  65. return host_name
  66. def random_string(length):
  67. """generate a random string"""
  68. import string
  69. from random import choice
  70. return ''.join([choice(string.letters + string.digits) for i in range(length)])
  71. def load_json(arg):
  72. # already a dictionary?
  73. if not isinstance(arg, basestring):
  74. return arg
  75. import json
  76. return json.loads(arg, encoding='utf-8')
  77. # Get Traceback
  78. # ==============================================================================
  79. def getTraceback():
  80. """
  81. Returns the traceback of the Exception
  82. """
  83. import sys, traceback
  84. exc_type, value, tb = sys.exc_info()
  85. trace_list = traceback.format_tb(tb, None) + \
  86. traceback.format_exception_only(exc_type, value)
  87. body = "Traceback (innermost last):\n" + "%-20s %s" % \
  88. (unicode((b"").join(trace_list[:-1]), 'utf-8'), unicode(trace_list[-1], 'utf-8'))
  89. if webnotes.logger:
  90. webnotes.logger.error('Db:'+(webnotes.conn and webnotes.conn.cur_db_name or '') \
  91. + ' - ' + body)
  92. return body
  93. def log(event, details):
  94. webnotes.logger.info(details)
  95. # datetime functions
  96. def getdate(string_date):
  97. """
  98. Coverts string date (yyyy-mm-dd) to datetime.date object
  99. """
  100. import datetime
  101. if isinstance(string_date, datetime.date):
  102. return string_date
  103. elif isinstance(string_date, datetime.datetime):
  104. return datetime.date()
  105. if " " in string_date:
  106. string_date = string_date.split(" ")[0]
  107. return datetime.datetime.strptime(string_date, "%Y-%m-%d").date()
  108. def add_to_date(date, years=0, months=0, days=0):
  109. """Adds `days` to the given date"""
  110. format = isinstance(date, basestring)
  111. if date:
  112. date = getdate(date)
  113. else:
  114. raise Exception, "Start date required"
  115. from dateutil.relativedelta import relativedelta
  116. date += relativedelta(years=years, months=months, days=days)
  117. if format:
  118. return date.strftime("%Y-%m-%d")
  119. else:
  120. return date
  121. def add_days(date, days):
  122. return add_to_date(date, days=days)
  123. def add_months(date, months):
  124. return add_to_date(date, months=months)
  125. def add_years(date, years):
  126. return add_to_date(date, years=years)
  127. def date_diff(string_ed_date, string_st_date):
  128. return (getdate(string_ed_date) - getdate(string_st_date)).days
  129. def time_diff(string_ed_date, string_st_date):
  130. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  131. def time_diff_in_seconds(string_ed_date, string_st_date):
  132. return time_diff(string_ed_date, string_st_date).seconds
  133. def time_diff_in_hours(string_ed_date, string_st_date):
  134. return round(float(time_diff(string_ed_date, string_st_date).seconds) / 3600, 6)
  135. def now_datetime():
  136. from datetime import datetime
  137. return convert_utc_to_user_timezone(datetime.utcnow())
  138. def get_user_time_zone():
  139. if getattr(webnotes.local, "user_time_zone", None) is None:
  140. webnotes.local.user_time_zone = webnotes.cache().get_value("time_zone")
  141. if not webnotes.local.user_time_zone:
  142. webnotes.local.user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
  143. or 'Asia/Calcutta'
  144. webnotes.cache().set_value("time_zone", webnotes.local.user_time_zone)
  145. return webnotes.local.user_time_zone
  146. def convert_utc_to_user_timezone(utc_timestamp):
  147. from pytz import timezone, UnknownTimeZoneError
  148. utcnow = timezone('UTC').localize(utc_timestamp)
  149. try:
  150. return utcnow.astimezone(timezone(get_user_time_zone()))
  151. except UnknownTimeZoneError:
  152. return utcnow
  153. def now():
  154. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  155. if getattr(webnotes.local, "current_date", None):
  156. return getdate(webnotes.local.current_date).strftime("%Y-%m-%d") + " " + \
  157. now_datetime().strftime('%H:%M:%S')
  158. else:
  159. return now_datetime().strftime('%Y-%m-%d %H:%M:%S')
  160. def nowdate():
  161. """return current date as yyyy-mm-dd"""
  162. return now_datetime().strftime('%Y-%m-%d')
  163. def today():
  164. return nowdate()
  165. def nowtime():
  166. """return current time in hh:mm"""
  167. return now_datetime().strftime('%H:%M')
  168. def get_first_day(dt, d_years=0, d_months=0):
  169. """
  170. Returns the first day of the month for the date specified by date object
  171. Also adds `d_years` and `d_months` if specified
  172. """
  173. import datetime
  174. dt = getdate(dt)
  175. # d_years, d_months are "deltas" to apply to dt
  176. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  177. year = dt.year + d_years + overflow_years
  178. return datetime.date(year, month + 1, 1)
  179. def get_last_day(dt):
  180. """
  181. Returns last day of the month using:
  182. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  183. """
  184. import datetime
  185. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  186. def get_datetime(datetime_str):
  187. from datetime import datetime
  188. if isinstance(datetime_str, datetime):
  189. return datetime_str.replace(microsecond=0, tzinfo=None)
  190. return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
  191. def get_datetime_str(datetime_obj):
  192. if isinstance(datetime_obj, basestring):
  193. datetime_obj = get_datetime(datetime_obj)
  194. return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')
  195. def formatdate(string_date=None):
  196. """
  197. Convers the given string date to :data:`user_format`
  198. User format specified in :term:`Control Panel`
  199. Examples:
  200. * dd-mm-yyyy
  201. * mm-dd-yyyy
  202. * dd/mm/yyyy
  203. """
  204. if string_date:
  205. string_date = getdate(string_date)
  206. else:
  207. string_date = now_datetime().date()
  208. if getattr(webnotes.local, "user_format", None) is None:
  209. webnotes.local.user_format = webnotes.conn.get_default("date_format")
  210. out = webnotes.local.user_format
  211. return out.replace("dd", string_date.strftime("%d"))\
  212. .replace("mm", string_date.strftime("%m"))\
  213. .replace("yyyy", string_date.strftime("%Y"))
  214. def global_date_format(date):
  215. """returns date as 1 January 2012"""
  216. formatted_date = getdate(date).strftime("%d %B %Y")
  217. return formatted_date.startswith("0") and formatted_date[1:] or formatted_date
  218. def dict_to_str(args, sep='&'):
  219. """
  220. Converts a dictionary to URL
  221. """
  222. import urllib
  223. t = []
  224. for k in args.keys():
  225. t.append(str(k)+'='+urllib.quote(str(args[k] or '')))
  226. return sep.join(t)
  227. def timestamps_equal(t1, t2):
  228. """Returns true if same the two string timestamps are same"""
  229. scrub = lambda x: x.replace(':', ' ').replace('-',' ').split()
  230. t1, t2 = scrub(t1), scrub(t2)
  231. if len(t1) != len(t2):
  232. return
  233. for i in range(len(t1)):
  234. if t1[i]!=t2[i]:
  235. return
  236. return 1
  237. def has_common(l1, l2):
  238. """Returns truthy value if there are common elements in lists l1 and l2"""
  239. return set(l1) & set(l2)
  240. def flt(s, precision=None):
  241. """Convert to float (ignore commas)"""
  242. if isinstance(s, basestring):
  243. s = s.replace(',','')
  244. try:
  245. num = float(s)
  246. if precision is not None:
  247. num = _round(num, precision)
  248. except Exception:
  249. num = 0
  250. return num
  251. def cint(s):
  252. """Convert to integer"""
  253. try: num = int(float(s))
  254. except: num = 0
  255. return num
  256. def cstr(s):
  257. if isinstance(s, unicode):
  258. return s
  259. elif s==None:
  260. return ''
  261. elif isinstance(s, basestring):
  262. return unicode(s, 'utf-8')
  263. else:
  264. return unicode(s)
  265. def _round(num, precision=0):
  266. """round method for round halfs to nearest even algorithm"""
  267. precision = cint(precision)
  268. multiplier = 10 ** precision
  269. # avoid rounding errors
  270. num = round(num * multiplier if precision else num, 8)
  271. import math
  272. floor = math.floor(num)
  273. decimal_part = num - floor
  274. if decimal_part == 0.5:
  275. num = floor if (floor % 2 == 0) else floor + 1
  276. else:
  277. num = round(num)
  278. return (num / multiplier) if precision else num
  279. def encode(obj, encoding="utf-8"):
  280. if isinstance(obj, list):
  281. out = []
  282. for o in obj:
  283. if isinstance(o, unicode):
  284. out.append(o.encode(encoding))
  285. else:
  286. out.append(o)
  287. return out
  288. elif isinstance(obj, unicode):
  289. return obj.encode(encoding)
  290. else:
  291. return obj
  292. def parse_val(v):
  293. """Converts to simple datatypes from SQL query results"""
  294. import datetime
  295. if isinstance(v, (datetime.date, datetime.datetime)):
  296. v = unicode(v)
  297. elif isinstance(v, datetime.timedelta):
  298. v = ":".join(unicode(v).split(":")[:2])
  299. elif isinstance(v, long):
  300. v = int(v)
  301. return v
  302. def fmt_money(amount, precision=None, currency=None):
  303. """
  304. Convert to string with commas for thousands, millions etc
  305. """
  306. number_format = webnotes.conn.get_default("number_format") or "#,###.##"
  307. decimal_str, comma_str, precision = get_number_format_info(number_format)
  308. amount = '%.*f' % (precision, flt(amount))
  309. if amount.find('.') == -1:
  310. decimals = ''
  311. else:
  312. decimals = amount.split('.')[1]
  313. parts = []
  314. minus = ''
  315. if flt(amount) < 0:
  316. minus = '-'
  317. amount = cstr(abs(flt(amount))).split('.')[0]
  318. if len(amount) > 3:
  319. parts.append(amount[-3:])
  320. amount = amount[:-3]
  321. val = number_format=="#,##,###.##" and 2 or 3
  322. while len(amount) > val:
  323. parts.append(amount[-val:])
  324. amount = amount[:-val]
  325. parts.append(amount)
  326. parts.reverse()
  327. amount = comma_str.join(parts) + (precision and (decimal_str + decimals) or "")
  328. amount = minus + amount
  329. if currency:
  330. symbol = webnotes.conn.get_value("Currency", currency, "symbol")
  331. if symbol:
  332. amount = symbol + " " + amount
  333. return amount
  334. number_format_info = {
  335. "#.###": ("", ".", 0),
  336. "#,###": ("", ",", 0),
  337. "#,###.##": (".", ",", 2),
  338. "#,##,###.##": (".", ",", 2),
  339. "#.###,##": (",", ".", 2),
  340. "# ###.##": (".", " ", 2),
  341. "#,###.###": (".", ",", 3),
  342. }
  343. def get_number_format_info(format):
  344. return number_format_info.get(format) or (".", ",", 2)
  345. #
  346. # convet currency to words
  347. #
  348. def money_in_words(number, main_currency = None, fraction_currency=None):
  349. """
  350. Returns string in words with currency and fraction currency.
  351. """
  352. d = get_defaults()
  353. if not main_currency:
  354. main_currency = d.get('currency', 'INR')
  355. if not fraction_currency:
  356. fraction_currency = webnotes.conn.get_value("Currency", main_currency, "fraction") or "Cent"
  357. n = "%.2f" % flt(number)
  358. main, fraction = n.split('.')
  359. if len(fraction)==1: fraction += '0'
  360. number_format = webnotes.conn.get_value("Currency", main_currency, "number_format") or \
  361. webnotes.conn.get_default("number_format") or "#,###.##"
  362. in_million = True
  363. if number_format == "#,##,###.##": in_million = False
  364. out = main_currency + ' ' + in_words(main, in_million).title()
  365. if cint(fraction):
  366. out = out + ' and ' + in_words(fraction, in_million).title() + ' ' + fraction_currency
  367. return out + ' only.'
  368. #
  369. # convert number to words
  370. #
  371. def in_words(integer, in_million=True):
  372. """
  373. Returns string in words for the given integer.
  374. """
  375. n=int(integer)
  376. known = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
  377. 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
  378. 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
  379. def psn(n, known, xpsn):
  380. import sys;
  381. if n in known: return known[n]
  382. bestguess, remainder = str(n), 0
  383. if n<=20:
  384. webnotes.errprint(sys.stderr)
  385. webnotes.errprint(n)
  386. webnotes.errprint("How did this happen?")
  387. assert 0
  388. elif n < 100:
  389. bestguess= xpsn((n//10)*10, known, xpsn) + '-' + xpsn(n%10, known, xpsn)
  390. return bestguess
  391. elif n < 1000:
  392. bestguess= xpsn(n//100, known, xpsn) + ' ' + 'hundred'
  393. remainder = n%100
  394. else:
  395. if in_million:
  396. if n < 1000000:
  397. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  398. remainder = n%1000
  399. elif n < 1000000000:
  400. bestguess= xpsn(n//1000000, known, xpsn) + ' ' + 'million'
  401. remainder = n%1000000
  402. else:
  403. bestguess= xpsn(n//1000000000, known, xpsn) + ' ' + 'billion'
  404. remainder = n%1000000000
  405. else:
  406. if n < 100000:
  407. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  408. remainder = n%1000
  409. elif n < 10000000:
  410. bestguess= xpsn(n//100000, known, xpsn) + ' ' + 'lakh'
  411. remainder = n%100000
  412. else:
  413. bestguess= xpsn(n//10000000, known, xpsn) + ' ' + 'crore'
  414. remainder = n%10000000
  415. if remainder:
  416. if remainder >= 100:
  417. comma = ','
  418. else:
  419. comma = ''
  420. return bestguess + comma + ' ' + xpsn(remainder, known, xpsn)
  421. else:
  422. return bestguess
  423. return psn(n, known, psn)
  424. # Get Defaults
  425. # ==============================================================================
  426. def get_defaults(key=None):
  427. """
  428. Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed
  429. """
  430. return webnotes.conn.get_defaults(key)
  431. def set_default(key, val):
  432. """
  433. Set / add a default value to :term:`Control Panel`
  434. """
  435. return webnotes.conn.set_default(key, val)
  436. def remove_blanks(d):
  437. """
  438. Returns d with empty ('' or None) values stripped
  439. """
  440. empty_keys = []
  441. for key in d:
  442. if d[key]=='' or d[key]==None:
  443. # del d[key] raises runtime exception, using a workaround
  444. empty_keys.append(key)
  445. for key in empty_keys:
  446. del d[key]
  447. return d
  448. def pprint_dict(d, level=1, no_blanks=True):
  449. """
  450. Pretty print a dictionary with indents
  451. """
  452. if no_blanks:
  453. remove_blanks(d)
  454. # make indent
  455. indent, ret = '', ''
  456. for i in range(0,level): indent += '\t'
  457. # add lines
  458. comment, lines = '', []
  459. kl = d.keys()
  460. kl.sort()
  461. # make lines
  462. for key in kl:
  463. if key != '##comment':
  464. tmp = {key: d[key]}
  465. lines.append(indent + str(tmp)[1:-1] )
  466. # add comment string
  467. if '##comment' in kl:
  468. ret = ('\n' + indent) + '# ' + d['##comment'] + '\n'
  469. # open
  470. ret += indent + '{\n'
  471. # lines
  472. ret += indent + ',\n\t'.join(lines)
  473. # close
  474. ret += '\n' + indent + '}'
  475. return ret
  476. def get_common(d1,d2):
  477. """
  478. returns (list of keys) the common part of two dicts
  479. """
  480. return [p for p in d1 if p in d2 and d1[p]==d2[p]]
  481. def get_common_dict(d1, d2):
  482. """
  483. return common dictionary of d1 and d2
  484. """
  485. ret = {}
  486. for key in d1:
  487. if key in d2 and d2[key]==d1[key]:
  488. ret[key] = d1[key]
  489. return ret
  490. def get_diff_dict(d1, d2):
  491. """
  492. return common dictionary of d1 and d2
  493. """
  494. diff_keys = set(d2.keys()).difference(set(d1.keys()))
  495. ret = {}
  496. for d in diff_keys: ret[d] = d2[d]
  497. return ret
  498. def get_file_timestamp(fn):
  499. """
  500. Returns timestamp of the given file
  501. """
  502. import os
  503. from webnotes.utils import cint
  504. try:
  505. return str(cint(os.stat(fn).st_mtime))
  506. except OSError, e:
  507. if e.args[0]!=2:
  508. raise
  509. else:
  510. return None
  511. # to be deprecated
  512. def make_esc(esc_chars):
  513. """
  514. Function generator for Escaping special characters
  515. """
  516. return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
  517. # esc / unescape characters -- used for command line
  518. def esc(s, esc_chars):
  519. """
  520. Escape special characters
  521. """
  522. if not s:
  523. return ""
  524. for c in esc_chars:
  525. esc_str = '\\' + c
  526. s = s.replace(c, esc_str)
  527. return s
  528. def unesc(s, esc_chars):
  529. """
  530. UnEscape special characters
  531. """
  532. for c in esc_chars:
  533. esc_str = '\\' + c
  534. s = s.replace(esc_str, c)
  535. return s
  536. def is_html(text):
  537. out = False
  538. for key in ["<br>", "<p", "<img", "<div"]:
  539. if key in text:
  540. out = True
  541. break
  542. return out
  543. def strip_html(text):
  544. """
  545. removes anything enclosed in and including <>
  546. """
  547. import re
  548. return re.compile(r'<.*?>').sub('', text)
  549. def escape_html(text):
  550. html_escape_table = {
  551. "&": "&amp;",
  552. '"': "&quot;",
  553. "'": "&apos;",
  554. ">": "&gt;",
  555. "<": "&lt;",
  556. }
  557. return "".join(html_escape_table.get(c,c) for c in text)
  558. def get_doctype_label(dt=None):
  559. """
  560. Gets label of a doctype
  561. """
  562. if dt:
  563. res = webnotes.conn.sql("""\
  564. SELECT name, dt_label FROM `tabDocType Label`
  565. WHERE name=%s""", dt)
  566. return res and res[0][0] or dt
  567. else:
  568. res = webnotes.conn.sql("SELECT name, dt_label FROM `tabDocType Label`")
  569. dt_label_dict = {}
  570. for r in res:
  571. dt_label_dict[r[0]] = r[1]
  572. return dt_label_dict
  573. def get_label_doctype(label):
  574. """
  575. Gets doctype from its label
  576. """
  577. res = webnotes.conn.sql("""\
  578. SELECT name FROM `tabDocType Label`
  579. WHERE dt_label=%s""", label)
  580. return res and res[0][0] or label
  581. def pretty_date(iso_datetime):
  582. """
  583. Takes an ISO time and returns a string representing how
  584. long ago the date represents.
  585. Ported from PrettyDate by John Resig
  586. """
  587. if not iso_datetime: return ''
  588. from datetime import datetime
  589. import math
  590. if isinstance(iso_datetime, basestring):
  591. iso_datetime = datetime.strptime(iso_datetime, '%Y-%m-%d %H:%M:%S')
  592. now_dt = datetime.strptime(now(), '%Y-%m-%d %H:%M:%S')
  593. dt_diff = now_dt - iso_datetime
  594. # available only in python 2.7+
  595. # dt_diff_seconds = dt_diff.total_seconds()
  596. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  597. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  598. # differnt cases
  599. if dt_diff_seconds < 60.0:
  600. return 'just now'
  601. elif dt_diff_seconds < 120.0:
  602. return '1 minute ago'
  603. elif dt_diff_seconds < 3600.0:
  604. return '%s minutes ago' % cint(math.floor(dt_diff_seconds / 60.0))
  605. elif dt_diff_seconds < 7200.0:
  606. return '1 hour ago'
  607. elif dt_diff_seconds < 86400.0:
  608. return '%s hours ago' % cint(math.floor(dt_diff_seconds / 3600.0))
  609. elif dt_diff_days == 1.0:
  610. return 'Yesterday'
  611. elif dt_diff_days < 7.0:
  612. return '%s days ago' % cint(dt_diff_days)
  613. elif dt_diff_days < 31.0:
  614. return '%s week(s) ago' % cint(math.ceil(dt_diff_days / 7.0))
  615. elif dt_diff_days < 365.0:
  616. return '%s months ago' % cint(math.ceil(dt_diff_days / 30.0))
  617. else:
  618. return 'more than %s year(s) ago' % cint(math.floor(dt_diff_days / 365.0))
  619. def execute_in_shell(cmd, verbose=0):
  620. # using Popen instead of os.system - as recommended by python docs
  621. from subprocess import Popen
  622. import tempfile
  623. with tempfile.TemporaryFile() as stdout:
  624. with tempfile.TemporaryFile() as stderr:
  625. p = Popen(cmd, shell=True, stdout=stdout, stderr=stderr)
  626. p.wait()
  627. stdout.seek(0)
  628. out = stdout.read()
  629. stderr.seek(0)
  630. err = stderr.read()
  631. if verbose:
  632. if err: print err
  633. if out: print out
  634. return err, out
  635. def comma_or(some_list):
  636. return comma_sep(some_list, " or ")
  637. def comma_and(some_list):
  638. return comma_sep(some_list, " and ")
  639. def comma_sep(some_list, sep):
  640. if isinstance(some_list, (list, tuple)):
  641. # list(some_list) is done to preserve the existing list
  642. some_list = [unicode(s) for s in list(some_list)]
  643. if not some_list:
  644. return ""
  645. elif len(some_list) == 1:
  646. return some_list[0]
  647. else:
  648. some_list = ["'%s'" % s for s in some_list]
  649. return ", ".join(some_list[:-1]) + sep + some_list[-1]
  650. else:
  651. return some_list
  652. def filter_strip_join(some_list, sep):
  653. """given a list, filter None values, strip spaces and join"""
  654. return (cstr(sep)).join((cstr(a).strip() for a in filter(None, some_list)))
  655. def get_path(*path, **kwargs):
  656. base = kwargs.get('base')
  657. if not base:
  658. base = get_base_path()
  659. import os
  660. return os.path.join(base, *path)
  661. def get_base_path():
  662. import conf
  663. import os
  664. return os.path.dirname(os.path.abspath(conf.__file__))
  665. def get_site_base_path(sites_dir=None, hostname=None):
  666. if not sites_dir:
  667. sites_dir = conf.sites_dir
  668. if not hostname:
  669. hostname = conf.site
  670. if not (sites_dir and hostname):
  671. return get_base_path()
  672. import os
  673. return os.path.join(sites_dir, hostname)
  674. def get_site_path(*path):
  675. return get_path(base=get_site_base_path(), *path)
  676. def get_files_path():
  677. return get_site_path(webnotes.conf.files_path)
  678. def get_backups_path():
  679. return get_site_path(webnotes.conf.backup_path)
  680. def get_url(uri=None):
  681. url = get_request_site_address()
  682. if not url or "localhost" in url:
  683. subdomain = webnotes.conn.get_value("Website Settings", "Website Settings",
  684. "subdomain")
  685. if subdomain:
  686. if "http" not in subdomain:
  687. url = "http://" + subdomain
  688. if uri:
  689. import urllib
  690. url = urllib.basejoin(url, uri)
  691. return url
  692. def get_url_to_form(doctype, name, base_url=None, label=None):
  693. if not base_url:
  694. base_url = get_url()
  695. if not label: label = name
  696. return """<a href="%(base_url)s/app.html#!Form/%(doctype)s/%(name)s">%(label)s</a>""" % locals()
  697. def encode_dict(d, encoding="utf-8"):
  698. for key in d:
  699. if isinstance(d[key], basestring) and isinstance(d[key], unicode):
  700. d[key] = d[key].encode(encoding)
  701. return d
  702. def decode_dict(d, encoding="utf-8"):
  703. for key in d:
  704. if isinstance(d[key], basestring) and not isinstance(d[key], unicode):
  705. d[key] = d[key].decode(encoding, "ignore")
  706. return d
  707. import operator
  708. operator_map = {
  709. # startswith
  710. "^": lambda (a, b): (a or "").startswith(b),
  711. # in or not in a list
  712. "in": lambda (a, b): operator.contains(b, a),
  713. "not in": lambda (a, b): not operator.contains(b, a),
  714. # comparison operators
  715. "=": lambda (a, b): operator.eq(a, b),
  716. "!=": lambda (a, b): operator.ne(a, b),
  717. ">": lambda (a, b): operator.gt(a, b),
  718. "<": lambda (a, b): operator.lt(a, b),
  719. ">=": lambda (a, b): operator.ge(a, b),
  720. "<=": lambda (a, b): operator.le(a, b),
  721. "not None": lambda (a, b): a and True or False,
  722. "None": lambda (a, b): (not a) and True or False
  723. }
  724. def compare(val1, condition, val2):
  725. if condition in operator_map:
  726. return operator_map[condition]((val1, val2))
  727. return False
  728. def get_site_name(hostname):
  729. return hostname.split(':')[0]
  730. def get_disk_usage():
  731. """get disk usage of files folder"""
  732. import os
  733. files_path = get_files_path()
  734. if not os.path.exists(files_path):
  735. return 0
  736. err, out = execute_in_shell("du -hsm {files_path}".format(files_path=files_path))
  737. return cint(out.split("\n")[-2].split("\t")[0])
  738. def expand_partial_links(html):
  739. import re
  740. url = get_url()
  741. if not url.endswith("/"): url += "/"
  742. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)',
  743. '\g<1>\g<2>{}\g<3>\g<4>'.format(url), html)