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.
 
 
 
 
 
 

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