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.
 
 
 
 
 
 

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