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.
 
 
 
 
 
 

551 lines
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 DataError(Exception): pass
  117. class UnknownDomainError(Exception): pass
  118. class SessionStopped(Exception): pass
  119. class MappingMismatchError(ValidationError): pass
  120. class InvalidStatusError(ValidationError): pass
  121. class DoesNotExistError(ValidationError): pass
  122. class MandatoryError(ValidationError): pass
  123. class InvalidSignatureError(ValidationError): pass
  124. class RateLimitExceededError(ValidationError): pass
  125. class OutgoingEmailError(Exception): pass
  126. def get_traceback():
  127. import utils
  128. return utils.get_traceback()
  129. def errprint(msg):
  130. from utils import cstr
  131. if not request:
  132. print cstr(msg)
  133. error_log.append(cstr(msg))
  134. def log(msg):
  135. if not request:
  136. if conf.get("logging") or False:
  137. print repr(msg)
  138. from utils import cstr
  139. debug_log.append(cstr(msg))
  140. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  141. def _raise_exception():
  142. if raise_exception:
  143. if flags.rollback_on_exception:
  144. conn.rollback()
  145. import inspect
  146. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  147. raise raise_exception, msg
  148. else:
  149. raise ValidationError, msg
  150. if flags.mute_messages:
  151. _raise_exception()
  152. return
  153. from utils import cstr
  154. if as_table and type(msg) in (list, tuple):
  155. 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>'
  156. if flags.print_messages:
  157. print "Message: " + repr(msg)
  158. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  159. _raise_exception()
  160. def throw(msg, exc=ValidationError):
  161. msgprint(msg, raise_exception=exc)
  162. def create_folder(path):
  163. if not os.path.exists(path): os.makedirs(path)
  164. def connect(site=None, db_name=None):
  165. from db import Database
  166. if site:
  167. init(site)
  168. local.conn = Database(user=db_name or local.conf.db_name)
  169. local.response = _dict()
  170. local.form_dict = _dict()
  171. local.session = _dict()
  172. set_user("Administrator")
  173. def set_user(username):
  174. import webnotes.profile
  175. local.session["user"] = username
  176. local.user = webnotes.profile.Profile(username)
  177. local.restrictions = None
  178. def get_request_header(key, default=None):
  179. return request.headers.get(key, default)
  180. logger = None
  181. whitelisted = []
  182. guest_methods = []
  183. def whitelist(allow_guest=False):
  184. """
  185. decorator for whitelisting a function
  186. Note: if the function is allowed to be accessed by a guest user,
  187. it must explicitly be marked as allow_guest=True
  188. for specific roles, set allow_roles = ['Administrator'] etc.
  189. """
  190. def innerfn(fn):
  191. global whitelisted, guest_methods
  192. whitelisted.append(fn)
  193. if allow_guest:
  194. guest_methods.append(fn)
  195. return fn
  196. return innerfn
  197. def only_for(roles):
  198. if not isinstance(roles, (tuple, list)):
  199. roles = (roles,)
  200. roles = set(roles)
  201. myroles = set(get_roles())
  202. if not roles.intersection(myroles):
  203. raise PermissionError
  204. def clear_cache(user=None, doctype=None):
  205. """clear cache"""
  206. import webnotes.sessions
  207. if doctype:
  208. import webnotes.model.doctype
  209. webnotes.model.doctype.clear_cache(doctype)
  210. reset_metadata_version()
  211. elif user:
  212. webnotes.sessions.clear_cache(user)
  213. else: # everything
  214. import translate
  215. webnotes.sessions.clear_cache()
  216. translate.clear_cache()
  217. reset_metadata_version()
  218. def get_roles(username=None):
  219. import webnotes.profile
  220. if not local.session:
  221. return ["Guest"]
  222. elif not username or username==local.session.user:
  223. return local.user.get_roles()
  224. else:
  225. return webnotes.profile.Profile(username).get_roles()
  226. def has_permission(doctype, ptype="read", refdoc=None):
  227. import webnotes.permissions
  228. return webnotes.permissions.has_permission(doctype, ptype, refdoc)
  229. def clear_perms(doctype):
  230. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  231. def reset_perms(doctype):
  232. clear_perms(doctype)
  233. reload_doc(conn.get_value("DocType", doctype, "module"),
  234. "DocType", doctype, force=True)
  235. def generate_hash(txt=None):
  236. """Generates random hash for session id"""
  237. import hashlib, time
  238. return hashlib.sha224((txt or "") + str(time.time())).hexdigest()
  239. def reset_metadata_version():
  240. v = generate_hash()
  241. cache().set_value("metadata_version", v)
  242. return v
  243. def get_obj(dt = None, dn = None, doc=None, doclist=None, with_children = True):
  244. from webnotes.model.code import get_obj
  245. return get_obj(dt, dn, doc, doclist, with_children)
  246. def doc(doctype=None, name=None, fielddata=None):
  247. from webnotes.model.doc import Document
  248. return Document(doctype, name, fielddata)
  249. def new_doc(doctype, parent_doc=None, parentfield=None):
  250. from webnotes.model.create_new import get_new_doc
  251. return get_new_doc(doctype, parent_doc, parentfield)
  252. def new_bean(doctype):
  253. from webnotes.model.create_new import get_new_doc
  254. return bean([get_new_doc(doctype)])
  255. def doclist(lst=None):
  256. from webnotes.model.doclist import DocList
  257. return DocList(lst)
  258. def bean(doctype=None, name=None, copy=None):
  259. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  260. from webnotes.model.bean import Bean
  261. if copy:
  262. return Bean(copy_doclist(copy))
  263. else:
  264. return Bean(doctype, name)
  265. def set_value(doctype, docname, fieldname, value):
  266. import webnotes.client
  267. return webnotes.client.set_value(doctype, docname, fieldname, value)
  268. def get_doclist(doctype, name=None):
  269. return bean(doctype, name).doclist
  270. def get_doctype(doctype, processed=False):
  271. import webnotes.model.doctype
  272. return webnotes.model.doctype.get(doctype, processed)
  273. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None,
  274. for_reload=False, ignore_permissions=False):
  275. import webnotes.model.delete_doc
  276. if not ignore_doctypes:
  277. ignore_doctypes = []
  278. if isinstance(name, list):
  279. for n in name:
  280. webnotes.model.delete_doc.delete_doc(doctype, n, doclist, force, ignore_doctypes,
  281. for_reload, ignore_permissions)
  282. else:
  283. webnotes.model.delete_doc.delete_doc(doctype, name, doclist, force, ignore_doctypes,
  284. for_reload, ignore_permissions)
  285. def reload_doc(module, dt=None, dn=None, force=False):
  286. import webnotes.modules
  287. return webnotes.modules.reload_doc(module, dt, dn, force=force)
  288. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  289. from webnotes.model.rename_doc import rename_doc
  290. return rename_doc(doctype, old, new, force=force, merge=merge)
  291. def insert(doclist):
  292. import webnotes.model
  293. return webnotes.model.insert(doclist)
  294. def get_module(modulename):
  295. return importlib.import_module(modulename)
  296. def scrub(txt):
  297. return txt.replace(' ','_').replace('-', '_').replace('/', '_').lower()
  298. def get_module_path(module, *joins):
  299. module = scrub(module)
  300. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  301. def get_pymodule_path(modulename, *joins):
  302. joins = [scrub(part) for part in joins]
  303. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  304. def get_module_list(app_name):
  305. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  306. def get_all_apps(with_webnotes=False):
  307. apps = get_file_items(os.path.join(local.sites_path, "apps.txt")) \
  308. + get_file_items(os.path.join(local.site_path, "apps.txt"))
  309. if with_webnotes:
  310. apps.insert(0, 'webnotes')
  311. return apps
  312. def get_installed_apps():
  313. if flags.in_install_db:
  314. return []
  315. installed = json.loads(conn.get_global("installed_apps") or "[]")
  316. return installed
  317. def get_hooks(app_name=None):
  318. def load_app_hooks(app_name=None):
  319. hooks = {}
  320. for app in [app_name] if app_name else get_installed_apps():
  321. for item in get_file_items(get_pymodule_path(app, "hooks.txt")):
  322. key, value = item.split("=", 1)
  323. key, value = key.strip(), value.strip()
  324. hooks.setdefault(key, [])
  325. hooks[key].append(value)
  326. return hooks
  327. if app_name:
  328. return _dict(load_app_hooks(app_name))
  329. else:
  330. return _dict(cache().get_value("app_hooks", load_app_hooks))
  331. def setup_module_map():
  332. _cache = cache()
  333. if conf.db_name:
  334. local.app_modules = _cache.get_value("app_modules")
  335. local.module_app = _cache.get_value("module_app")
  336. if not local.app_modules:
  337. local.module_app, local.app_modules = {}, {}
  338. for app in get_all_apps(True):
  339. local.app_modules.setdefault(app, [])
  340. for module in get_module_list(app):
  341. local.module_app[module] = app
  342. local.app_modules[app].append(module)
  343. if conf.db_name:
  344. _cache.set_value("app_modules", local.app_modules)
  345. _cache.set_value("module_app", local.module_app)
  346. def get_file_items(path):
  347. content = read_file(path)
  348. if content:
  349. return [p.strip() for p in content.splitlines() if p.strip() and not p.startswith("#")]
  350. else:
  351. return []
  352. def read_file(path):
  353. if os.path.exists(path):
  354. with open(path, "r") as f:
  355. return unicode(f.read(), encoding="utf-8")
  356. else:
  357. return None
  358. def get_attr(method_string):
  359. modulename = '.'.join(method_string.split('.')[:-1])
  360. methodname = method_string.split('.')[-1]
  361. return getattr(get_module(modulename), methodname)
  362. def make_property_setter(args):
  363. args = _dict(args)
  364. bean([{
  365. 'doctype': "Property Setter",
  366. 'doctype_or_field': args.doctype_or_field or "DocField",
  367. 'doc_type': args.doctype,
  368. 'field_name': args.fieldname,
  369. 'property': args.property,
  370. 'value': args.value,
  371. 'property_type': args.property_type or "Data",
  372. '__islocal': 1
  373. }]).save()
  374. def get_application_home_page(user='Guest'):
  375. """get home page for user"""
  376. hpl = conn.sql("""select home_page
  377. from `tabDefault Home Page`
  378. where parent='Control Panel'
  379. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  380. if hpl:
  381. return hpl[0][0]
  382. else:
  383. return conn.get_value("Control Panel", None, "home_page")
  384. def copy_doclist(in_doclist):
  385. new_doclist = []
  386. parent_doc = None
  387. for i, d in enumerate(in_doclist):
  388. is_dict = False
  389. if isinstance(d, dict):
  390. is_dict = True
  391. values = _dict(d.copy())
  392. else:
  393. values = _dict(d.fields.copy())
  394. newd = new_doc(values.doctype, parent_doc=(None if i==0 else parent_doc), parentfield=values.parentfield)
  395. newd.fields.update(values)
  396. if i==0:
  397. parent_doc = newd
  398. new_doclist.append(newd.fields if is_dict else newd)
  399. return doclist(new_doclist)
  400. def compare(val1, condition, val2):
  401. import webnotes.utils
  402. return webnotes.utils.compare(val1, condition, val2)
  403. def repsond_as_web_page(title, html):
  404. local.message_title = title
  405. local.message = "<h3>" + title + "</h3>" + html
  406. local.response['type'] = 'page'
  407. local.response['page_name'] = 'message.html'
  408. return obj
  409. def build_match_conditions(doctype, fields=None, as_condition=True):
  410. import webnotes.widgets.reportview
  411. return webnotes.widgets.reportview.build_match_conditions(doctype, fields, as_condition)
  412. def get_list(doctype, filters=None, fields=None, docstatus=None,
  413. group_by=None, order_by=None, limit_start=0, limit_page_length=None,
  414. as_list=False, debug=False):
  415. import webnotes.widgets.reportview
  416. return webnotes.widgets.reportview.execute(doctype, filters=filters, fields=fields, docstatus=docstatus,
  417. group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
  418. as_list=as_list, debug=debug)
  419. jenv = None
  420. def get_jenv():
  421. global jenv
  422. if not jenv:
  423. from jinja2 import Environment, ChoiceLoader, PackageLoader
  424. apps = get_installed_apps()
  425. apps.remove("webnotes")
  426. # webnotes will be loaded last, so app templates will get precedence
  427. jenv = Environment(loader = ChoiceLoader([PackageLoader(app, ".") \
  428. for app in apps + ["webnotes"]]))
  429. set_filters(jenv)
  430. return jenv
  431. def set_filters(jenv):
  432. from webnotes.utils import global_date_format
  433. from markdown2 import markdown
  434. from json import dumps
  435. jenv.filters["global_date_format"] = global_date_format
  436. jenv.filters["markdown"] = markdown
  437. jenv.filters["json"] = dumps
  438. # load jenv_filters from hooks.txt
  439. for app in get_all_apps(True):
  440. for jenv_filter in (get_hooks(app).jenv_filter or []):
  441. filter_name, filter_function = jenv_filter.split(":")
  442. jenv.filters[filter_name] = get_attr(filter_function)
  443. def get_template(path):
  444. return get_jenv().get_template(path)