You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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