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.
 
 
 
 
 
 

1275 rivejä
39 KiB

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