Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

629 linhas
18 KiB

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