Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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