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.
 
 
 
 
 
 

519 lines
14 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. """
  4. globals attached to webnotes module
  5. + some utility functions that should probably be moved
  6. """
  7. from __future__ import unicode_literals
  8. from werkzeug.local import Local
  9. local = Local()
  10. class _dict(dict):
  11. """dict like object that exposes keys as attributes"""
  12. def __getattr__(self, key):
  13. return self.get(key)
  14. def __setattr__(self, key, value):
  15. self[key] = value
  16. def __getstate__(self):
  17. return self
  18. def __setstate__(self, d):
  19. self.update(d)
  20. def update(self, d):
  21. """update and return self -- the missing dict feature in python"""
  22. super(_dict, self).update(d)
  23. return self
  24. def copy(self):
  25. return _dict(super(_dict, self).copy())
  26. def __getattr__(self, key):
  27. return webnotes.local.get("key", None)
  28. def _(msg):
  29. """translate object in current lang, if exists"""
  30. from webnotes.translate import messages
  31. return messages.get(lang, {}).get(msg, msg)
  32. def set_user_lang(user, user_language=None):
  33. from webnotes.translate import get_lang_dict
  34. if not user_language:
  35. user_language = conn.get_value("Profile", user, "language")
  36. if user_language:
  37. lang_dict = get_lang_dict()
  38. if user_language in lang_dict:
  39. local.lang = lang_dict[user_language]
  40. def load_translations(module, doctype, name):
  41. from webnotes.translate import load_doc_messages
  42. load_doc_messages(module, doctype, name)
  43. # local-globals
  44. conn = local("conn")
  45. form = form_dict = local("form_dict")
  46. request = local("request")
  47. request_method = local("request_method")
  48. response = local("response")
  49. _response = local("_response")
  50. session = local("session")
  51. user = local("user")
  52. error_log = local("error_log")
  53. debug_log = local("debug_log")
  54. message_log = local("message_log")
  55. lang = local("lang")
  56. def init():
  57. local.error_log = []
  58. local.message_log = []
  59. local.debug_log = []
  60. local.response = _dict({})
  61. local.lang = "en"
  62. local.request_method = request.method if request else None
  63. _memc = None
  64. mute_emails = False
  65. mute_messages = False
  66. test_objects = {}
  67. print_messages = False
  68. in_import = False
  69. in_test = False
  70. rollback_on_exception = False
  71. # memcache
  72. def cache():
  73. global _memc
  74. if not _memc:
  75. from webnotes.memc import MClient
  76. _memc = MClient(['localhost:11211'])
  77. return _memc
  78. class DuplicateEntryError(Exception): pass
  79. class ValidationError(Exception): pass
  80. class AuthenticationError(Exception): pass
  81. class PermissionError(Exception): pass
  82. class OutgoingEmailError(ValidationError): pass
  83. class UnknownDomainError(Exception): pass
  84. class SessionStopped(Exception): pass
  85. class MappingMismatchError(ValidationError): pass
  86. class InvalidStatusError(ValidationError): pass
  87. class DoesNotExistError(ValidationError): pass
  88. class MandatoryError(ValidationError): pass
  89. def getTraceback():
  90. import utils
  91. return utils.getTraceback()
  92. def errprint(msg):
  93. from utils import cstr
  94. if not request:
  95. print cstr(msg)
  96. error_log.append(cstr(msg))
  97. def log(msg):
  98. if not request:
  99. import conf
  100. if getattr(conf, "logging", False):
  101. print repr(msg)
  102. from utils import cstr
  103. debug_log.append(cstr(msg))
  104. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  105. def _raise_exception():
  106. if raise_exception:
  107. if rollback_on_exception:
  108. conn.rollback()
  109. import inspect
  110. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  111. raise raise_exception, msg
  112. else:
  113. raise ValidationError, msg
  114. if mute_messages:
  115. _raise_exception()
  116. return
  117. from utils import cstr
  118. if as_table and type(msg) in (list, tuple):
  119. msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>'
  120. if print_messages:
  121. print "Message: " + repr(msg)
  122. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  123. _raise_exception()
  124. def throw(msg, exc=ValidationError):
  125. msgprint(msg, raise_exception=exc)
  126. def create_folder(path):
  127. import os
  128. try:
  129. os.makedirs(path)
  130. except OSError, e:
  131. if e.args[0]!=17:
  132. raise e
  133. def create_symlink(source_path, link_path):
  134. import os
  135. try:
  136. os.symlink(source_path, link_path)
  137. except OSError, e:
  138. if e.args[0]!=17:
  139. raise e
  140. def remove_file(path):
  141. import os
  142. try:
  143. os.remove(path)
  144. except OSError, e:
  145. if e.args[0]!=2:
  146. raise e
  147. def connect(db_name=None, password=None):
  148. import webnotes.db
  149. local.conn = webnotes.db.Database(user=db_name, password=password)
  150. local.session = _dict({'user':'Administrator'})
  151. local.response = _dict()
  152. local.form_dict = _dict()
  153. import webnotes.profile
  154. local.user = webnotes.profile.Profile('Administrator')
  155. def get_request_header(key, default=None):
  156. try:
  157. return request.headers.get(key, default)
  158. except Exception, e:
  159. return None
  160. logger = None
  161. def get_db_password(db_name):
  162. """get db password from conf"""
  163. import conf
  164. if hasattr(conf, 'get_db_password'):
  165. return conf.get_db_password(db_name)
  166. elif hasattr(conf, 'db_password'):
  167. return conf.db_password
  168. else:
  169. return db_name
  170. whitelisted = []
  171. guest_methods = []
  172. def whitelist(allow_guest=False, allow_roles=None):
  173. """
  174. decorator for whitelisting a function
  175. Note: if the function is allowed to be accessed by a guest user,
  176. it must explicitly be marked as allow_guest=True
  177. for specific roles, set allow_roles = ['Administrator'] etc.
  178. """
  179. def innerfn(fn):
  180. global whitelisted, guest_methods
  181. whitelisted.append(fn)
  182. if allow_guest:
  183. guest_methods.append(fn)
  184. if allow_roles:
  185. roles = get_roles()
  186. allowed = False
  187. for role in allow_roles:
  188. if role in roles:
  189. allowed = True
  190. break
  191. if not allowed:
  192. raise PermissionError, "Method not allowed"
  193. return fn
  194. return innerfn
  195. def clear_cache(user=None, doctype=None):
  196. """clear cache"""
  197. if doctype:
  198. from webnotes.model.doctype import clear_cache
  199. clear_cache(doctype)
  200. elif user:
  201. from webnotes.sessions import clear_cache
  202. clear_cache(user)
  203. else:
  204. from webnotes.sessions import clear_cache
  205. clear_cache()
  206. def get_roles(user=None, with_standard=True):
  207. """get roles of current user"""
  208. if not user:
  209. user = session.user
  210. if user=='Guest':
  211. return ['Guest']
  212. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  213. where parent=%s and role!='All'""", user)] + ['All']
  214. # filter standard if required
  215. if not with_standard:
  216. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  217. return roles
  218. def check_admin_or_system_manager():
  219. if ("System Manager" not in get_roles()) and \
  220. (session.user!="Administrator"):
  221. msgprint("Only Allowed for Role System Manager or Administrator", raise_exception=True)
  222. def has_permission(doctype, ptype="read", refdoc=None):
  223. """check if user has permission"""
  224. from webnotes.defaults import get_user_default_as_list
  225. if session.user=="Administrator":
  226. return True
  227. if conn.get_value("DocType", doctype, "istable"):
  228. return True
  229. if isinstance(refdoc, basestring):
  230. refdoc = doc(doctype, refdoc)
  231. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  232. where p.parent = %s
  233. and ifnull(p.`%s`,0) = 1
  234. and ifnull(p.permlevel,0) = 0
  235. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  236. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  237. if refdoc:
  238. match_failed = {}
  239. for p in perms:
  240. if p.match:
  241. if ":" in p.match:
  242. keys = p.match.split(":")
  243. else:
  244. keys = [p.match, p.match]
  245. if refdoc.fields.get(keys[0],"[No Value]") in get_user_default_as_list(keys[1]):
  246. return True
  247. else:
  248. match_failed[keys[0]] = refdoc.fields.get(keys[0],"[No Value]")
  249. else:
  250. # found a permission without a match
  251. return True
  252. # no valid permission found
  253. if match_failed:
  254. doctypelist = get_doctype(doctype)
  255. msg = _("Not allowed for: ")
  256. for key in match_failed:
  257. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  258. + " = " + (match_failed[key] or "None")
  259. msgprint(msg)
  260. return False
  261. else:
  262. return perms and True or False
  263. def generate_hash():
  264. """Generates random hash for session id"""
  265. import hashlib, time
  266. return hashlib.sha224(str(time.time())).hexdigest()
  267. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  268. from webnotes.model.code import get_obj
  269. return get_obj(dt, dn, doc, doclist, with_children)
  270. def doc(doctype=None, name=None, fielddata=None):
  271. from webnotes.model.doc import Document
  272. return Document(doctype, name, fielddata)
  273. def new_doc(doctype, parent_doc=None, parentfield=None):
  274. from webnotes.model.create_new import get_new_doc
  275. return get_new_doc(doctype, parent_doc, parentfield)
  276. def new_bean(doctype):
  277. from webnotes.model.create_new import get_new_doc
  278. return bean([get_new_doc(doctype)])
  279. def doclist(lst=None):
  280. from webnotes.model.doclist import DocList
  281. return DocList(lst)
  282. def bean(doctype=None, name=None, copy=None):
  283. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  284. from webnotes.model.bean import Bean
  285. if copy:
  286. return Bean(copy_doclist(copy))
  287. else:
  288. return Bean(doctype, name)
  289. def set_value(doctype, docname, fieldname, value):
  290. import webnotes.client
  291. return webnotes.client.set_value(doctype, docname, fieldname, value)
  292. def get_doclist(doctype, name=None):
  293. return bean(doctype, name).doclist
  294. def get_doctype(doctype, processed=False):
  295. import webnotes.model.doctype
  296. return webnotes.model.doctype.get(doctype, processed)
  297. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False):
  298. import webnotes.model.utils
  299. if not ignore_doctypes:
  300. ignore_doctypes = []
  301. if isinstance(name, list):
  302. for n in name:
  303. webnotes.model.utils.delete_doc(doctype, n, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  304. else:
  305. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  306. def clear_perms(doctype):
  307. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  308. def reset_perms(doctype):
  309. clear_perms(doctype)
  310. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype, force=True)
  311. def reload_doc(module, dt=None, dn=None, force=False):
  312. import webnotes.modules
  313. return webnotes.modules.reload_doc(module, dt, dn, force)
  314. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  315. from webnotes.model.rename_doc import rename_doc
  316. rename_doc(doctype, old, new, force=force, merge=merge)
  317. def insert(doclist):
  318. import webnotes.model
  319. return webnotes.model.insert(doclist)
  320. def get_module(modulename):
  321. __import__(modulename)
  322. import sys
  323. return sys.modules[modulename]
  324. def get_method(method_string):
  325. modulename = '.'.join(method_string.split('.')[:-1])
  326. methodname = method_string.split('.')[-1]
  327. return getattr(get_module(modulename), methodname)
  328. def make_property_setter(args):
  329. args = _dict(args)
  330. bean([{
  331. 'doctype': "Property Setter",
  332. 'doctype_or_field': args.doctype_or_field or "DocField",
  333. 'doc_type': args.doctype,
  334. 'field_name': args.fieldname,
  335. 'property': args.property,
  336. 'value': args.value,
  337. 'property_type': args.property_type or "Data",
  338. '__islocal': 1
  339. }]).save()
  340. def get_application_home_page(user='Guest'):
  341. """get home page for user"""
  342. hpl = conn.sql("""select home_page
  343. from `tabDefault Home Page`
  344. where parent='Control Panel'
  345. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  346. if hpl:
  347. return hpl[0][0]
  348. else:
  349. # no app
  350. try:
  351. from startup import application_home_page
  352. return application_home_page
  353. except ImportError:
  354. return "desktop"
  355. def copy_doclist(in_doclist):
  356. new_doclist = []
  357. parent_doc = None
  358. for i, d in enumerate(in_doclist):
  359. is_dict = False
  360. if isinstance(d, dict):
  361. is_dict = True
  362. values = _dict(d.copy())
  363. else:
  364. values = _dict(d.fields.copy())
  365. newd = new_doc(values.doctype, parent_doc=(None if i==0 else parent_doc), parentfield=values.parentfield)
  366. newd.fields.update(values)
  367. if i==0:
  368. parent_doc = newd
  369. new_doclist.append(newd.fields if is_dict else newd)
  370. return doclist(new_doclist)
  371. def compare(val1, condition, val2):
  372. import webnotes.utils
  373. return webnotes.utils.compare(val1, condition, val2)
  374. def repsond_as_web_page(title, html):
  375. global message, message_title, response
  376. message_title = title
  377. message = "<h3>" + title + "</h3>" + html
  378. response['type'] = 'page'
  379. response['page_name'] = 'message.html'
  380. def load_json(obj):
  381. if isinstance(obj, basestring):
  382. import json
  383. try:
  384. obj = json.loads(obj)
  385. except ValueError:
  386. pass
  387. return obj
  388. def build_match_conditions(doctype, fields=None, as_condition=True, match_filters=None):
  389. import webnotes.widgets.reportview
  390. return webnotes.widgets.reportview.build_match_conditions(doctype, fields, as_condition, match_filters)
  391. def get_list(doctype, filters=None, fields=None, docstatus=None,
  392. group_by=None, order_by=None, limit_start=0, limit_page_length=None,
  393. as_list=False, debug=False):
  394. import webnotes.widgets.reportview
  395. return webnotes.widgets.reportview.execute(doctype, filters=filters, fields=fields, docstatus=docstatus,
  396. group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
  397. as_list=as_list, debug=debug)
  398. _config = None
  399. def get_config():
  400. global _config
  401. if not _config:
  402. import webnotes.utils, json
  403. _config = _dict()
  404. def update_config(path):
  405. try:
  406. with open(path, "r") as configfile:
  407. this_config = json.loads(configfile.read())
  408. for key, val in this_config.items():
  409. if isinstance(val, dict):
  410. _config.setdefault(key, _dict()).update(val)
  411. else:
  412. _config[key] = val
  413. except IOError:
  414. pass
  415. update_config(webnotes.utils.get_path("lib", "config.json"))
  416. update_config(webnotes.utils.get_path("app", "config.json"))
  417. return _config