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.
 
 
 
 
 
 

820 lines
21 KiB

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