Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

1369 wiersze
42 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, print_function
  8. from six import iteritems, text_type, string_types
  9. from werkzeug.local import Local, release_local
  10. import os, sys, importlib, inspect, json
  11. # public
  12. from .exceptions import *
  13. from .utils.jinja import get_jenv, get_template, render_template, get_email_from_template
  14. __version__ = '8.9.0'
  15. __title__ = "Frappe Framework"
  16. local = Local()
  17. class _dict(dict):
  18. """dict like object that exposes keys as attributes"""
  19. def __getattr__(self, key):
  20. ret = self.get(key)
  21. if not ret and key.startswith("__"):
  22. raise AttributeError()
  23. return ret
  24. def __setattr__(self, key, value):
  25. self[key] = value
  26. def __getstate__(self):
  27. return self
  28. def __setstate__(self, d):
  29. self.update(d)
  30. def update(self, d):
  31. """update and return self -- the missing dict feature in python"""
  32. super(_dict, self).update(d)
  33. return self
  34. def copy(self):
  35. return _dict(dict(self).copy())
  36. def _(msg, lang=None):
  37. """Returns translated string in current lang, if exists."""
  38. from frappe.translate import get_full_dict
  39. if not hasattr(local, 'lang'):
  40. local.lang = lang or 'en'
  41. if not lang:
  42. lang = local.lang
  43. # msg should always be unicode
  44. msg = as_unicode(msg).strip()
  45. # return lang_full_dict according to lang passed parameter
  46. return get_full_dict(lang).get(msg) or msg
  47. def as_unicode(text, encoding='utf-8'):
  48. '''Convert to unicode if required'''
  49. if isinstance(text, text_type):
  50. return text
  51. elif text==None:
  52. return ''
  53. elif isinstance(text, string_types):
  54. return text_type(text, encoding)
  55. else:
  56. return text_type(text)
  57. def get_lang_dict(fortype, name=None):
  58. """Returns the translated language dict for the given type and name.
  59. :param fortype: must be one of `doctype`, `page`, `report`, `include`, `jsfile`, `boot`
  60. :param name: name of the document for which assets are to be returned."""
  61. from frappe.translate import get_dict
  62. return get_dict(fortype, name)
  63. def set_user_lang(user, user_language=None):
  64. """Guess and set user language for the session. `frappe.local.lang`"""
  65. from frappe.translate import get_user_lang
  66. local.lang = get_user_lang(user)
  67. # local-globals
  68. db = local("db")
  69. conf = local("conf")
  70. form = form_dict = local("form_dict")
  71. request = local("request")
  72. response = local("response")
  73. session = local("session")
  74. user = local("user")
  75. flags = local("flags")
  76. error_log = local("error_log")
  77. debug_log = local("debug_log")
  78. message_log = local("message_log")
  79. lang = local("lang")
  80. def init(site, sites_path=None, new_site=False):
  81. """Initialize frappe for the current site. Reset thread locals `frappe.local`"""
  82. if getattr(local, "initialised", None):
  83. return
  84. if not sites_path:
  85. sites_path = '.'
  86. local.error_log = []
  87. local.message_log = []
  88. local.debug_log = []
  89. local.realtime_log = []
  90. local.flags = _dict({
  91. "ran_schedulers": [],
  92. "currently_saving": [],
  93. "redirect_location": "",
  94. "in_install_db": False,
  95. "in_install_app": False,
  96. "in_import": False,
  97. "in_test": False,
  98. "mute_messages": False,
  99. "ignore_links": False,
  100. "mute_emails": False,
  101. "has_dataurl": False,
  102. "new_site": new_site
  103. })
  104. local.rollback_observers = []
  105. local.test_objects = {}
  106. local.site = site
  107. local.sites_path = sites_path
  108. local.site_path = os.path.join(sites_path, site)
  109. local.request_ip = None
  110. local.response = _dict({"docs":[]})
  111. local.task_id = None
  112. local.conf = _dict(get_site_config())
  113. local.lang = local.conf.lang or "en"
  114. local.lang_full_dict = None
  115. local.module_app = None
  116. local.app_modules = None
  117. local.system_settings = _dict()
  118. local.user = None
  119. local.user_perms = None
  120. local.session = None
  121. local.role_permissions = {}
  122. local.valid_columns = {}
  123. local.new_doc_templates = {}
  124. local.link_count = {}
  125. local.jenv = None
  126. local.jloader =None
  127. local.cache = {}
  128. local.meta_cache = {}
  129. local.form_dict = _dict()
  130. local.session = _dict()
  131. setup_module_map()
  132. local.initialised = True
  133. def connect(site=None, db_name=None):
  134. """Connect to site database instance.
  135. :param site: If site is given, calls `frappe.init`.
  136. :param db_name: Optional. Will use from `site_config.json`."""
  137. from frappe.database import Database
  138. if site:
  139. init(site)
  140. local.db = Database(user=db_name or local.conf.db_name)
  141. set_user("Administrator")
  142. def get_site_config(sites_path=None, site_path=None):
  143. """Returns `site_config.json` combined with `sites/common_site_config.json`.
  144. `site_config` is a set of site wide settings like database name, password, email etc."""
  145. config = {}
  146. sites_path = sites_path or getattr(local, "sites_path", None)
  147. site_path = site_path or getattr(local, "site_path", None)
  148. if sites_path:
  149. common_site_config = os.path.join(sites_path, "common_site_config.json")
  150. if os.path.exists(common_site_config):
  151. config.update(get_file_json(common_site_config))
  152. if site_path:
  153. site_config = os.path.join(site_path, "site_config.json")
  154. if os.path.exists(site_config):
  155. config.update(get_file_json(site_config))
  156. elif local.site and not local.flags.new_site:
  157. print("{0} does not exist".format(local.site))
  158. sys.exit(1)
  159. #raise IncorrectSitePath, "{0} does not exist".format(site_config)
  160. return _dict(config)
  161. def get_conf(site=None):
  162. if hasattr(local, 'conf'):
  163. return local.conf
  164. else:
  165. # if no site, get from common_site_config.json
  166. with init_site(site):
  167. return local.conf
  168. class init_site:
  169. def __init__(self, site=None):
  170. '''If site==None, initialize it for empty site ('') to load common_site_config.json'''
  171. self.site = site or ''
  172. def __enter__(self):
  173. init(self.site)
  174. return local
  175. def __exit__(self, type, value, traceback):
  176. destroy()
  177. def destroy():
  178. """Closes connection and releases werkzeug local."""
  179. if db:
  180. db.close()
  181. release_local(local)
  182. # memcache
  183. redis_server = None
  184. def cache():
  185. """Returns memcache connection."""
  186. global redis_server
  187. if not redis_server:
  188. from frappe.utils.redis_wrapper import RedisWrapper
  189. redis_server = RedisWrapper.from_url(conf.get('redis_cache')
  190. or "redis://localhost:11311")
  191. return redis_server
  192. def get_traceback():
  193. """Returns error traceback."""
  194. from frappe.utils import get_traceback
  195. return get_traceback()
  196. def errprint(msg):
  197. """Log error. This is sent back as `exc` in response.
  198. :param msg: Message."""
  199. msg = as_unicode(msg)
  200. if not request or (not "cmd" in local.form_dict) or conf.developer_mode:
  201. print(msg.encode('utf-8'))
  202. error_log.append(msg)
  203. def log(msg):
  204. """Add to `debug_log`.
  205. :param msg: Message."""
  206. if not request:
  207. if conf.get("logging") or False:
  208. print(repr(msg))
  209. debug_log.append(as_unicode(msg))
  210. def msgprint(msg, title=None, raise_exception=0, as_table=False, indicator=None, alert=False):
  211. """Print a message to the user (via HTTP response).
  212. Messages are sent in the `__server_messages` property in the
  213. response JSON and shown in a pop-up / modal.
  214. :param msg: Message.
  215. :param title: [optional] Message title.
  216. :param raise_exception: [optional] Raise given exception and show message.
  217. :param as_table: [optional] If `msg` is a list of lists, render as HTML table.
  218. """
  219. from frappe.utils import encode
  220. out = _dict(message=msg)
  221. def _raise_exception():
  222. if raise_exception:
  223. if flags.rollback_on_exception:
  224. db.rollback()
  225. import inspect
  226. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  227. raise raise_exception(encode(msg))
  228. else:
  229. raise ValidationError(encode(msg))
  230. if flags.mute_messages:
  231. _raise_exception()
  232. return
  233. if as_table and type(msg) in (list, tuple):
  234. out.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>'
  235. if flags.print_messages and out.msg:
  236. print("Message: " + repr(out.msg).encode("utf-8"))
  237. if title:
  238. out.title = title
  239. if not indicator and raise_exception:
  240. indicator = 'red'
  241. if indicator:
  242. out.indicator = indicator
  243. if alert:
  244. out.alert = 1
  245. message_log.append(json.dumps(out))
  246. _raise_exception()
  247. def clear_messages():
  248. local.message_log = []
  249. def throw(msg, exc=ValidationError, title=None):
  250. """Throw execption and show message (`msgprint`).
  251. :param msg: Message.
  252. :param exc: Exception class. Default `frappe.ValidationError`"""
  253. msgprint(msg, raise_exception=exc, title=title, indicator='red')
  254. def emit_js(js, user=False, **kwargs):
  255. from frappe.async import publish_realtime
  256. if user == False:
  257. user = session.user
  258. publish_realtime('eval_js', js, user=user, **kwargs)
  259. def create_folder(path, with_init=False):
  260. """Create a folder in the given path and add an `__init__.py` file (optional).
  261. :param path: Folder path.
  262. :param with_init: Create `__init__.py` in the new folder."""
  263. from frappe.utils import touch_file
  264. if not os.path.exists(path):
  265. os.makedirs(path)
  266. if with_init:
  267. touch_file(os.path.join(path, "__init__.py"))
  268. def set_user(username):
  269. """Set current user.
  270. :param username: **User** name to set as current user."""
  271. local.session.user = username
  272. local.session.sid = username
  273. local.cache = {}
  274. local.form_dict = _dict()
  275. local.jenv = None
  276. local.session.data = _dict()
  277. local.role_permissions = {}
  278. local.new_doc_templates = {}
  279. local.user_perms = None
  280. def get_user():
  281. from frappe.utils.user import UserPermissions
  282. if not local.user_perms:
  283. local.user_perms = UserPermissions(local.session.user)
  284. return local.user_perms
  285. def get_roles(username=None):
  286. """Returns roles of current user."""
  287. if not local.session:
  288. return ["Guest"]
  289. if username:
  290. import frappe.permissions
  291. return frappe.permissions.get_roles(username)
  292. else:
  293. return get_user().get_roles()
  294. def get_request_header(key, default=None):
  295. """Return HTTP request header.
  296. :param key: HTTP header key.
  297. :param default: Default value."""
  298. return request.headers.get(key, default)
  299. def sendmail(recipients=[], sender="", subject="No Subject", message="No Message",
  300. as_markdown=False, delayed=True, reference_doctype=None, reference_name=None,
  301. unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None,
  302. attachments=None, content=None, doctype=None, name=None, reply_to=None,
  303. cc=[], message_id=None, in_reply_to=None, send_after=None, expose_recipients=None,
  304. send_priority=1, communication=None, retry=1, now=None, read_receipt=None, is_notification=False,
  305. inline_images=None, template=None, args=None, header=None):
  306. """Send email using user's default **Email Account** or global default **Email Account**.
  307. :param recipients: List of recipients.
  308. :param sender: Email sender. Default is current user.
  309. :param subject: Email Subject.
  310. :param message: (or `content`) Email Content.
  311. :param as_markdown: Convert content markdown to HTML.
  312. :param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true
  313. :param send_priority: Priority for Email Queue, default 1.
  314. :param reference_doctype: (or `doctype`) Append as communication to this DocType.
  315. :param reference_name: (or `name`) Append as communication to this document name.
  316. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
  317. :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
  318. :param attachments: List of attachments.
  319. :param reply_to: Reply-To Email Address.
  320. :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.
  321. :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
  322. :param send_after: Send after the given datetime.
  323. :param expose_recipients: Display all recipients in the footer message - "This email was sent to"
  324. :param communication: Communication link to be set in Email Queue record
  325. :param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id
  326. :param template: Name of html template from templates/emails folder
  327. :param args: Arguments for rendering the template
  328. :param header: Append header in email
  329. """
  330. text_content = None
  331. if template:
  332. message, text_content = get_email_from_template(template, args)
  333. message = content or message
  334. if as_markdown:
  335. from markdown2 import markdown
  336. message = markdown(message)
  337. if not delayed:
  338. now = True
  339. from frappe.email import queue
  340. queue.send(recipients=recipients, sender=sender,
  341. subject=subject, message=message, text_content=text_content,
  342. reference_doctype = doctype or reference_doctype, reference_name = name or reference_name,
  343. unsubscribe_method=unsubscribe_method, unsubscribe_params=unsubscribe_params, unsubscribe_message=unsubscribe_message,
  344. attachments=attachments, reply_to=reply_to, cc=cc, message_id=message_id, in_reply_to=in_reply_to,
  345. send_after=send_after, expose_recipients=expose_recipients, send_priority=send_priority,
  346. communication=communication, now=now, read_receipt=read_receipt, is_notification=is_notification,
  347. inline_images=inline_images, header=header)
  348. whitelisted = []
  349. guest_methods = []
  350. xss_safe_methods = []
  351. def whitelist(allow_guest=False, xss_safe=False):
  352. """
  353. Decorator for whitelisting a function and making it accessible via HTTP.
  354. Standard request will be `/api/method/[path.to.method]`
  355. :param allow_guest: Allow non logged-in user to access this method.
  356. Use as:
  357. @frappe.whitelist()
  358. def myfunc(param1, param2):
  359. pass
  360. """
  361. def innerfn(fn):
  362. global whitelisted, guest_methods, xss_safe_methods
  363. whitelisted.append(fn)
  364. if allow_guest:
  365. guest_methods.append(fn)
  366. if xss_safe:
  367. xss_safe_methods.append(fn)
  368. return fn
  369. return innerfn
  370. def only_for(roles):
  371. """Raise `frappe.PermissionError` if the user does not have any of the given **Roles**.
  372. :param roles: List of roles to check."""
  373. if local.flags.in_test:
  374. return
  375. if not isinstance(roles, (tuple, list)):
  376. roles = (roles,)
  377. roles = set(roles)
  378. myroles = set(get_roles())
  379. if not roles.intersection(myroles):
  380. raise PermissionError
  381. def clear_cache(user=None, doctype=None):
  382. """Clear **User**, **DocType** or global cache.
  383. :param user: If user is given, only user cache is cleared.
  384. :param doctype: If doctype is given, only DocType cache is cleared."""
  385. import frappe.sessions
  386. from frappe.core.doctype.domain_settings.domain_settings import clear_domain_cache
  387. if doctype:
  388. import frappe.model.meta
  389. frappe.model.meta.clear_cache(doctype)
  390. reset_metadata_version()
  391. elif user:
  392. frappe.sessions.clear_cache(user)
  393. else: # everything
  394. from frappe import translate
  395. frappe.sessions.clear_cache()
  396. translate.clear_cache()
  397. reset_metadata_version()
  398. clear_domain_cache()
  399. local.cache = {}
  400. local.new_doc_templates = {}
  401. for fn in get_hooks("clear_cache"):
  402. get_attr(fn)()
  403. local.role_permissions = {}
  404. def has_permission(doctype=None, ptype="read", doc=None, user=None, verbose=False, throw=False):
  405. """Raises `frappe.PermissionError` if not permitted.
  406. :param doctype: DocType for which permission is to be check.
  407. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  408. :param doc: [optional] Checks User permissions for given doc.
  409. :param user: [optional] Check for given user. Default: current user."""
  410. if not doctype and doc:
  411. doctype = doc.doctype
  412. import frappe.permissions
  413. out = frappe.permissions.has_permission(doctype, ptype, doc=doc, verbose=verbose, user=user)
  414. if throw and not out:
  415. if doc:
  416. frappe.throw(_("No permission for {0}").format(doc.doctype + " " + doc.name))
  417. else:
  418. frappe.throw(_("No permission for {0}").format(doctype))
  419. return out
  420. def has_website_permission(doc=None, ptype='read', user=None, verbose=False, doctype=None):
  421. """Raises `frappe.PermissionError` if not permitted.
  422. :param doctype: DocType for which permission is to be check.
  423. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  424. :param doc: Checks User permissions for given doc.
  425. :param user: [optional] Check for given user. Default: current user."""
  426. if not user:
  427. user = session.user
  428. if doc:
  429. if isinstance(doc, string_types):
  430. doc = get_doc(doctype, doc)
  431. doctype = doc.doctype
  432. if doc.flags.ignore_permissions:
  433. return True
  434. # check permission in controller
  435. if hasattr(doc, 'has_website_permission'):
  436. return doc.has_website_permission(ptype, verbose=verbose)
  437. hooks = (get_hooks("has_website_permission") or {}).get(doctype, [])
  438. if hooks:
  439. for method in hooks:
  440. result = call(method, doc=doc, ptype=ptype, user=user, verbose=verbose)
  441. # if even a single permission check is Falsy
  442. if not result:
  443. return False
  444. # else it is Truthy
  445. return True
  446. else:
  447. return False
  448. def is_table(doctype):
  449. """Returns True if `istable` property (indicating child Table) is set for given DocType."""
  450. def get_tables():
  451. return db.sql_list("select name from tabDocType where istable=1")
  452. tables = cache().get_value("is_table", get_tables)
  453. return doctype in tables
  454. def get_precision(doctype, fieldname, currency=None, doc=None):
  455. """Get precision for a given field"""
  456. from frappe.model.meta import get_field_precision
  457. return get_field_precision(get_meta(doctype).get_field(fieldname), doc, currency)
  458. def generate_hash(txt=None, length=None):
  459. """Generates random hash for given text + current timestamp + random string."""
  460. import hashlib, time
  461. from .utils import random_string
  462. digest = hashlib.sha224(((txt or "") + repr(time.time()) + repr(random_string(8))).encode()).hexdigest()
  463. if length:
  464. digest = digest[:length]
  465. return digest
  466. def reset_metadata_version():
  467. """Reset `metadata_version` (Client (Javascript) build ID) hash."""
  468. v = generate_hash()
  469. cache().set_value("metadata_version", v)
  470. return v
  471. def new_doc(doctype, parent_doc=None, parentfield=None, as_dict=False):
  472. """Returns a new document of the given DocType with defaults set.
  473. :param doctype: DocType of the new document.
  474. :param parent_doc: [optional] add to parent document.
  475. :param parentfield: [optional] add against this `parentfield`."""
  476. from frappe.model.create_new import get_new_doc
  477. return get_new_doc(doctype, parent_doc, parentfield, as_dict=as_dict)
  478. def set_value(doctype, docname, fieldname, value=None):
  479. """Set document value. Calls `frappe.client.set_value`"""
  480. import frappe.client
  481. return frappe.client.set_value(doctype, docname, fieldname, value)
  482. def get_doc(arg1, arg2=None):
  483. """Return a `frappe.model.document.Document` object of the given type and name.
  484. :param arg1: DocType name as string **or** document JSON.
  485. :param arg2: [optional] Document name as string.
  486. Examples:
  487. # insert a new document
  488. todo = frappe.get_doc({"doctype":"ToDo", "description": "test"})
  489. tood.insert()
  490. # open an existing document
  491. todo = frappe.get_doc("ToDo", "TD0001")
  492. """
  493. import frappe.model.document
  494. return frappe.model.document.get_doc(arg1, arg2)
  495. def get_last_doc(doctype):
  496. """Get last created document of this type."""
  497. d = get_all(doctype, ["name"], order_by="creation desc", limit_page_length=1)
  498. if d:
  499. return get_doc(doctype, d[0].name)
  500. else:
  501. raise DoesNotExistError
  502. def get_single(doctype):
  503. """Return a `frappe.model.document.Document` object of the given Single doctype."""
  504. return get_doc(doctype, doctype)
  505. def get_meta(doctype, cached=True):
  506. """Get `frappe.model.meta.Meta` instance of given doctype name."""
  507. import frappe.model.meta
  508. return frappe.model.meta.get_meta(doctype, cached=cached)
  509. def get_meta_module(doctype):
  510. import frappe.modules
  511. return frappe.modules.load_doctype_module(doctype)
  512. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  513. ignore_permissions=False, flags=None):
  514. """Delete a document. Calls `frappe.model.delete_doc.delete_doc`.
  515. :param doctype: DocType of document to be delete.
  516. :param name: Name of document to be delete.
  517. :param force: Allow even if document is linked. Warning: This may lead to data integrity errors.
  518. :param ignore_doctypes: Ignore if child table is one of these.
  519. :param for_reload: Call `before_reload` trigger before deleting.
  520. :param ignore_permissions: Ignore user permissions."""
  521. import frappe.model.delete_doc
  522. frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload,
  523. ignore_permissions, flags)
  524. def delete_doc_if_exists(doctype, name, force=0):
  525. """Delete document if exists."""
  526. if db.exists(doctype, name):
  527. delete_doc(doctype, name, force=force)
  528. def reload_doctype(doctype, force=False, reset_permissions=False):
  529. """Reload DocType from model (`[module]/[doctype]/[name]/[name].json`) files."""
  530. reload_doc(scrub(db.get_value("DocType", doctype, "module")), "doctype", scrub(doctype),
  531. force=force, reset_permissions=reset_permissions)
  532. def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False):
  533. """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
  534. :param module: Module name.
  535. :param dt: DocType name.
  536. :param dn: Document name.
  537. :param force: Reload even if `modified` timestamp matches.
  538. """
  539. import frappe.modules
  540. return frappe.modules.reload_doc(module, dt, dn, force=force, reset_permissions=reset_permissions)
  541. def rename_doc(*args, **kwargs):
  542. """Rename a document. Calls `frappe.model.rename_doc.rename_doc`"""
  543. from frappe.model.rename_doc import rename_doc
  544. return rename_doc(*args, **kwargs)
  545. def get_module(modulename):
  546. """Returns a module object for given Python module name using `importlib.import_module`."""
  547. return importlib.import_module(modulename)
  548. def scrub(txt):
  549. """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
  550. return txt.replace(' ','_').replace('-', '_').lower()
  551. def unscrub(txt):
  552. """Returns titlified string. e.g. `sales_order` becomes `Sales Order`."""
  553. return txt.replace('_',' ').replace('-', ' ').title()
  554. def get_module_path(module, *joins):
  555. """Get the path of the given module name.
  556. :param module: Module name.
  557. :param *joins: Join additional path elements using `os.path.join`."""
  558. module = scrub(module)
  559. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  560. def get_app_path(app_name, *joins):
  561. """Return path of given app.
  562. :param app: App name.
  563. :param *joins: Join additional path elements using `os.path.join`."""
  564. return get_pymodule_path(app_name, *joins)
  565. def get_site_path(*joins):
  566. """Return path of current site.
  567. :param *joins: Join additional path elements using `os.path.join`."""
  568. return os.path.join(local.site_path, *joins)
  569. def get_pymodule_path(modulename, *joins):
  570. """Return path of given Python module name.
  571. :param modulename: Python module name.
  572. :param *joins: Join additional path elements using `os.path.join`."""
  573. if not "public" in joins:
  574. joins = [scrub(part) for part in joins]
  575. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  576. def get_module_list(app_name):
  577. """Get list of modules for given all via `app/modules.txt`."""
  578. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  579. def get_all_apps(with_internal_apps=True, sites_path=None):
  580. """Get list of all apps via `sites/apps.txt`."""
  581. if not sites_path:
  582. sites_path = local.sites_path
  583. apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
  584. if with_internal_apps:
  585. for app in get_file_items(os.path.join(local.site_path, "apps.txt")):
  586. if app not in apps:
  587. apps.append(app)
  588. if "frappe" in apps:
  589. apps.remove("frappe")
  590. apps.insert(0, 'frappe')
  591. return apps
  592. def get_installed_apps(sort=False, frappe_last=False):
  593. """Get list of installed apps in current site."""
  594. if getattr(flags, "in_install_db", True):
  595. return []
  596. if not db:
  597. connect()
  598. installed = json.loads(db.get_global("installed_apps") or "[]")
  599. if sort:
  600. installed = [app for app in get_all_apps(True) if app in installed]
  601. if frappe_last:
  602. if 'frappe' in installed:
  603. installed.remove('frappe')
  604. installed.append('frappe')
  605. return installed
  606. def get_doc_hooks():
  607. '''Returns hooked methods for given doc. It will expand the dict tuple if required.'''
  608. if not hasattr(local, 'doc_events_hooks'):
  609. hooks = get_hooks('doc_events', {})
  610. out = {}
  611. for key, value in iteritems(hooks):
  612. if isinstance(key, tuple):
  613. for doctype in key:
  614. append_hook(out, doctype, value)
  615. else:
  616. append_hook(out, key, value)
  617. local.doc_events_hooks = out
  618. return local.doc_events_hooks
  619. def get_hooks(hook=None, default=None, app_name=None):
  620. """Get hooks via `app/hooks.py`
  621. :param hook: Name of the hook. Will gather all hooks for this name and return as a list.
  622. :param default: Default if no hook found.
  623. :param app_name: Filter by app."""
  624. def load_app_hooks(app_name=None):
  625. hooks = {}
  626. for app in [app_name] if app_name else get_installed_apps(sort=True):
  627. app = "frappe" if app=="webnotes" else app
  628. try:
  629. app_hooks = get_module(app + ".hooks")
  630. except ImportError:
  631. if local.flags.in_install_app:
  632. # if app is not installed while restoring
  633. # ignore it
  634. pass
  635. print('Could not find app "{0}"'.format(app_name))
  636. if not request:
  637. sys.exit(1)
  638. raise
  639. for key in dir(app_hooks):
  640. if not key.startswith("_"):
  641. append_hook(hooks, key, getattr(app_hooks, key))
  642. return hooks
  643. if app_name:
  644. hooks = _dict(load_app_hooks(app_name))
  645. else:
  646. hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
  647. if hook:
  648. return hooks.get(hook) or (default if default is not None else [])
  649. else:
  650. return hooks
  651. def append_hook(target, key, value):
  652. '''appends a hook to the the target dict.
  653. If the hook key, exists, it will make it a key.
  654. If the hook value is a dict, like doc_events, it will
  655. listify the values against the key.
  656. '''
  657. if isinstance(value, dict):
  658. # dict? make a list of values against each key
  659. target.setdefault(key, {})
  660. for inkey in value:
  661. append_hook(target[key], inkey, value[inkey])
  662. else:
  663. # make a list
  664. target.setdefault(key, [])
  665. if not isinstance(value, list):
  666. value = [value]
  667. target[key].extend(value)
  668. def setup_module_map():
  669. """Rebuild map of all modules (internal)."""
  670. _cache = cache()
  671. if conf.db_name:
  672. local.app_modules = _cache.get_value("app_modules")
  673. local.module_app = _cache.get_value("module_app")
  674. if not (local.app_modules and local.module_app):
  675. local.module_app, local.app_modules = {}, {}
  676. for app in get_all_apps(True):
  677. if app=="webnotes": app="frappe"
  678. local.app_modules.setdefault(app, [])
  679. for module in get_module_list(app):
  680. module = scrub(module)
  681. local.module_app[module] = app
  682. local.app_modules[app].append(module)
  683. if conf.db_name:
  684. _cache.set_value("app_modules", local.app_modules)
  685. _cache.set_value("module_app", local.module_app)
  686. def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
  687. """Returns items from text file as a list. Ignores empty lines."""
  688. import frappe.utils
  689. content = read_file(path, raise_not_found=raise_not_found)
  690. if content:
  691. content = frappe.utils.strip(content)
  692. return [p.strip() for p in content.splitlines() if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))]
  693. else:
  694. return []
  695. def get_file_json(path):
  696. """Read a file and return parsed JSON object."""
  697. with open(path, 'r') as f:
  698. return json.load(f)
  699. def read_file(path, raise_not_found=False):
  700. """Open a file and return its content as Unicode."""
  701. if isinstance(path, text_type):
  702. path = path.encode("utf-8")
  703. if os.path.exists(path):
  704. with open(path, "r") as f:
  705. return as_unicode(f.read())
  706. elif raise_not_found:
  707. raise IOError("{} Not Found".format(path))
  708. else:
  709. return None
  710. def get_attr(method_string):
  711. """Get python method object from its name."""
  712. app_name = method_string.split(".")[0]
  713. if not local.flags.in_install and app_name not in get_installed_apps():
  714. throw(_("App {0} is not installed").format(app_name), AppNotInstalledError)
  715. modulename = '.'.join(method_string.split('.')[:-1])
  716. methodname = method_string.split('.')[-1]
  717. return getattr(get_module(modulename), methodname)
  718. def call(fn, *args, **kwargs):
  719. """Call a function and match arguments."""
  720. if isinstance(fn, string_types):
  721. fn = get_attr(fn)
  722. if hasattr(fn, 'fnargs'):
  723. fnargs = fn.fnargs
  724. else:
  725. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  726. newargs = {}
  727. for a in kwargs:
  728. if (a in fnargs) or varkw:
  729. newargs[a] = kwargs.get(a)
  730. if "flags" in newargs:
  731. del newargs["flags"]
  732. return fn(*args, **newargs)
  733. def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
  734. """Create a new **Property Setter** (for overriding DocType and DocField properties).
  735. If doctype is not specified, it will create a property setter for all fields with the
  736. given fieldname"""
  737. args = _dict(args)
  738. if not args.doctype_or_field:
  739. args.doctype_or_field = 'DocField'
  740. if not args.property_type:
  741. args.property_type = db.get_value('DocField',
  742. {'parent': 'DocField', 'fieldname': args.property}, 'fieldtype') or 'Data'
  743. if not args.doctype:
  744. doctype_list = db.sql_list('select distinct parent from tabDocField where fieldname=%s', args.fieldname)
  745. else:
  746. doctype_list = [args.doctype]
  747. for doctype in doctype_list:
  748. if not args.property_type:
  749. args.property_type = db.get_value('DocField',
  750. {'parent': doctype, 'fieldname': args.fieldname}, 'fieldtype') or 'Data'
  751. ps = get_doc({
  752. 'doctype': "Property Setter",
  753. 'doctype_or_field': args.doctype_or_field,
  754. 'doc_type': doctype,
  755. 'field_name': args.fieldname,
  756. 'property': args.property,
  757. 'value': args.value,
  758. 'property_type': args.property_type or "Data",
  759. '__islocal': 1
  760. })
  761. ps.flags.ignore_validate = ignore_validate
  762. ps.flags.validate_fields_for_doctype = validate_fields_for_doctype
  763. ps.validate_fieldtype_change()
  764. ps.insert()
  765. def import_doc(path, ignore_links=False, ignore_insert=False, insert=False):
  766. """Import a file using Data Import Tool."""
  767. from frappe.core.page.data_import_tool import data_import_tool
  768. data_import_tool.import_doc(path, ignore_links=ignore_links, ignore_insert=ignore_insert, insert=insert)
  769. def copy_doc(doc, ignore_no_copy=True):
  770. """ No_copy fields also get copied."""
  771. import copy
  772. def remove_no_copy_fields(d):
  773. for df in d.meta.get("fields", {"no_copy": 1}):
  774. if hasattr(d, df.fieldname):
  775. d.set(df.fieldname, None)
  776. fields_to_clear = ['name', 'owner', 'creation', 'modified', 'modified_by']
  777. if not local.flags.in_test:
  778. fields_to_clear.append("docstatus")
  779. if not isinstance(doc, dict):
  780. d = doc.as_dict()
  781. else:
  782. d = doc
  783. newdoc = get_doc(copy.deepcopy(d))
  784. newdoc.set("__islocal", 1)
  785. for fieldname in (fields_to_clear + ['amended_from', 'amendment_date']):
  786. newdoc.set(fieldname, None)
  787. if not ignore_no_copy:
  788. remove_no_copy_fields(newdoc)
  789. for i, d in enumerate(newdoc.get_all_children()):
  790. d.set("__islocal", 1)
  791. for fieldname in fields_to_clear:
  792. d.set(fieldname, None)
  793. if not ignore_no_copy:
  794. remove_no_copy_fields(d)
  795. return newdoc
  796. def compare(val1, condition, val2):
  797. """Compare two values using `frappe.utils.compare`
  798. `condition` could be:
  799. - "^"
  800. - "in"
  801. - "not in"
  802. - "="
  803. - "!="
  804. - ">"
  805. - "<"
  806. - ">="
  807. - "<="
  808. - "not None"
  809. - "None"
  810. """
  811. import frappe.utils
  812. return frappe.utils.compare(val1, condition, val2)
  813. def respond_as_web_page(title, html, success=None, http_status_code=None,
  814. context=None, indicator_color=None, primary_action='/', primary_label = None, fullpage=False):
  815. """Send response as a web page with a message rather than JSON. Used to show permission errors etc.
  816. :param title: Page title and heading.
  817. :param message: Message to be shown.
  818. :param success: Alert message.
  819. :param http_status_code: HTTP status code
  820. :param context: web template context
  821. :param indicator_color: color of indicator in title
  822. :param primary_action: route on primary button (default is `/`)
  823. :param primary_label: label on primary button (defaut is "Home")
  824. :param fullpage: hide header / footer"""
  825. local.message_title = title
  826. local.message = html
  827. local.response['type'] = 'page'
  828. local.response['route'] = 'message'
  829. if http_status_code:
  830. local.response['http_status_code'] = http_status_code
  831. if not context:
  832. context = {}
  833. if not indicator_color:
  834. if success:
  835. indicator_color = 'green'
  836. elif http_status_code and http_status_code > 300:
  837. indicator_color = 'red'
  838. else:
  839. indicator_color = 'blue'
  840. context['indicator_color'] = indicator_color
  841. context['primary_label'] = primary_label
  842. context['primary_action'] = primary_action
  843. context['error_code'] = http_status_code
  844. context['fullpage'] = fullpage
  845. local.response['context'] = context
  846. def redirect_to_message(title, html, http_status_code=None, context=None, indicator_color=None):
  847. """Redirects to /message?id=random
  848. Similar to respond_as_web_page, but used to 'redirect' and show message pages like success, failure, etc. with a detailed message
  849. :param title: Page title and heading.
  850. :param message: Message to be shown.
  851. :param http_status_code: HTTP status code.
  852. Example Usage:
  853. frappe.redirect_to_message(_('Thank you'), "<div><p>You will receive an email at test@example.com</p></div>")
  854. """
  855. message_id = generate_hash(length=8)
  856. message = {
  857. 'context': context or {},
  858. 'http_status_code': http_status_code or 200
  859. }
  860. message['context'].update({
  861. 'header': title,
  862. 'title': title,
  863. 'message': html
  864. })
  865. if indicator_color:
  866. message['context'].update({
  867. "indicator_color": indicator_color
  868. })
  869. cache().set_value("message_id:{0}".format(message_id), message, expires_in_sec=60)
  870. location = '/message?id={0}'.format(message_id)
  871. if not getattr(local, 'is_ajax', False):
  872. local.response["type"] = "redirect"
  873. local.response["location"] = location
  874. else:
  875. return location
  876. def build_match_conditions(doctype, as_condition=True):
  877. """Return match (User permissions) for given doctype as list or SQL."""
  878. import frappe.desk.reportview
  879. return frappe.desk.reportview.build_match_conditions(doctype, as_condition)
  880. def get_list(doctype, *args, **kwargs):
  881. """List database query via `frappe.model.db_query`. Will also check for permissions.
  882. :param doctype: DocType on which query is to be made.
  883. :param fields: List of fields or `*`.
  884. :param filters: List of filters (see example).
  885. :param order_by: Order By e.g. `modified desc`.
  886. :param limit_page_start: Start results at record #. Default 0.
  887. :param limit_page_length: No of records in the page. Default 20.
  888. Example usage:
  889. # simple dict filter
  890. frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  891. # filter as a list of lists
  892. frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
  893. # filter as a list of dicts
  894. frappe.get_list("ToDo", fields="*", filters = {"description": ("like", "test%")})
  895. """
  896. import frappe.model.db_query
  897. return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
  898. def get_all(doctype, *args, **kwargs):
  899. """List database query via `frappe.model.db_query`. Will **not** check for conditions.
  900. Parameters are same as `frappe.get_list`
  901. :param doctype: DocType on which query is to be made.
  902. :param fields: List of fields or `*`. Default is: `["name"]`.
  903. :param filters: List of filters (see example).
  904. :param order_by: Order By e.g. `modified desc`.
  905. :param limit_page_start: Start results at record #. Default 0.
  906. :param limit_page_length: No of records in the page. Default 20.
  907. Example usage:
  908. # simple dict filter
  909. frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  910. # filter as a list of lists
  911. frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
  912. # filter as a list of dicts
  913. frappe.get_all("ToDo", fields=["*"], filters = {"description": ("like", "test%")})
  914. """
  915. kwargs["ignore_permissions"] = True
  916. if not "limit_page_length" in kwargs:
  917. kwargs["limit_page_length"] = 0
  918. return get_list(doctype, *args, **kwargs)
  919. def get_value(*args, **kwargs):
  920. """Returns a document property or list of properties.
  921. Alias for `frappe.db.get_value`
  922. :param doctype: DocType name.
  923. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType.
  924. :param fieldname: Column name.
  925. :param ignore: Don't raise exception if table, column is missing.
  926. :param as_dict: Return values as dict.
  927. :param debug: Print query in error log.
  928. """
  929. return db.get_value(*args, **kwargs)
  930. def as_json(obj, indent=1):
  931. from frappe.utils.response import json_handler
  932. return json.dumps(obj, indent=indent, sort_keys=True, default=json_handler)
  933. def are_emails_muted():
  934. from utils import cint
  935. return flags.mute_emails or cint(conf.get("mute_emails") or 0) or False
  936. def get_test_records(doctype):
  937. """Returns list of objects from `test_records.json` in the given doctype's folder."""
  938. from frappe.modules import get_doctype_module, get_module_path
  939. path = os.path.join(get_module_path(get_doctype_module(doctype)), "doctype", scrub(doctype), "test_records.json")
  940. if os.path.exists(path):
  941. with open(path, "r") as f:
  942. return json.loads(f.read())
  943. else:
  944. return []
  945. def format_value(*args, **kwargs):
  946. """Format value with given field properties.
  947. :param value: Value to be formatted.
  948. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  949. import frappe.utils.formatters
  950. return frappe.utils.formatters.format_value(*args, **kwargs)
  951. def format(*args, **kwargs):
  952. """Format value with given field properties.
  953. :param value: Value to be formatted.
  954. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  955. import frappe.utils.formatters
  956. return frappe.utils.formatters.format_value(*args, **kwargs)
  957. def get_print(doctype=None, name=None, print_format=None, style=None, html=None, as_pdf=False, doc=None, output = None):
  958. """Get Print Format for given document.
  959. :param doctype: DocType of document.
  960. :param name: Name of document.
  961. :param print_format: Print Format name. Default 'Standard',
  962. :param style: Print Format style.
  963. :param as_pdf: Return as PDF. Default False."""
  964. from frappe.website.render import build_page
  965. from frappe.utils.pdf import get_pdf
  966. local.form_dict.doctype = doctype
  967. local.form_dict.name = name
  968. local.form_dict.format = print_format
  969. local.form_dict.style = style
  970. local.form_dict.doc = doc
  971. if not html:
  972. html = build_page("printview")
  973. if as_pdf:
  974. return get_pdf(html, output = output)
  975. else:
  976. return html
  977. def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None):
  978. from frappe.utils import scrub_urls
  979. if not file_name: file_name = name
  980. file_name = file_name.replace(' ','').replace('/','-')
  981. print_settings = db.get_singles_dict("Print Settings")
  982. local.flags.ignore_print_permissions = True
  983. if int(print_settings.send_print_as_pdf or 0):
  984. out = {
  985. "fname": file_name + ".pdf",
  986. "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True, doc=doc)
  987. }
  988. else:
  989. out = {
  990. "fname": file_name + ".html",
  991. "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html, doc=doc)).encode("utf-8")
  992. }
  993. local.flags.ignore_print_permissions = False
  994. return out
  995. def publish_progress(*args, **kwargs):
  996. """Show the user progress for a long request
  997. :param percent: Percent progress
  998. :param title: Title
  999. :param doctype: Optional, for DocType
  1000. :param name: Optional, for Document name
  1001. """
  1002. import frappe.async
  1003. return frappe.async.publish_progress(*args, **kwargs)
  1004. def publish_realtime(*args, **kwargs):
  1005. """Publish real-time updates
  1006. :param event: Event name, like `task_progress` etc.
  1007. :param message: JSON message object. For async must contain `task_id`
  1008. :param room: Room in which to publish update (default entire site)
  1009. :param user: Transmit to user
  1010. :param doctype: Transmit to doctype, docname
  1011. :param docname: Transmit to doctype, docname
  1012. :param after_commit: (default False) will emit after current transaction is committed
  1013. """
  1014. import frappe.async
  1015. return frappe.async.publish_realtime(*args, **kwargs)
  1016. def local_cache(namespace, key, generator, regenerate_if_none=False):
  1017. """A key value store for caching within a request
  1018. :param namespace: frappe.local.cache[namespace]
  1019. :param key: frappe.local.cache[namespace][key] used to retrieve value
  1020. :param generator: method to generate a value if not found in store
  1021. """
  1022. if namespace not in local.cache:
  1023. local.cache[namespace] = {}
  1024. if key not in local.cache[namespace]:
  1025. local.cache[namespace][key] = generator()
  1026. elif local.cache[namespace][key]==None and regenerate_if_none:
  1027. # if key exists but the previous result was None
  1028. local.cache[namespace][key] = generator()
  1029. return local.cache[namespace][key]
  1030. def enqueue(*args, **kwargs):
  1031. '''
  1032. Enqueue method to be executed using a background worker
  1033. :param method: method string or method object
  1034. :param queue: (optional) should be either long, default or short
  1035. :param timeout: (optional) should be set according to the functions
  1036. :param event: this is passed to enable clearing of jobs from queues
  1037. :param async: (optional) if async=False, the method is executed immediately, else via a worker
  1038. :param job_name: (optional) can be used to name an enqueue call, which can be used to prevent duplicate calls
  1039. :param kwargs: keyword arguments to be passed to the method
  1040. '''
  1041. import frappe.utils.background_jobs
  1042. return frappe.utils.background_jobs.enqueue(*args, **kwargs)
  1043. def get_doctype_app(doctype):
  1044. def _get_doctype_app():
  1045. doctype_module = local.db.get_value("DocType", doctype, "module")
  1046. return local.module_app[scrub(doctype_module)]
  1047. return local_cache("doctype_app", doctype, generator=_get_doctype_app)
  1048. loggers = {}
  1049. log_level = None
  1050. def logger(module=None, with_more_info=True):
  1051. '''Returns a python logger that uses StreamHandler'''
  1052. from frappe.utils.logger import get_logger
  1053. return get_logger(module or 'default', with_more_info=with_more_info)
  1054. def log_error(message=None, title=None):
  1055. '''Log error to Error Log'''
  1056. get_doc(dict(doctype='Error Log', error=str(message or get_traceback()),
  1057. method=title)).insert(ignore_permissions=True)
  1058. def get_desk_link(doctype, name):
  1059. return '<a href="#Form/{0}/{1}" style="font-weight: bold;">{2} {1}</a>'.format(doctype, name, _(doctype))
  1060. def bold(text):
  1061. return '<b>{0}</b>'.format(text)
  1062. def safe_eval(code, eval_globals=None, eval_locals=None):
  1063. '''A safer `eval`'''
  1064. whitelisted_globals = {
  1065. "int": int,
  1066. "float": float,
  1067. "long": long,
  1068. "round": round
  1069. }
  1070. if '__' in code:
  1071. throw('Illegal rule {0}. Cannot use "__"'.format(bold(code)))
  1072. if not eval_globals:
  1073. eval_globals = {}
  1074. eval_globals['__builtins__'] = {}
  1075. eval_globals.update(whitelisted_globals)
  1076. return eval(code, eval_globals, eval_locals)
  1077. def get_system_settings(key):
  1078. if not local.system_settings.has_key(key):
  1079. local.system_settings.update({key: db.get_single_value('System Settings', key)})
  1080. return local.system_settings.get(key)
  1081. def get_active_domains():
  1082. from frappe.core.doctype.domain_settings.domain_settings import get_active_domains
  1083. return get_active_domains()