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.
 
 
 
 
 
 

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