Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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