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.
 
 
 
 
 
 

1052 lines
32 KiB

  1. # Copyright (c) 2015, Frappe 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 functools import wraps
  10. import os, importlib, inspect, logging, json
  11. # public
  12. from frappe.__version__ import __version__
  13. from .exceptions import *
  14. from .utils.jinja import get_jenv, get_template, render_template
  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 _(msg, lang=None):
  36. """Returns translated string in current lang, if exists."""
  37. if not lang:
  38. lang = local.lang
  39. if lang == "en":
  40. return msg
  41. from frappe.translate import get_full_dict
  42. return get_full_dict(local.lang).get(msg) or msg
  43. def get_lang_dict(fortype, name=None):
  44. """Returns the translated language dict for the given type and name.
  45. :param fortype: must be one of `doctype`, `page`, `report`, `include`, `jsfile`, `boot`
  46. :param name: name of the document for which assets are to be returned."""
  47. if local.lang=="en":
  48. return {}
  49. from frappe.translate import get_dict
  50. return get_dict(fortype, name)
  51. def set_user_lang(user, user_language=None):
  52. """Guess and set user language for the session. `frappe.local.lang`"""
  53. from frappe.translate import get_user_lang
  54. local.lang = get_user_lang(user)
  55. # local-globals
  56. db = local("db")
  57. conf = local("conf")
  58. form = form_dict = local("form_dict")
  59. request = local("request")
  60. response = local("response")
  61. session = local("session")
  62. user = local("user")
  63. flags = local("flags")
  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. """Initialize frappe for the current site. Reset thread locals `frappe.local`"""
  70. if getattr(local, "initialised", None):
  71. return
  72. if not sites_path:
  73. sites_path = '.'
  74. local.error_log = []
  75. local.message_log = []
  76. local.debug_log = []
  77. local.realtime_log = []
  78. local.flags = _dict({
  79. "ran_schedulers": [],
  80. "redirect_location": "",
  81. "in_install_db": False,
  82. "in_install_app": False,
  83. "in_import": False,
  84. "in_test": False,
  85. "mute_messages": False,
  86. "ignore_links": False,
  87. "mute_emails": False,
  88. "has_dataurl": False,
  89. })
  90. local.rollback_observers = []
  91. local.test_objects = {}
  92. local.site = site
  93. local.sites_path = sites_path
  94. local.site_path = os.path.join(sites_path, site)
  95. local.request_ip = None
  96. local.response = _dict({"docs":[]})
  97. local.task_id = None
  98. local.conf = _dict(get_site_config())
  99. local.lang = local.conf.lang or "en"
  100. local.lang_full_dict = None
  101. local.module_app = None
  102. local.app_modules = None
  103. local.system_settings = None
  104. local.user = None
  105. local.user_obj = None
  106. local.session = None
  107. local.role_permissions = {}
  108. local.valid_columns = {}
  109. local.new_doc_templates = {}
  110. local.jenv = None
  111. local.jloader =None
  112. local.cache = {}
  113. setup_module_map()
  114. local.initialised = True
  115. def connect(site=None, db_name=None):
  116. """Connect to site database instance.
  117. :param site: If site is given, calls `frappe.init`.
  118. :param db_name: Optional. Will use from `site_config.json`."""
  119. from database import Database
  120. if site:
  121. init(site)
  122. local.db = Database(user=db_name or local.conf.db_name)
  123. local.form_dict = _dict()
  124. local.session = _dict()
  125. set_user("Administrator")
  126. def get_site_config(sites_path=None, site_path=None):
  127. """Returns `site_config.json` combined with `sites/common_site_config.json`.
  128. `site_config` is a set of site wide settings like database name, password, email etc."""
  129. config = {}
  130. sites_path = sites_path or getattr(local, "sites_path", None)
  131. site_path = site_path or getattr(local, "site_path", None)
  132. if sites_path:
  133. common_site_config = os.path.join(sites_path, "common_site_config.json")
  134. if os.path.exists(common_site_config):
  135. config.update(get_file_json(common_site_config))
  136. if site_path:
  137. site_config = os.path.join(site_path, "site_config.json")
  138. if os.path.exists(site_config):
  139. config.update(get_file_json(site_config))
  140. return _dict(config)
  141. def destroy():
  142. """Closes connection and releases werkzeug local."""
  143. if db:
  144. db.close()
  145. release_local(local)
  146. # memcache
  147. redis_server = None
  148. def cache():
  149. """Returns memcache connection."""
  150. global redis_server
  151. if not redis_server:
  152. from frappe.utils.redis_wrapper import RedisWrapper
  153. redis_server = RedisWrapper.from_url(conf.get("cache_redis_server") or "redis://localhost:11311")
  154. return redis_server
  155. def get_traceback():
  156. """Returns error traceback."""
  157. import utils
  158. return utils.get_traceback()
  159. def errprint(msg):
  160. """Log error. This is sent back as `exc` in response.
  161. :param msg: Message."""
  162. from utils import cstr
  163. if not request or (not "cmd" in local.form_dict):
  164. print cstr(msg)
  165. error_log.append(cstr(msg))
  166. def log(msg):
  167. """Add to `debug_log`.
  168. :param msg: Message."""
  169. if not request:
  170. if conf.get("logging") or False:
  171. print repr(msg)
  172. from utils import cstr
  173. debug_log.append(cstr(msg))
  174. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  175. """Print a message to the user (via HTTP response).
  176. Messages are sent in the `__server_messages` property in the
  177. response JSON and shown in a pop-up / modal.
  178. :param msg: Message.
  179. :param small: [optional] Show as a floating message in the footer.
  180. :param raise_exception: [optional] Raise given exception and show message.
  181. :param as_table: [optional] If `msg` is a list of lists, render as HTML table.
  182. """
  183. from utils import cstr, encode
  184. def _raise_exception():
  185. if raise_exception:
  186. if flags.rollback_on_exception:
  187. db.rollback()
  188. import inspect
  189. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  190. raise raise_exception, encode(msg)
  191. else:
  192. raise ValidationError, encode(msg)
  193. if flags.mute_messages:
  194. _raise_exception()
  195. return
  196. if as_table and type(msg) in (list, tuple):
  197. 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>'
  198. if flags.print_messages:
  199. print "Message: " + repr(msg).encode("utf-8")
  200. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  201. _raise_exception()
  202. def throw(msg, exc=ValidationError):
  203. """Throw execption and show message (`msgprint`).
  204. :param msg: Message.
  205. :param exc: Exception class. Default `frappe.ValidationError`"""
  206. msgprint(msg, raise_exception=exc)
  207. def create_folder(path, with_init=False):
  208. """Create a folder in the given path and add an `__init__.py` file (optional).
  209. :param path: Folder path.
  210. :param with_init: Create `__init__.py` in the new folder."""
  211. from frappe.utils import touch_file
  212. if not os.path.exists(path):
  213. os.makedirs(path)
  214. if with_init:
  215. touch_file(os.path.join(path, "__init__.py"))
  216. def set_user(username):
  217. """Set current user.
  218. :param username: **User** name to set as current user."""
  219. local.session.user = username
  220. local.session.sid = username
  221. local.cache = {}
  222. local.form_dict = _dict()
  223. local.jenv = None
  224. local.session.data = _dict()
  225. local.role_permissions = {}
  226. local.new_doc_templates = {}
  227. local.user_obj = None
  228. def get_user():
  229. from frappe.utils.user import User
  230. if not local.user_obj:
  231. local.user_obj = User(local.session.user)
  232. return local.user_obj
  233. def get_roles(username=None):
  234. """Returns roles of current user."""
  235. if not local.session:
  236. return ["Guest"]
  237. if username:
  238. import frappe.utils.user
  239. return frappe.utils.user.get_roles(username)
  240. else:
  241. return get_user().get_roles()
  242. def get_request_header(key, default=None):
  243. """Return HTTP request header.
  244. :param key: HTTP header key.
  245. :param default: Default value."""
  246. return request.headers.get(key, default)
  247. def sendmail(recipients=(), sender="", subject="No Subject", message="No Message",
  248. as_markdown=False, bulk=False, reference_doctype=None, reference_name=None,
  249. unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None,
  250. attachments=None, content=None, doctype=None, name=None, reply_to=None,
  251. cc=(), message_id=None, as_bulk=False, send_after=None, expose_recipients=False):
  252. """Send email using user's default **Email Account** or global default **Email Account**.
  253. :param recipients: List of recipients.
  254. :param sender: Email sender. Default is current user.
  255. :param subject: Email Subject.
  256. :param message: (or `content`) Email Content.
  257. :param as_markdown: Convert content markdown to HTML.
  258. :param bulk: Send via scheduled email sender **Bulk Email**. Don't send immediately.
  259. :param reference_doctype: (or `doctype`) Append as communication to this DocType.
  260. :param reference_name: (or `name`) Append as communication to this document name.
  261. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
  262. :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
  263. :param attachments: List of attachments.
  264. :param reply_to: Reply-To email id.
  265. :param message_id: Used for threading. If a reply is received to this email, Message-Id is sent back as In-Reply-To in received email.
  266. :param send_after: Send after the given datetime.
  267. :param expose_recipients: Display all recipients in the footer message - "This email was sent to"
  268. """
  269. if bulk or as_bulk:
  270. import frappe.email.bulk
  271. frappe.email.bulk.send(recipients=recipients, sender=sender,
  272. subject=subject, message=content or message,
  273. reference_doctype = doctype or reference_doctype, reference_name = name or reference_name,
  274. unsubscribe_method=unsubscribe_method, unsubscribe_params=unsubscribe_params, unsubscribe_message=unsubscribe_message,
  275. attachments=attachments, reply_to=reply_to, cc=cc, message_id=message_id, send_after=send_after,
  276. expose_recipients=expose_recipients)
  277. else:
  278. import frappe.email
  279. if as_markdown:
  280. frappe.email.sendmail_md(recipients, sender=sender,
  281. subject=subject, msg=content or message, attachments=attachments, reply_to=reply_to,
  282. cc=cc, message_id=message_id)
  283. else:
  284. frappe.email.sendmail(recipients, sender=sender,
  285. subject=subject, msg=content or message, attachments=attachments, reply_to=reply_to,
  286. cc=cc, message_id=message_id)
  287. logger = None
  288. whitelisted = []
  289. guest_methods = []
  290. xss_safe_methods = []
  291. def whitelist(allow_guest=False, xss_safe=False):
  292. """
  293. Decorator for whitelisting a function and making it accessible via HTTP.
  294. Standard request will be `/api/method/[path.to.method]`
  295. :param allow_guest: Allow non logged-in user to access this method.
  296. Use as:
  297. @frappe.whitelist()
  298. def myfunc(param1, param2):
  299. pass
  300. """
  301. def innerfn(fn):
  302. global whitelisted, guest_methods, xss_safe_methods
  303. whitelisted.append(fn)
  304. if allow_guest:
  305. guest_methods.append(fn)
  306. if xss_safe:
  307. xss_safe_methods.append(fn)
  308. return fn
  309. return innerfn
  310. def only_for(roles):
  311. """Raise `frappe.PermissionError` if the user does not have any of the given **Roles**.
  312. :param roles: List of roles to check."""
  313. if not isinstance(roles, (tuple, list)):
  314. roles = (roles,)
  315. roles = set(roles)
  316. myroles = set(get_roles())
  317. if not roles.intersection(myroles):
  318. raise PermissionError
  319. def clear_cache(user=None, doctype=None):
  320. """Clear **User**, **DocType** or global cache.
  321. :param user: If user is given, only user cache is cleared.
  322. :param doctype: If doctype is given, only DocType cache is cleared."""
  323. import frappe.sessions
  324. if doctype:
  325. import frappe.model.meta
  326. frappe.model.meta.clear_cache(doctype)
  327. reset_metadata_version()
  328. elif user:
  329. frappe.sessions.clear_cache(user)
  330. else: # everything
  331. import translate
  332. frappe.sessions.clear_cache()
  333. translate.clear_cache()
  334. reset_metadata_version()
  335. frappe.local.cache = {}
  336. for fn in frappe.get_hooks("clear_cache"):
  337. get_attr(fn)()
  338. frappe.local.role_permissions = {}
  339. def has_permission(doctype, ptype="read", doc=None, user=None, verbose=False):
  340. """Raises `frappe.PermissionError` if not permitted.
  341. :param doctype: DocType for which permission is to be check.
  342. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  343. :param doc: [optional] Checks User permissions for given doc.
  344. :param user: [optional] Check for given user. Default: current user."""
  345. import frappe.permissions
  346. return frappe.permissions.has_permission(doctype, ptype, doc=doc, verbose=verbose, user=user)
  347. def has_website_permission(doctype, ptype="read", doc=None, user=None, verbose=False):
  348. """Raises `frappe.PermissionError` if not permitted.
  349. :param doctype: DocType for which permission is to be check.
  350. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  351. :param doc: Checks User permissions for given doc.
  352. :param user: [optional] Check for given user. Default: current user."""
  353. if not user:
  354. user = session.user
  355. hooks = (get_hooks("has_website_permission") or {}).get(doctype, [])
  356. if hooks:
  357. if isinstance(doc, basestring):
  358. doc = get_doc(doctype, doc)
  359. for method in hooks:
  360. result = call(get_attr(method), doc=doc, ptype=ptype, user=user, verbose=verbose)
  361. # if even a single permission check is Falsy
  362. if not result:
  363. return False
  364. # else it is Truthy
  365. return True
  366. else:
  367. return False
  368. def is_table(doctype):
  369. """Returns True if `istable` property (indicating child Table) is set for given DocType."""
  370. def get_tables():
  371. return db.sql_list("select name from tabDocType where ifnull(istable,0)=1")
  372. tables = cache().get_value("is_table", get_tables)
  373. return doctype in tables
  374. def get_precision(doctype, fieldname, currency=None, doc=None):
  375. """Get precision for a given field"""
  376. from frappe.model.meta import get_field_precision
  377. return get_field_precision(get_meta(doctype).get_field(fieldname), doc, currency)
  378. def generate_hash(txt=None):
  379. """Generates random hash for given text + current timestamp + random string."""
  380. import hashlib, time
  381. from .utils import random_string
  382. return hashlib.sha224((txt or "") + repr(time.time()) + repr(random_string(8))).hexdigest()
  383. def reset_metadata_version():
  384. """Reset `metadata_version` (Client (Javascript) build ID) hash."""
  385. v = generate_hash()
  386. cache().set_value("metadata_version", v)
  387. return v
  388. def new_doc(doctype, parent_doc=None, parentfield=None, as_dict=False):
  389. """Returns a new document of the given DocType with defaults set.
  390. :param doctype: DocType of the new document.
  391. :param parent_doc: [optional] add to parent document.
  392. :param parentfield: [optional] add against this `parentfield`."""
  393. from frappe.model.create_new import get_new_doc
  394. return get_new_doc(doctype, parent_doc, parentfield, as_dict=as_dict)
  395. def set_value(doctype, docname, fieldname, value):
  396. """Set document value. Calls `frappe.client.set_value`"""
  397. import frappe.client
  398. return frappe.client.set_value(doctype, docname, fieldname, value)
  399. def get_doc(arg1, arg2=None):
  400. """Return a `frappe.model.document.Document` object of the given type and name.
  401. :param arg1: DocType name as string **or** document JSON.
  402. :param arg2: [optional] Document name as string.
  403. Examples:
  404. # insert a new document
  405. todo = frappe.get_doc({"doctype":"ToDo", "description": "test"})
  406. tood.insert()
  407. # open an existing document
  408. todo = frappe.get_doc("ToDo", "TD0001")
  409. """
  410. import frappe.model.document
  411. return frappe.model.document.get_doc(arg1, arg2)
  412. def get_last_doc(doctype):
  413. """Get last created document of this type."""
  414. d = get_all(doctype, ["name"], order_by="creation desc", limit_page_length=1)
  415. if d:
  416. return get_doc(doctype, d[0].name)
  417. else:
  418. raise DoesNotExistError
  419. def get_single(doctype):
  420. """Return a `frappe.model.document.Document` object of the given Single doctype."""
  421. return get_doc(doctype, doctype)
  422. def get_meta(doctype, cached=True):
  423. """Get `frappe.model.meta.Meta` instance of given doctype name."""
  424. import frappe.model.meta
  425. return frappe.model.meta.get_meta(doctype, cached=cached)
  426. def get_meta_module(doctype):
  427. import frappe.modules
  428. return frappe.modules.load_doctype_module(doctype)
  429. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  430. ignore_permissions=False, flags=None):
  431. """Delete a document. Calls `frappe.model.delete_doc.delete_doc`.
  432. :param doctype: DocType of document to be delete.
  433. :param name: Name of document to be delete.
  434. :param force: Allow even if document is linked. Warning: This may lead to data integrity errors.
  435. :param ignore_doctypes: Ignore if child table is one of these.
  436. :param for_reload: Call `before_reload` trigger before deleting.
  437. :param ignore_permissions: Ignore user permissions."""
  438. import frappe.model.delete_doc
  439. frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload,
  440. ignore_permissions, flags)
  441. def delete_doc_if_exists(doctype, name):
  442. """Delete document if exists."""
  443. if db.exists(doctype, name):
  444. delete_doc(doctype, name)
  445. def reload_doctype(doctype, force=False):
  446. """Reload DocType from model (`[module]/[doctype]/[name]/[name].json`) files."""
  447. reload_doc(scrub(db.get_value("DocType", doctype, "module")), "doctype", scrub(doctype), force=force)
  448. def reload_doc(module, dt=None, dn=None, force=False):
  449. """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
  450. :param module: Module name.
  451. :param dt: DocType name.
  452. :param dn: Document name.
  453. :param force: Reload even if `modified` timestamp matches.
  454. """
  455. import frappe.modules
  456. return frappe.modules.reload_doc(module, dt, dn, force=force)
  457. def rename_doc(doctype, old, new, debug=0, force=False, merge=False, ignore_permissions=False):
  458. """Rename a document. Calls `frappe.model.rename_doc.rename_doc`"""
  459. from frappe.model.rename_doc import rename_doc
  460. return rename_doc(doctype, old, new, force=force, merge=merge, ignore_permissions=ignore_permissions)
  461. def get_module(modulename):
  462. """Returns a module object for given Python module name using `importlib.import_module`."""
  463. return importlib.import_module(modulename)
  464. def scrub(txt):
  465. """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
  466. return txt.replace(' ','_').replace('-', '_').lower()
  467. def unscrub(txt):
  468. """Returns titlified string. e.g. `sales_order` becomes `Sales Order`."""
  469. return txt.replace('_',' ').replace('-', ' ').title()
  470. def get_module_path(module, *joins):
  471. """Get the path of the given module name.
  472. :param module: Module name.
  473. :param *joins: Join additional path elements using `os.path.join`."""
  474. module = scrub(module)
  475. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  476. def get_app_path(app_name, *joins):
  477. """Return path of given app.
  478. :param app: App name.
  479. :param *joins: Join additional path elements using `os.path.join`."""
  480. return get_pymodule_path(app_name, *joins)
  481. def get_site_path(*joins):
  482. """Return path of current site.
  483. :param *joins: Join additional path elements using `os.path.join`."""
  484. return os.path.join(local.site_path, *joins)
  485. def get_pymodule_path(modulename, *joins):
  486. """Return path of given Python module name.
  487. :param modulename: Python module name.
  488. :param *joins: Join additional path elements using `os.path.join`."""
  489. joins = [scrub(part) for part in joins]
  490. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  491. def get_module_list(app_name):
  492. """Get list of modules for given all via `app/modules.txt`."""
  493. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  494. def get_all_apps(with_frappe=False, with_internal_apps=True, sites_path=None):
  495. """Get list of all apps via `sites/apps.txt`."""
  496. if not sites_path:
  497. sites_path = local.sites_path
  498. apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
  499. if with_internal_apps:
  500. apps.extend(get_file_items(os.path.join(local.site_path, "apps.txt")))
  501. if with_frappe:
  502. if "frappe" in apps:
  503. apps.remove("frappe")
  504. apps.insert(0, 'frappe')
  505. return apps
  506. def get_installed_apps(sort=False):
  507. """Get list of installed apps in current site."""
  508. if getattr(flags, "in_install_db", True):
  509. return []
  510. installed = json.loads(db.get_global("installed_apps") or "[]")
  511. if sort:
  512. installed = [app for app in get_all_apps(True) if app in installed]
  513. return installed
  514. def get_hooks(hook=None, default=None, app_name=None):
  515. """Get hooks via `app/hooks.py`
  516. :param hook: Name of the hook. Will gather all hooks for this name and return as a list.
  517. :param default: Default if no hook found.
  518. :param app_name: Filter by app."""
  519. def load_app_hooks(app_name=None):
  520. hooks = {}
  521. for app in [app_name] if app_name else get_installed_apps(sort=True):
  522. app = "frappe" if app=="webnotes" else app
  523. try:
  524. app_hooks = get_module(app + ".hooks")
  525. except ImportError:
  526. if local.flags.in_install_app:
  527. # if app is not installed while restoring
  528. # ignore it
  529. pass
  530. raise
  531. for key in dir(app_hooks):
  532. if not key.startswith("_"):
  533. append_hook(hooks, key, getattr(app_hooks, key))
  534. return hooks
  535. def append_hook(target, key, value):
  536. if isinstance(value, dict):
  537. target.setdefault(key, {})
  538. for inkey in value:
  539. append_hook(target[key], inkey, value[inkey])
  540. else:
  541. append_to_list(target, key, value)
  542. def append_to_list(target, key, value):
  543. target.setdefault(key, [])
  544. if not isinstance(value, list):
  545. value = [value]
  546. target[key].extend(value)
  547. if app_name:
  548. hooks = _dict(load_app_hooks(app_name))
  549. else:
  550. hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
  551. if hook:
  552. return hooks.get(hook) or (default if default is not None else [])
  553. else:
  554. return hooks
  555. def setup_module_map():
  556. """Rebuild map of all modules (internal)."""
  557. _cache = cache()
  558. if conf.db_name:
  559. local.app_modules = _cache.get_value("app_modules")
  560. local.module_app = _cache.get_value("module_app")
  561. if not (local.app_modules and local.module_app):
  562. local.module_app, local.app_modules = {}, {}
  563. for app in get_all_apps(True):
  564. if app=="webnotes": app="frappe"
  565. local.app_modules.setdefault(app, [])
  566. for module in get_module_list(app):
  567. module = scrub(module)
  568. local.module_app[module] = app
  569. local.app_modules[app].append(module)
  570. if conf.db_name:
  571. _cache.set_value("app_modules", local.app_modules)
  572. _cache.set_value("module_app", local.module_app)
  573. def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
  574. """Returns items from text file as a list. Ignores empty lines."""
  575. import frappe.utils
  576. content = read_file(path, raise_not_found=raise_not_found)
  577. if content:
  578. content = frappe.utils.strip(content)
  579. return [p.strip() for p in content.splitlines() if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))]
  580. else:
  581. return []
  582. def get_file_json(path):
  583. """Read a file and return parsed JSON object."""
  584. with open(path, 'r') as f:
  585. return json.load(f)
  586. def read_file(path, raise_not_found=False):
  587. """Open a file and return its content as Unicode."""
  588. from frappe.utils import cstr
  589. if os.path.exists(path):
  590. with open(path, "r") as f:
  591. return cstr(f.read())
  592. elif raise_not_found:
  593. raise IOError("{} Not Found".format(path))
  594. else:
  595. return None
  596. def get_attr(method_string):
  597. """Get python method object from its name."""
  598. modulename = '.'.join(method_string.split('.')[:-1])
  599. methodname = method_string.split('.')[-1]
  600. return getattr(get_module(modulename), methodname)
  601. def call(fn, *args, **kwargs):
  602. """Call a function and match arguments."""
  603. if hasattr(fn, 'fnargs'):
  604. fnargs = fn.fnargs
  605. else:
  606. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  607. newargs = {}
  608. for a in kwargs:
  609. if (a in fnargs) or varkw:
  610. newargs[a] = kwargs.get(a)
  611. if "flags" in newargs:
  612. del newargs["flags"]
  613. return fn(*args, **newargs)
  614. def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
  615. """Create a new **Property Setter** (for overriding DocType and DocField properties)."""
  616. args = _dict(args)
  617. ps = get_doc({
  618. 'doctype': "Property Setter",
  619. 'doctype_or_field': args.doctype_or_field or "DocField",
  620. 'doc_type': args.doctype,
  621. 'field_name': args.fieldname,
  622. 'property': args.property,
  623. 'value': args.value,
  624. 'property_type': args.property_type or "Data",
  625. '__islocal': 1
  626. })
  627. ps.flags.ignore_validate = ignore_validate
  628. ps.flags.validate_fields_for_doctype = validate_fields_for_doctype
  629. ps.insert()
  630. def import_doc(path, ignore_links=False, ignore_insert=False, insert=False):
  631. """Import a file using Data Import Tool."""
  632. from frappe.core.page.data_import_tool import data_import_tool
  633. data_import_tool.import_doc(path, ignore_links=ignore_links, ignore_insert=ignore_insert, insert=insert)
  634. def copy_doc(doc, ignore_no_copy=True):
  635. """ No_copy fields also get copied."""
  636. import copy
  637. def remove_no_copy_fields(d):
  638. for df in d.meta.get("fields", {"no_copy": 1}):
  639. if hasattr(d, df.fieldname):
  640. d.set(df.fieldname, None)
  641. if not isinstance(doc, dict):
  642. d = doc.as_dict()
  643. else:
  644. d = doc
  645. newdoc = get_doc(copy.deepcopy(d))
  646. newdoc.name = None
  647. newdoc.set("__islocal", 1)
  648. newdoc.owner = None
  649. newdoc.creation = None
  650. newdoc.amended_from = None
  651. newdoc.amendment_date = None
  652. if not ignore_no_copy:
  653. remove_no_copy_fields(newdoc)
  654. for d in newdoc.get_all_children():
  655. d.name = None
  656. d.parent = None
  657. d.set("__islocal", 1)
  658. d.owner = None
  659. d.creation = None
  660. if not ignore_no_copy:
  661. remove_no_copy_fields(d)
  662. return newdoc
  663. def compare(val1, condition, val2):
  664. """Compare two values using `frappe.utils.compare`
  665. `condition` could be:
  666. - "^"
  667. - "in"
  668. - "not in"
  669. - "="
  670. - "!="
  671. - ">"
  672. - "<"
  673. - ">="
  674. - "<="
  675. - "not None"
  676. - "None"
  677. """
  678. import frappe.utils
  679. return frappe.utils.compare(val1, condition, val2)
  680. def respond_as_web_page(title, html, success=None, http_status_code=None):
  681. """Send response as a web page with a message rather than JSON. Used to show permission errors etc.
  682. :param title: Page title and heading.
  683. :param message: Message to be shown.
  684. :param success: Alert message.
  685. :param http_status_code: HTTP status code."""
  686. local.message_title = title
  687. local.message = html
  688. local.message_success = success
  689. local.response['type'] = 'page'
  690. local.response['page_name'] = 'message'
  691. if http_status_code:
  692. local.response['http_status_code'] = http_status_code
  693. def build_match_conditions(doctype, as_condition=True):
  694. """Return match (User permissions) for given doctype as list or SQL."""
  695. import frappe.desk.reportview
  696. return frappe.desk.reportview.build_match_conditions(doctype, as_condition)
  697. def get_list(doctype, *args, **kwargs):
  698. """List database query via `frappe.model.db_query`. Will also check for permissions.
  699. :param doctype: DocType on which query is to be made.
  700. :param fields: List of fields or `*`.
  701. :param filters: List of filters (see example).
  702. :param order_by: Order By e.g. `modified desc`.
  703. :param limit_page_start: Start results at record #. Default 0.
  704. :param limit_poge_length: No of records in the page. Default 20.
  705. Example usage:
  706. # simple dict filter
  707. frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  708. # filter as a list of lists
  709. frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
  710. # filter as a list of dicts
  711. frappe.get_list("ToDo", fields="*", filters = {"description": ("like", "test%")})
  712. """
  713. import frappe.model.db_query
  714. return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
  715. def get_all(doctype, *args, **kwargs):
  716. """List database query via `frappe.model.db_query`. Will **not** check for conditions.
  717. Parameters are same as `frappe.get_list`
  718. :param doctype: DocType on which query is to be made.
  719. :param fields: List of fields or `*`. Default is: `["name"]`.
  720. :param filters: List of filters (see example).
  721. :param order_by: Order By e.g. `modified desc`.
  722. :param limit_page_start: Start results at record #. Default 0.
  723. :param limit_poge_length: No of records in the page. Default 20.
  724. Example usage:
  725. # simple dict filter
  726. frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  727. # filter as a list of lists
  728. frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
  729. # filter as a list of dicts
  730. frappe.get_all("ToDo", fields=["*"], filters = {"description": ("like", "test%")})
  731. """
  732. kwargs["ignore_permissions"] = True
  733. if not "limit_page_length" in kwargs:
  734. kwargs["limit_page_length"] = 0
  735. return get_list(doctype, *args, **kwargs)
  736. def get_value(*args, **kwargs):
  737. """Returns a document property or list of properties.
  738. Alias for `frappe.db.get_value`
  739. :param doctype: DocType name.
  740. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType.
  741. :param fieldname: Column name.
  742. :param ignore: Don't raise exception if table, column is missing.
  743. :param as_dict: Return values as dict.
  744. :param debug: Print query in error log.
  745. """
  746. return db.get_value(*args, **kwargs)
  747. def add_version(doc):
  748. """Insert a new **Version** of the given document.
  749. A **Version** is a JSON dump of the current document state."""
  750. get_doc({
  751. "doctype": "Version",
  752. "ref_doctype": doc.doctype,
  753. "docname": doc.name,
  754. "doclist_json": as_json(doc.as_dict())
  755. }).insert(ignore_permissions=True)
  756. def as_json(obj, indent=1):
  757. from frappe.utils.response import json_handler
  758. return json.dumps(obj, indent=indent, sort_keys=True, default=json_handler)
  759. def are_emails_muted():
  760. return flags.mute_emails or conf.get("mute_emails") or False
  761. def get_test_records(doctype):
  762. """Returns list of objects from `test_records.json` in the given doctype's folder."""
  763. from frappe.modules import get_doctype_module, get_module_path
  764. path = os.path.join(get_module_path(get_doctype_module(doctype)), "doctype", scrub(doctype), "test_records.json")
  765. if os.path.exists(path):
  766. with open(path, "r") as f:
  767. return json.loads(f.read())
  768. else:
  769. return []
  770. def format_value(value, df, doc=None, currency=None):
  771. """Format value with given field properties.
  772. :param value: Value to be formatted.
  773. :param df: DocField object with properties `fieldtype`, `options` etc."""
  774. import frappe.utils.formatters
  775. return frappe.utils.formatters.format_value(value, df, doc, currency=currency)
  776. def get_print(doctype, name, print_format=None, style=None, html=None, as_pdf=False):
  777. """Get Print Format for given document.
  778. :param doctype: DocType of document.
  779. :param name: Name of document.
  780. :param print_format: Print Format name. Default 'Standard',
  781. :param style: Print Format style.
  782. :param as_pdf: Return as PDF. Default False."""
  783. from frappe.website.render import build_page
  784. from frappe.utils.pdf import get_pdf
  785. local.form_dict.doctype = doctype
  786. local.form_dict.name = name
  787. local.form_dict.format = print_format
  788. local.form_dict.style = style
  789. if not html:
  790. html = build_page("print")
  791. if as_pdf:
  792. return get_pdf(html)
  793. else:
  794. return html
  795. def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None):
  796. from frappe.utils import scrub_urls
  797. if not file_name: file_name = name
  798. file_name = file_name.replace(' ','').replace('/','-')
  799. print_settings = db.get_singles_dict("Print Settings")
  800. local.flags.ignore_print_permissions = True
  801. if int(print_settings.send_print_as_pdf or 0):
  802. out = {
  803. "fname": file_name + ".pdf",
  804. "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True)
  805. }
  806. else:
  807. out = {
  808. "fname": file_name + ".html",
  809. "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html)).encode("utf-8")
  810. }
  811. local.flags.ignore_print_permissions = False
  812. return out
  813. logging_setup_complete = False
  814. def get_logger(module=None):
  815. from frappe.setup_logging import setup_logging
  816. global logging_setup_complete
  817. if not logging_setup_complete:
  818. setup_logging()
  819. logging_setup_complete = True
  820. return logging.getLogger(module or "frappe")
  821. def publish_realtime(*args, **kwargs):
  822. """Publish real-time updates
  823. :param event: Event name, like `task_progress` etc.
  824. :param message: JSON message object. For async must contain `task_id`
  825. :param room: Room in which to publish update (default entire site)
  826. :param user: Transmit to user
  827. :param doctype: Transmit to doctype, docname
  828. :param docname: Transmit to doctype, docname"""
  829. import frappe.async
  830. return frappe.async.publish_realtime(*args, **kwargs)
  831. def local_cache(namespace, key, generator):
  832. """A key value store for caching within a request
  833. :param namespace: frappe.local.cache[namespace]
  834. :param key: frappe.local.cache[namespace][key] used to retrieve value
  835. :param generator: method to generate a value if not found in store
  836. """
  837. if namespace not in local.cache:
  838. local.cache[namespace] = {}
  839. if key not in local.cache[namespace]:
  840. local.cache[namespace][key] = generator()
  841. return local.cache[namespace][key]