Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

535 řádky
15 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  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, release_local
  9. from werkzeug.exceptions import NotFound
  10. from MySQLdb import ProgrammingError as SQLError
  11. import os, sys, importlib
  12. import json
  13. import semantic_version
  14. local = Local()
  15. class _dict(dict):
  16. """dict like object that exposes keys as attributes"""
  17. def __getattr__(self, key):
  18. return self.get(key)
  19. def __setattr__(self, key, value):
  20. self[key] = value
  21. def __getstate__(self):
  22. return self
  23. def __setstate__(self, d):
  24. self.update(d)
  25. def update(self, d):
  26. """update and return self -- the missing dict feature in python"""
  27. super(_dict, self).update(d)
  28. return self
  29. def copy(self):
  30. return _dict(dict(self).copy())
  31. def __getattr__(self, key):
  32. return local.get("key", None)
  33. def _(msg):
  34. """translate object in current lang, if exists"""
  35. if local.lang == "en":
  36. return msg
  37. from webnotes.translate import get_full_dict
  38. return get_full_dict(local.lang).get(msg, msg)
  39. def get_lang_dict(fortype, name=None):
  40. if local.lang=="en":
  41. return {}
  42. from webnotes.translate import get_dict
  43. return get_dict(fortype, name)
  44. def set_user_lang(user, user_language=None):
  45. from webnotes.translate import get_lang_dict
  46. if not user_language:
  47. user_language = conn.get_value("Profile", user, "language")
  48. if user_language:
  49. lang_dict = get_lang_dict()
  50. if user_language in lang_dict:
  51. local.lang = lang_dict[user_language]
  52. # local-globals
  53. conn = local("conn")
  54. conf = local("conf")
  55. form = form_dict = local("form_dict")
  56. request = local("request")
  57. request_method = local("request_method")
  58. response = local("response")
  59. _response = local("_response")
  60. session = local("session")
  61. user = local("user")
  62. flags = local("flags")
  63. restrictions = local("restrictions")
  64. error_log = local("error_log")
  65. debug_log = local("debug_log")
  66. message_log = local("message_log")
  67. lang = local("lang")
  68. def init(site, sites_path=None):
  69. if getattr(local, "initialised", None):
  70. return
  71. if not sites_path:
  72. sites_path = '.'
  73. local.error_log = []
  74. local.site = site
  75. local.sites_path = sites_path
  76. local.site_path = os.path.join(sites_path, site)
  77. local.message_log = []
  78. local.debug_log = []
  79. local.response = _dict({})
  80. local.lang = "en"
  81. local.request_method = request.method if request else None
  82. local.conf = _dict(get_site_config())
  83. local.initialised = True
  84. local.flags = _dict({})
  85. local.rollback_observers = []
  86. local.module_app = None
  87. local.app_modules = None
  88. local.user = None
  89. local.restrictions = None
  90. setup_module_map()
  91. def get_site_config():
  92. site_filepath = os.path.join(local.site_path, "site_config.json")
  93. if os.path.exists(site_filepath):
  94. with open(site_filepath, 'r') as f:
  95. return json.load(f)
  96. else:
  97. return _dict()
  98. def destroy():
  99. """closes connection and releases werkzeug local"""
  100. if conn:
  101. conn.close()
  102. release_local(local)
  103. _memc = None
  104. test_objects = {}
  105. # memcache
  106. def cache():
  107. global _memc
  108. if not _memc:
  109. from webnotes.memc import MClient
  110. _memc = MClient(['localhost:11211'])
  111. return _memc
  112. class DuplicateEntryError(Exception): pass
  113. class ValidationError(Exception): pass
  114. class AuthenticationError(Exception): pass
  115. class PermissionError(Exception): pass
  116. class UnknownDomainError(Exception): pass
  117. class SessionStopped(Exception): pass
  118. class MappingMismatchError(ValidationError): pass
  119. class InvalidStatusError(ValidationError): pass
  120. class DoesNotExistError(ValidationError): pass
  121. class MandatoryError(ValidationError): pass
  122. class InvalidSignatureError(ValidationError): pass
  123. class RateLimitExceededError(ValidationError): pass
  124. def get_traceback():
  125. import utils
  126. return utils.get_traceback()
  127. def errprint(msg):
  128. from utils import cstr
  129. if not request:
  130. print cstr(msg)
  131. error_log.append(cstr(msg))
  132. def log(msg):
  133. if not request:
  134. if conf.get("logging") or False:
  135. print repr(msg)
  136. from utils import cstr
  137. debug_log.append(cstr(msg))
  138. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  139. def _raise_exception():
  140. if raise_exception:
  141. if flags.rollback_on_exception:
  142. conn.rollback()
  143. import inspect
  144. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  145. raise raise_exception, msg
  146. else:
  147. raise ValidationError, msg
  148. if flags.mute_messages:
  149. _raise_exception()
  150. return
  151. from utils import cstr
  152. if as_table and type(msg) in (list, tuple):
  153. 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>'
  154. if flags.print_messages:
  155. print "Message: " + repr(msg)
  156. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  157. _raise_exception()
  158. def throw(msg, exc=ValidationError):
  159. msgprint(msg, raise_exception=exc)
  160. def create_folder(path):
  161. if not os.path.exists(path): os.makedirs(path)
  162. def connect(site=None, db_name=None):
  163. from db import Database
  164. if site:
  165. init(site)
  166. local.conn = Database(user=db_name or local.conf.db_name)
  167. local.response = _dict()
  168. local.form_dict = _dict()
  169. local.session = _dict()
  170. set_user("Administrator")
  171. def set_user(username):
  172. import webnotes.profile
  173. local.session["user"] = username
  174. local.user = webnotes.profile.Profile(username)
  175. local.restrictions = None
  176. def get_request_header(key, default=None):
  177. return request.headers.get(key, default)
  178. logger = None
  179. whitelisted = []
  180. guest_methods = []
  181. def whitelist(allow_guest=False):
  182. """
  183. decorator for whitelisting a function
  184. Note: if the function is allowed to be accessed by a guest user,
  185. it must explicitly be marked as allow_guest=True
  186. for specific roles, set allow_roles = ['Administrator'] etc.
  187. """
  188. def innerfn(fn):
  189. global whitelisted, guest_methods
  190. whitelisted.append(fn)
  191. if allow_guest:
  192. guest_methods.append(fn)
  193. return fn
  194. return innerfn
  195. def only_for(roles):
  196. if not isinstance(roles, (tuple, list)):
  197. roles = (roles,)
  198. roles = set(roles)
  199. myroles = set(get_roles())
  200. if not roles.intersection(myroles):
  201. raise PermissionError
  202. def clear_cache(user=None, doctype=None):
  203. """clear cache"""
  204. import webnotes.sessions
  205. if doctype:
  206. import webnotes.model.doctype
  207. webnotes.model.doctype.clear_cache(doctype)
  208. reset_metadata_version()
  209. elif user:
  210. webnotes.sessions.clear_cache(user)
  211. else: # everything
  212. import translate
  213. webnotes.sessions.clear_cache()
  214. translate.clear_cache()
  215. reset_metadata_version()
  216. def get_roles(username=None):
  217. import webnotes.profile
  218. if not local.session:
  219. return ["Guest"]
  220. elif not username or username==local.session.user:
  221. return local.user.get_roles()
  222. else:
  223. return webnotes.profile.Profile(username).get_roles()
  224. def has_permission(doctype, ptype="read", refdoc=None):
  225. import webnotes.permissions
  226. return webnotes.permissions.has_permission(doctype, ptype, refdoc)
  227. def clear_perms(doctype):
  228. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  229. def reset_perms(doctype):
  230. clear_perms(doctype)
  231. reload_doc(conn.get_value("DocType", doctype, "module"),
  232. "DocType", doctype, force=True)
  233. def generate_hash():
  234. """Generates random hash for session id"""
  235. import hashlib, time
  236. return hashlib.sha224(str(time.time())).hexdigest()
  237. def reset_metadata_version():
  238. v = generate_hash()
  239. cache().set_value("metadata_version", v)
  240. return v
  241. def get_obj(dt = None, dn = None, doc=None, doclist=None, with_children = True):
  242. from webnotes.model.code import get_obj
  243. return get_obj(dt, dn, doc, doclist, with_children)
  244. def doc(doctype=None, name=None, fielddata=None):
  245. from webnotes.model.doc import Document
  246. return Document(doctype, name, fielddata)
  247. def new_doc(doctype, parent_doc=None, parentfield=None):
  248. from webnotes.model.create_new import get_new_doc
  249. return get_new_doc(doctype, parent_doc, parentfield)
  250. def new_bean(doctype):
  251. from webnotes.model.create_new import get_new_doc
  252. return bean([get_new_doc(doctype)])
  253. def doclist(lst=None):
  254. from webnotes.model.doclist import DocList
  255. return DocList(lst)
  256. def bean(doctype=None, name=None, copy=None):
  257. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  258. from webnotes.model.bean import Bean
  259. if copy:
  260. return Bean(copy_doclist(copy))
  261. else:
  262. return Bean(doctype, name)
  263. def set_value(doctype, docname, fieldname, value):
  264. import webnotes.client
  265. return webnotes.client.set_value(doctype, docname, fieldname, value)
  266. def get_doclist(doctype, name=None):
  267. return bean(doctype, name).doclist
  268. def get_doctype(doctype, processed=False):
  269. import webnotes.model.doctype
  270. return webnotes.model.doctype.get(doctype, processed)
  271. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None,
  272. for_reload=False, ignore_permissions=False):
  273. import webnotes.model.delete_doc
  274. if not ignore_doctypes:
  275. ignore_doctypes = []
  276. if isinstance(name, list):
  277. for n in name:
  278. webnotes.model.delete_doc.delete_doc(doctype, n, doclist, force, ignore_doctypes,
  279. for_reload, ignore_permissions)
  280. else:
  281. webnotes.model.delete_doc.delete_doc(doctype, name, doclist, force, ignore_doctypes,
  282. for_reload, ignore_permissions)
  283. def reload_doc(module, dt=None, dn=None, force=False):
  284. import webnotes.modules
  285. return webnotes.modules.reload_doc(module, dt, dn, force=force)
  286. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  287. from webnotes.model.rename_doc import rename_doc
  288. return rename_doc(doctype, old, new, force=force, merge=merge)
  289. def insert(doclist):
  290. import webnotes.model
  291. return webnotes.model.insert(doclist)
  292. def get_module(modulename):
  293. return importlib.import_module(modulename)
  294. def scrub(txt):
  295. return txt.replace(' ','_').replace('-', '_').replace('/', '_').lower()
  296. def get_module_path(module, *joins):
  297. module = scrub(module)
  298. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  299. def get_pymodule_path(modulename, *joins):
  300. joins = [scrub(part) for part in joins]
  301. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  302. def get_module_list(app_name):
  303. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  304. def get_all_apps(with_webnotes=False):
  305. apps = get_file_items(os.path.join(local.sites_path, "apps.txt")) \
  306. + get_file_items(os.path.join(local.site_path, "apps.txt"))
  307. if with_webnotes:
  308. apps.insert(0, 'webnotes')
  309. return apps
  310. def get_installed_apps():
  311. if flags.in_install_db:
  312. return []
  313. return json.loads(conn.get_global("installed_apps") or "[]")
  314. def get_hooks(app_name=None):
  315. def load_app_hooks(app_name=None):
  316. hooks = {}
  317. for app in [app_name] if app_name else get_installed_apps():
  318. for item in get_file_items(get_pymodule_path(app, "hooks.txt")):
  319. key, value = item.split("=", 1)
  320. key, value = key.strip(), value.strip()
  321. hooks.setdefault(key, [])
  322. hooks[key].append(value)
  323. return hooks
  324. if app_name:
  325. return _dict(load_app_hooks(app_name))
  326. else:
  327. return _dict(cache().get_value("app_hooks", load_app_hooks))
  328. def setup_module_map():
  329. _cache = cache()
  330. if conf.db_name:
  331. local.app_modules = _cache.get_value("app_modules")
  332. local.module_app = _cache.get_value("module_app")
  333. if not local.app_modules:
  334. local.module_app, local.app_modules = {}, {}
  335. for app in get_all_apps(True):
  336. local.app_modules.setdefault(app, [])
  337. for module in get_module_list(app):
  338. local.module_app[module] = app
  339. local.app_modules[app].append(module)
  340. if conf.db_name:
  341. _cache.set_value("app_modules", local.app_modules)
  342. _cache.set_value("module_app", local.module_app)
  343. def get_file_items(path):
  344. content = read_file(path)
  345. if content:
  346. return [p.strip() for p in content.splitlines() if p.strip() and not p.startswith("#")]
  347. else:
  348. return []
  349. def read_file(path):
  350. if os.path.exists(path):
  351. with open(path, "r") as f:
  352. return unicode(f.read(), encoding="utf-8")
  353. else:
  354. return None
  355. def get_attr(method_string):
  356. modulename = '.'.join(method_string.split('.')[:-1])
  357. methodname = method_string.split('.')[-1]
  358. return getattr(get_module(modulename), methodname)
  359. def make_property_setter(args):
  360. args = _dict(args)
  361. bean([{
  362. 'doctype': "Property Setter",
  363. 'doctype_or_field': args.doctype_or_field or "DocField",
  364. 'doc_type': args.doctype,
  365. 'field_name': args.fieldname,
  366. 'property': args.property,
  367. 'value': args.value,
  368. 'property_type': args.property_type or "Data",
  369. '__islocal': 1
  370. }]).save()
  371. def get_application_home_page(user='Guest'):
  372. """get home page for user"""
  373. hpl = conn.sql("""select home_page
  374. from `tabDefault Home Page`
  375. where parent='Control Panel'
  376. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  377. if hpl:
  378. return hpl[0][0]
  379. else:
  380. return conn.get_value("Control Panel", None, "home_page")
  381. def copy_doclist(in_doclist):
  382. new_doclist = []
  383. parent_doc = None
  384. for i, d in enumerate(in_doclist):
  385. is_dict = False
  386. if isinstance(d, dict):
  387. is_dict = True
  388. values = _dict(d.copy())
  389. else:
  390. values = _dict(d.fields.copy())
  391. newd = new_doc(values.doctype, parent_doc=(None if i==0 else parent_doc), parentfield=values.parentfield)
  392. newd.fields.update(values)
  393. if i==0:
  394. parent_doc = newd
  395. new_doclist.append(newd.fields if is_dict else newd)
  396. return doclist(new_doclist)
  397. def compare(val1, condition, val2):
  398. import webnotes.utils
  399. return webnotes.utils.compare(val1, condition, val2)
  400. def repsond_as_web_page(title, html):
  401. local.message_title = title
  402. local.message = "<h3>" + title + "</h3>" + html
  403. local.response['type'] = 'page'
  404. local.response['page_name'] = 'message.html'
  405. return obj
  406. def build_match_conditions(doctype, fields=None, as_condition=True):
  407. import webnotes.widgets.reportview
  408. return webnotes.widgets.reportview.build_match_conditions(doctype, fields, as_condition)
  409. def get_list(doctype, filters=None, fields=None, docstatus=None,
  410. group_by=None, order_by=None, limit_start=0, limit_page_length=None,
  411. as_list=False, debug=False):
  412. import webnotes.widgets.reportview
  413. return webnotes.widgets.reportview.execute(doctype, filters=filters, fields=fields, docstatus=docstatus,
  414. group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
  415. as_list=as_list, debug=debug)
  416. jenv = None
  417. def get_jenv():
  418. global jenv
  419. if not jenv:
  420. from jinja2 import Environment, ChoiceLoader, PackageLoader
  421. from webnotes.utils import global_date_format
  422. from markdown2 import markdown
  423. from json import dumps
  424. # webnotes will be loaded last, so app templates will get precedence
  425. jenv = Environment(loader = ChoiceLoader([PackageLoader(app, ".") \
  426. for app in get_all_apps() + ["webnotes"]]))
  427. jenv.filters["global_date_format"] = global_date_format
  428. jenv.filters["markdown"] = markdown
  429. jenv.filters["json"] = dumps
  430. return jenv
  431. def get_template(path):
  432. return get_jenv().get_template(path)