Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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