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.
 
 
 
 
 
 

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