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.
 
 
 
 
 
 

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