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.
 
 
 
 
 
 

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