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.

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