25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

517 satır
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. return webnotes.request.headers.get(key, default)
  157. remote_ip = get_request_header('REMOTE_ADDR') #Required for login from python shell
  158. logger = None
  159. def get_db_password(db_name):
  160. """get db password from conf"""
  161. import conf
  162. if hasattr(conf, 'get_db_password'):
  163. return conf.get_db_password(db_name)
  164. elif hasattr(conf, 'db_password'):
  165. return conf.db_password
  166. else:
  167. return db_name
  168. whitelisted = []
  169. guest_methods = []
  170. def whitelist(allow_guest=False, allow_roles=None):
  171. """
  172. decorator for whitelisting a function
  173. Note: if the function is allowed to be accessed by a guest user,
  174. it must explicitly be marked as allow_guest=True
  175. for specific roles, set allow_roles = ['Administrator'] etc.
  176. """
  177. def innerfn(fn):
  178. global whitelisted, guest_methods
  179. whitelisted.append(fn)
  180. if allow_guest:
  181. guest_methods.append(fn)
  182. if allow_roles:
  183. roles = get_roles()
  184. allowed = False
  185. for role in allow_roles:
  186. if role in roles:
  187. allowed = True
  188. break
  189. if not allowed:
  190. raise PermissionError, "Method not allowed"
  191. return fn
  192. return innerfn
  193. def clear_cache(user=None, doctype=None):
  194. """clear cache"""
  195. if doctype:
  196. from webnotes.model.doctype import clear_cache
  197. clear_cache(doctype)
  198. elif user:
  199. from webnotes.sessions import clear_cache
  200. clear_cache(user)
  201. else:
  202. from webnotes.sessions import clear_cache
  203. clear_cache()
  204. def get_roles(user=None, with_standard=True):
  205. """get roles of current user"""
  206. if not user:
  207. user = session.user
  208. if user=='Guest':
  209. return ['Guest']
  210. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  211. where parent=%s and role!='All'""", user)] + ['All']
  212. # filter standard if required
  213. if not with_standard:
  214. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  215. return roles
  216. def check_admin_or_system_manager():
  217. if ("System Manager" not in get_roles()) and \
  218. (session.user!="Administrator"):
  219. msgprint("Only Allowed for Role System Manager or Administrator", raise_exception=True)
  220. def has_permission(doctype, ptype="read", refdoc=None):
  221. """check if user has permission"""
  222. from webnotes.defaults import get_user_default_as_list
  223. if session.user=="Administrator":
  224. return True
  225. if conn.get_value("DocType", doctype, "istable"):
  226. return True
  227. if isinstance(refdoc, basestring):
  228. refdoc = doc(doctype, refdoc)
  229. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  230. where p.parent = %s
  231. and ifnull(p.`%s`,0) = 1
  232. and ifnull(p.permlevel,0) = 0
  233. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  234. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  235. if refdoc:
  236. match_failed = {}
  237. for p in perms:
  238. if p.match:
  239. if ":" in p.match:
  240. keys = p.match.split(":")
  241. else:
  242. keys = [p.match, p.match]
  243. if refdoc.fields.get(keys[0],"[No Value]") \
  244. in get_user_default_as_list(keys[1]):
  245. return True
  246. else:
  247. match_failed[keys[0]] = refdoc.fields.get(keys[0],"[No Value]")
  248. else:
  249. # found a permission without a match
  250. return True
  251. # no valid permission found
  252. if match_failed:
  253. doctypelist = get_doctype(doctype)
  254. msg = _("Not allowed for: ")
  255. for key in match_failed:
  256. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  257. + " = " + (match_failed[key] or "None")
  258. msgprint(msg)
  259. return False
  260. else:
  261. return perms and True or False
  262. def generate_hash():
  263. """Generates random hash for session id"""
  264. import hashlib, time
  265. return hashlib.sha224(str(time.time())).hexdigest()
  266. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  267. from webnotes.model.code import get_obj
  268. return get_obj(dt, dn, doc, doclist, with_children)
  269. def doc(doctype=None, name=None, fielddata=None):
  270. from webnotes.model.doc import Document
  271. return Document(doctype, name, fielddata)
  272. def new_doc(doctype, parent_doc=None, parentfield=None):
  273. from webnotes.model.create_new import get_new_doc
  274. return get_new_doc(doctype, parent_doc, parentfield)
  275. def new_bean(doctype):
  276. from webnotes.model.create_new import get_new_doc
  277. return bean([get_new_doc(doctype)])
  278. def doclist(lst=None):
  279. from webnotes.model.doclist import DocList
  280. return DocList(lst)
  281. def bean(doctype=None, name=None, copy=None):
  282. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  283. from webnotes.model.bean import Bean
  284. if copy:
  285. return Bean(copy_doclist(copy))
  286. else:
  287. return Bean(doctype, name)
  288. def set_value(doctype, docname, fieldname, value):
  289. import webnotes.client
  290. return webnotes.client.set_value(doctype, docname, fieldname, value)
  291. def get_doclist(doctype, name=None):
  292. return bean(doctype, name).doclist
  293. def get_doctype(doctype, processed=False):
  294. import webnotes.model.doctype
  295. return webnotes.model.doctype.get(doctype, processed)
  296. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False):
  297. import webnotes.model.utils
  298. if not ignore_doctypes:
  299. ignore_doctypes = []
  300. if isinstance(name, list):
  301. for n in name:
  302. webnotes.model.utils.delete_doc(doctype, n, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  303. else:
  304. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload, ignore_permissions)
  305. def clear_perms(doctype):
  306. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  307. def reset_perms(doctype):
  308. clear_perms(doctype)
  309. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype, force=True)
  310. def reload_doc(module, dt=None, dn=None, force=False):
  311. import webnotes.modules
  312. return webnotes.modules.reload_doc(module, dt, dn, force)
  313. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  314. from webnotes.model.rename_doc import rename_doc
  315. rename_doc(doctype, old, new, force=force, merge=merge)
  316. def insert(doclist):
  317. import webnotes.model
  318. return webnotes.model.insert(doclist)
  319. def get_module(modulename):
  320. __import__(modulename)
  321. import sys
  322. return sys.modules[modulename]
  323. def get_method(method_string):
  324. modulename = '.'.join(method_string.split('.')[:-1])
  325. methodname = method_string.split('.')[-1]
  326. return getattr(get_module(modulename), methodname)
  327. def make_property_setter(args):
  328. args = _dict(args)
  329. bean([{
  330. 'doctype': "Property Setter",
  331. 'doctype_or_field': args.doctype_or_field or "DocField",
  332. 'doc_type': args.doctype,
  333. 'field_name': args.fieldname,
  334. 'property': args.property,
  335. 'value': args.value,
  336. 'property_type': args.property_type or "Data",
  337. '__islocal': 1
  338. }]).save()
  339. def get_application_home_page(user='Guest'):
  340. """get home page for user"""
  341. hpl = conn.sql("""select home_page
  342. from `tabDefault Home Page`
  343. where parent='Control Panel'
  344. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  345. if hpl:
  346. return hpl[0][0]
  347. else:
  348. # no app
  349. try:
  350. from startup import application_home_page
  351. return application_home_page
  352. except ImportError:
  353. return "desktop"
  354. def copy_doclist(in_doclist):
  355. new_doclist = []
  356. parent_doc = None
  357. for i, d in enumerate(in_doclist):
  358. is_dict = False
  359. if isinstance(d, dict):
  360. is_dict = True
  361. values = _dict(d.copy())
  362. else:
  363. values = _dict(d.fields.copy())
  364. newd = new_doc(values.doctype, parent_doc=(None if i==0 else parent_doc), parentfield=values.parentfield)
  365. newd.fields.update(values)
  366. if i==0:
  367. parent_doc = newd
  368. new_doclist.append(newd.fields if is_dict else newd)
  369. return doclist(new_doclist)
  370. def compare(val1, condition, val2):
  371. import webnotes.utils
  372. return webnotes.utils.compare(val1, condition, val2)
  373. def repsond_as_web_page(title, html):
  374. global message, message_title, response
  375. message_title = title
  376. message = "<h3>" + title + "</h3>" + html
  377. response['type'] = 'page'
  378. response['page_name'] = 'message.html'
  379. def load_json(obj):
  380. if isinstance(obj, basestring):
  381. import json
  382. try:
  383. obj = json.loads(obj)
  384. except ValueError:
  385. pass
  386. return obj
  387. def build_match_conditions(doctype, fields=None, as_condition=True, match_filters=None):
  388. import webnotes.widgets.reportview
  389. return webnotes.widgets.reportview.build_match_conditions(doctype, fields, as_condition, match_filters)
  390. def get_list(doctype, filters=None, fields=None, docstatus=None,
  391. group_by=None, order_by=None, limit_start=0, limit_page_length=None,
  392. as_list=False, debug=False):
  393. import webnotes.widgets.reportview
  394. return webnotes.widgets.reportview.execute(doctype, filters=filters, fields=fields, docstatus=docstatus,
  395. group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
  396. as_list=as_list, debug=debug)
  397. _config = None
  398. def get_config():
  399. global _config
  400. if not _config:
  401. import webnotes.utils, json
  402. _config = _dict()
  403. def update_config(path):
  404. try:
  405. with open(path, "r") as configfile:
  406. this_config = json.loads(configfile.read())
  407. for key, val in this_config.items():
  408. if isinstance(val, dict):
  409. _config.setdefault(key, _dict()).update(val)
  410. else:
  411. _config[key] = val
  412. except IOError:
  413. pass
  414. update_config(webnotes.utils.get_path("lib", "config.json"))
  415. update_config(webnotes.utils.get_path("app", "config.json"))
  416. return _config