Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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