Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

519 linhas
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. global lang, user_lang
  35. if not user_language:
  36. user_language = conn.get_value("Profile", user, "language")
  37. if user_language:
  38. lang_dict = get_lang_dict()
  39. if user_language in lang_dict:
  40. lang = lang_dict[user_language]
  41. user_lang = True
  42. def load_translations(module, doctype, name):
  43. from webnotes.translate import load_doc_messages
  44. load_doc_messages(module, doctype, name)
  45. # local-globals
  46. conn = local("conn")
  47. form = form_dict = local("form_dict")
  48. request = local("request")
  49. response = local("response")
  50. _response = local("_response")
  51. session = local("session")
  52. user = local("user")
  53. error_log = local("error_log")
  54. debug_log = local("debug_log")
  55. message_log = local("message_log")
  56. lang = local("lang")
  57. def init():
  58. local.error_log = []
  59. local.message_log = []
  60. local.debug_log = []
  61. local.response = _dict({})
  62. local.lang = "en"
  63. _memc = None
  64. mute_emails = False
  65. mute_messages = False
  66. test_objects = {}
  67. request_method = None
  68. print_messages = False
  69. user_lang = False
  70. in_import = False
  71. in_test = False
  72. rollback_on_exception = False
  73. # memcache
  74. def cache():
  75. global _memc
  76. if not _memc:
  77. from webnotes.memc import MClient
  78. _memc = MClient(['localhost:11211'])
  79. return _memc
  80. class DuplicateEntryError(Exception): pass
  81. class ValidationError(Exception): pass
  82. class AuthenticationError(Exception): pass
  83. class PermissionError(Exception): pass
  84. class OutgoingEmailError(ValidationError): pass
  85. class UnknownDomainError(Exception): pass
  86. class SessionStopped(Exception): pass
  87. class MappingMismatchError(ValidationError): pass
  88. class InvalidStatusError(ValidationError): pass
  89. class DoesNotExistError(ValidationError): pass
  90. class MandatoryError(ValidationError): pass
  91. def getTraceback():
  92. import utils
  93. return utils.getTraceback()
  94. def errprint(msg):
  95. from utils import cstr
  96. if not request_method:
  97. print cstr(msg)
  98. error_log.append(cstr(msg))
  99. def log(msg):
  100. if not request_method:
  101. import conf
  102. if getattr(conf, "logging", False):
  103. print repr(msg)
  104. from utils import cstr
  105. debug_log.append(cstr(msg))
  106. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  107. def _raise_exception():
  108. if raise_exception:
  109. if rollback_on_exception:
  110. conn.rollback()
  111. import inspect
  112. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  113. raise raise_exception, msg
  114. else:
  115. raise ValidationError, msg
  116. if mute_messages:
  117. _raise_exception()
  118. return
  119. from utils import cstr
  120. if as_table and type(msg) in (list, tuple):
  121. 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>'
  122. if print_messages:
  123. print "Message: " + repr(msg)
  124. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  125. _raise_exception()
  126. def throw(msg, exc=ValidationError):
  127. msgprint(msg, raise_exception=exc)
  128. def create_folder(path):
  129. import os
  130. try:
  131. os.makedirs(path)
  132. except OSError, e:
  133. if e.args[0]!=17:
  134. raise e
  135. def create_symlink(source_path, link_path):
  136. import os
  137. try:
  138. os.symlink(source_path, link_path)
  139. except OSError, e:
  140. if e.args[0]!=17:
  141. raise e
  142. def remove_file(path):
  143. import os
  144. try:
  145. os.remove(path)
  146. except OSError, e:
  147. if e.args[0]!=2:
  148. raise e
  149. def connect(db_name=None, password=None):
  150. import webnotes.db
  151. local.conn = webnotes.db.Database(user=db_name, password=password)
  152. local.session = _dict({'user':'Administrator'})
  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]") \
  246. in get_user_default_as_list(keys[1]):
  247. return True
  248. else:
  249. match_failed[keys[0]] = refdoc.fields.get(keys[0],"[No Value]")
  250. else:
  251. # found a permission without a match
  252. return True
  253. # no valid permission found
  254. if match_failed:
  255. doctypelist = get_doctype(doctype)
  256. msg = _("Not allowed for: ")
  257. for key in match_failed:
  258. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  259. + " = " + (match_failed[key] or "None")
  260. msgprint(msg)
  261. return False
  262. else:
  263. return perms and True or False
  264. def generate_hash():
  265. """Generates random hash for session id"""
  266. import hashlib, time
  267. return hashlib.sha224(str(time.time())).hexdigest()
  268. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  269. from webnotes.model.code import get_obj
  270. return get_obj(dt, dn, doc, doclist, with_children)
  271. def doc(doctype=None, name=None, fielddata=None):
  272. from webnotes.model.doc import Document
  273. return Document(doctype, name, fielddata)
  274. def new_doc(doctype, parent_doc=None, parentfield=None):
  275. from webnotes.model.create_new import get_new_doc
  276. return get_new_doc(doctype, parent_doc, parentfield)
  277. def new_bean(doctype):
  278. from webnotes.model.create_new import get_new_doc
  279. return bean([get_new_doc(doctype)])
  280. def doclist(lst=None):
  281. from webnotes.model.doclist import DocList
  282. return DocList(lst)
  283. def bean(doctype=None, name=None, copy=None):
  284. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  285. from webnotes.model.bean import Bean
  286. if copy:
  287. return Bean(copy_doclist(copy))
  288. else:
  289. return Bean(doctype, name)
  290. def set_value(doctype, docname, fieldname, value):
  291. import webnotes.client
  292. return webnotes.client.set_value(doctype, docname, fieldname, value)
  293. def get_doclist(doctype, name=None):
  294. return bean(doctype, name).doclist
  295. def get_doctype(doctype, processed=False):
  296. import webnotes.model.doctype
  297. return webnotes.model.doctype.get(doctype, processed)
  298. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False):
  299. import webnotes.model.utils
  300. if not ignore_doctypes:
  301. ignore_doctypes = []
  302. if isinstance(name, list):
  303. for n in name:
  304. webnotes.model.utils.delete_doc(doctype, n, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  305. else:
  306. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  307. def clear_perms(doctype):
  308. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  309. def reset_perms(doctype):
  310. clear_perms(doctype)
  311. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype, force=True)
  312. def reload_doc(module, dt=None, dn=None, force=False):
  313. import webnotes.modules
  314. return webnotes.modules.reload_doc(module, dt, dn, force)
  315. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  316. from webnotes.model.rename_doc import rename_doc
  317. rename_doc(doctype, old, new, force=force, merge=merge)
  318. def insert(doclist):
  319. import webnotes.model
  320. return webnotes.model.insert(doclist)
  321. def get_module(modulename):
  322. __import__(modulename)
  323. import sys
  324. return sys.modules[modulename]
  325. def get_method(method_string):
  326. modulename = '.'.join(method_string.split('.')[:-1])
  327. methodname = method_string.split('.')[-1]
  328. return getattr(get_module(modulename), methodname)
  329. def make_property_setter(args):
  330. args = _dict(args)
  331. bean([{
  332. 'doctype': "Property Setter",
  333. 'doctype_or_field': args.doctype_or_field or "DocField",
  334. 'doc_type': args.doctype,
  335. 'field_name': args.fieldname,
  336. 'property': args.property,
  337. 'value': args.value,
  338. 'property_type': args.property_type or "Data",
  339. '__islocal': 1
  340. }]).save()
  341. def get_application_home_page(user='Guest'):
  342. """get home page for user"""
  343. hpl = conn.sql("""select home_page
  344. from `tabDefault Home Page`
  345. where parent='Control Panel'
  346. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  347. if hpl:
  348. return hpl[0][0]
  349. else:
  350. # no app
  351. try:
  352. from startup import application_home_page
  353. return application_home_page
  354. except ImportError:
  355. return "desktop"
  356. def copy_doclist(in_doclist):
  357. new_doclist = []
  358. parent_doc = None
  359. for i, d in enumerate(in_doclist):
  360. is_dict = False
  361. if isinstance(d, dict):
  362. is_dict = True
  363. values = _dict(d.copy())
  364. else:
  365. values = _dict(d.fields.copy())
  366. newd = new_doc(values.doctype, parent_doc=(None if i==0 else parent_doc), parentfield=values.parentfield)
  367. newd.fields.update(values)
  368. if i==0:
  369. parent_doc = newd
  370. new_doclist.append(newd.fields if is_dict else newd)
  371. return doclist(new_doclist)
  372. def compare(val1, condition, val2):
  373. import webnotes.utils
  374. return webnotes.utils.compare(val1, condition, val2)
  375. def repsond_as_web_page(title, html):
  376. global message, message_title, response
  377. message_title = title
  378. message = "<h3>" + title + "</h3>" + html
  379. response['type'] = 'page'
  380. response['page_name'] = 'message.html'
  381. def load_json(obj):
  382. if isinstance(obj, basestring):
  383. import json
  384. try:
  385. obj = json.loads(obj)
  386. except ValueError:
  387. pass
  388. return obj
  389. def build_match_conditions(doctype, fields=None, as_condition=True, match_filters=None):
  390. import webnotes.widgets.reportview
  391. return webnotes.widgets.reportview.build_match_conditions(doctype, fields, as_condition, match_filters)
  392. def get_list(doctype, filters=None, fields=None, docstatus=None,
  393. group_by=None, order_by=None, limit_start=0, limit_page_length=None,
  394. as_list=False, debug=False):
  395. import webnotes.widgets.reportview
  396. return webnotes.widgets.reportview.execute(doctype, filters=filters, fields=fields, docstatus=docstatus,
  397. group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
  398. as_list=as_list, debug=debug)
  399. _config = None
  400. def get_config():
  401. global _config
  402. if not _config:
  403. import webnotes.utils, json
  404. _config = _dict()
  405. def update_config(path):
  406. try:
  407. with open(path, "r") as configfile:
  408. this_config = json.loads(configfile.read())
  409. for key, val in this_config.items():
  410. if isinstance(val, dict):
  411. _config.setdefault(key, _dict()).update(val)
  412. else:
  413. _config[key] = val
  414. except IOError:
  415. pass
  416. update_config(webnotes.utils.get_path("lib", "config.json"))
  417. update_config(webnotes.utils.get_path("app", "config.json"))
  418. return _config