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.

12 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
12 年之前
12 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. """
  23. globals attached to webnotes module
  24. + some utility functions that should probably be moved
  25. """
  26. from __future__ import unicode_literals
  27. class _dict(dict):
  28. """dict like object that exposes keys as attributes"""
  29. def __getattr__(self, key):
  30. return self.get(key)
  31. def __setattr__(self, key, value):
  32. self[key] = value
  33. def __getstate__(self):
  34. return self
  35. def __setstate__(self, d):
  36. self.update(d)
  37. def update(self, d):
  38. """update and return self -- the missing dict feature in python"""
  39. super(_dict, self).update(d)
  40. return self
  41. def copy(self):
  42. return _dict(super(_dict, self).copy())
  43. def _(msg):
  44. """translate object in current lang, if exists"""
  45. from webnotes.translate import messages
  46. return messages.get(lang, {}).get(msg, msg)
  47. request = form_dict = _dict()
  48. conn = None
  49. _memc = None
  50. form = None
  51. session = None
  52. user = None
  53. incoming_cookies = {}
  54. add_cookies = {} # append these to outgoing request
  55. cookies = {}
  56. response = _dict({'message':'', 'exc':''})
  57. error_log = []
  58. debug_log = []
  59. message_log = []
  60. mute_emails = False
  61. test_objects = {}
  62. request_method = None
  63. print_messages = False
  64. user_lang = False
  65. lang = 'en'
  66. in_import = False
  67. # memcache
  68. def cache():
  69. global _memc
  70. if not _memc:
  71. from webnotes.memc import MClient
  72. _memc = MClient(['localhost:11211'])
  73. return _memc
  74. class DuplicateEntryError(Exception): pass
  75. class ValidationError(Exception): pass
  76. class AuthenticationError(Exception): pass
  77. class PermissionError(Exception): pass
  78. class OutgoingEmailError(ValidationError): pass
  79. class UnknownDomainError(Exception): pass
  80. class SessionStopped(Exception): pass
  81. class MappingMismatchError(ValidationError): pass
  82. class InvalidStatusError(ValidationError): pass
  83. class DoesNotExistError(ValidationError): pass
  84. def getTraceback():
  85. import utils
  86. return utils.getTraceback()
  87. def errprint(msg):
  88. from utils import cstr
  89. if not request_method:
  90. print cstr(msg)
  91. error_log.append(cstr(msg))
  92. def log(msg):
  93. if not request_method:
  94. import conf
  95. if getattr(conf, "logging", False):
  96. print repr(msg)
  97. from utils import cstr
  98. debug_log.append(cstr(msg))
  99. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  100. from utils import cstr
  101. if as_table and type(msg) in (list, tuple):
  102. 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>'
  103. if print_messages:
  104. print "Message: " + repr(msg)
  105. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  106. if raise_exception:
  107. import inspect
  108. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  109. raise raise_exception, msg
  110. else:
  111. raise ValidationError, msg
  112. def create_folder(path):
  113. import os
  114. try:
  115. os.makedirs(path)
  116. except OSError, e:
  117. if e.args[0]!=17:
  118. raise e
  119. def create_symlink(source_path, link_path):
  120. import os
  121. try:
  122. os.symlink(source_path, link_path)
  123. except OSError, e:
  124. if e.args[0]!=17:
  125. raise e
  126. def remove_file(path):
  127. import os
  128. try:
  129. os.remove(path)
  130. except OSError, e:
  131. if e.args[0]!=2:
  132. raise e
  133. def connect(db_name=None, password=None):
  134. import webnotes.db
  135. global conn
  136. conn = webnotes.db.Database(user=db_name, password=password)
  137. global session
  138. session = _dict({'user':'Administrator'})
  139. import webnotes.profile
  140. global user
  141. user = webnotes.profile.Profile('Administrator')
  142. def get_env_vars(env_var):
  143. import os
  144. return os.environ.get(env_var,'None')
  145. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  146. logger = None
  147. def get_db_password(db_name):
  148. """get db password from conf"""
  149. import conf
  150. if hasattr(conf, 'get_db_password'):
  151. return conf.get_db_password(db_name)
  152. elif hasattr(conf, 'db_password'):
  153. return conf.db_password
  154. else:
  155. return db_name
  156. whitelisted = []
  157. guest_methods = []
  158. def whitelist(allow_guest=False, allow_roles=None):
  159. """
  160. decorator for whitelisting a function
  161. Note: if the function is allowed to be accessed by a guest user,
  162. it must explicitly be marked as allow_guest=True
  163. for specific roles, set allow_roles = ['Administrator'] etc.
  164. """
  165. def innerfn(fn):
  166. global whitelisted, guest_methods
  167. whitelisted.append(fn)
  168. if allow_guest:
  169. guest_methods.append(fn)
  170. if allow_roles:
  171. roles = get_roles()
  172. allowed = False
  173. for role in allow_roles:
  174. if role in roles:
  175. allowed = True
  176. break
  177. if not allowed:
  178. raise PermissionError, "Method not allowed"
  179. return fn
  180. return innerfn
  181. def clear_cache(user=None, doctype=None):
  182. """clear cache"""
  183. if doctype:
  184. from webnotes.model.doctype import clear_cache
  185. clear_cache(doctype)
  186. elif user:
  187. from webnotes.sessions import clear_cache
  188. clear_cache(user)
  189. else:
  190. from webnotes.sessions import clear_cache
  191. clear_cache()
  192. def get_roles(user=None, with_standard=True):
  193. """get roles of current user"""
  194. if not user:
  195. user = session.user
  196. if user=='Guest':
  197. return ['Guest']
  198. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  199. where parent=%s and role!='All'""", user)] + ['All']
  200. # filter standard if required
  201. if not with_standard:
  202. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  203. return roles
  204. def has_permission(doctype, ptype="read", doc=None):
  205. """check if user has permission"""
  206. from webnotes.defaults import get_user_default_as_list
  207. if session.user=="Administrator":
  208. return True
  209. if conn.get_value("DocType", doctype, "istable"):
  210. return True
  211. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  212. where p.parent = %s
  213. and ifnull(p.`%s`,0) = 1
  214. and ifnull(p.permlevel,0) = 0
  215. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  216. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  217. if doc:
  218. match_failed = {}
  219. for p in perms:
  220. if p.match:
  221. if ":" in p.match:
  222. keys = p.match.split(":")
  223. else:
  224. keys = [p.match, p.match]
  225. if doc.fields.get(keys[0],"[No Value]") \
  226. in get_user_default_as_list(keys[1]):
  227. return True
  228. else:
  229. match_failed[keys[0]] = doc.fields.get(keys[0],"[No Value]")
  230. else:
  231. # found a permission without a match
  232. return True
  233. # no valid permission found
  234. if match_failed:
  235. doctypelist = get_doctype(doctype)
  236. msg = _("Not allowed for: ")
  237. for key in match_failed:
  238. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  239. + " = " + (match_failed[key] or "None")
  240. msgprint(msg)
  241. return False
  242. else:
  243. return perms and True or False
  244. def generate_hash():
  245. """Generates random hash for session id"""
  246. import hashlib, time
  247. return hashlib.sha224(str(time.time())).hexdigest()
  248. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  249. from webnotes.model.code import get_obj
  250. return get_obj(dt, dn, doc, doclist, with_children)
  251. def doc(doctype=None, name=None, fielddata=None):
  252. from webnotes.model.doc import Document
  253. return Document(doctype, name, fielddata)
  254. def new_doc(doctype, parent_doc=None, parentfield=None):
  255. from webnotes.model.create_new import get_new_doc
  256. return get_new_doc(doctype, parent_doc, parentfield)
  257. def doclist(lst=None):
  258. from webnotes.model.doclist import DocList
  259. return DocList(lst)
  260. def bean(doctype=None, name=None, copy=None):
  261. """return an instance of the object, wrapped as a Bean (webnotes.model.bean)"""
  262. from webnotes.model.bean import Bean
  263. if copy:
  264. return Bean(copy_doclist(copy))
  265. else:
  266. return Bean(doctype, name)
  267. def get_doclist(doctype, name=None):
  268. return bean(doctype, name).doclist
  269. def get_doctype(doctype, processed=False):
  270. import webnotes.model.doctype
  271. return webnotes.model.doctype.get(doctype, processed)
  272. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=None, for_reload=False):
  273. import webnotes.model.utils
  274. if not ignore_doctypes:
  275. ignore_doctypes = []
  276. if isinstance(name, list):
  277. for n in name:
  278. webnotes.model.utils.delete_doc(doctype, n, doclist, force, ignore_doctypes, for_reload)
  279. else:
  280. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload)
  281. def clear_perms(doctype):
  282. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  283. def reset_perms(doctype):
  284. clear_perms(doctype)
  285. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  286. def reload_doc(module, dt=None, dn=None):
  287. import webnotes.modules
  288. return webnotes.modules.reload_doc(module, dt, dn)
  289. def rename_doc(doctype, old, new, debug=0, force=False, merge=False):
  290. from webnotes.model.rename_doc import rename_doc
  291. rename_doc(doctype, old, new, force=force, merge=merge)
  292. def insert(doclist):
  293. import webnotes.model
  294. return webnotes.model.insert(doclist)
  295. def get_method(method_string):
  296. modulename = '.'.join(method_string.split('.')[:-1])
  297. methodname = method_string.split('.')[-1]
  298. __import__(modulename)
  299. import sys
  300. moduleobj = sys.modules[modulename]
  301. return getattr(moduleobj, methodname)
  302. def make_property_setter(args):
  303. args = _dict(args)
  304. bean([{
  305. 'doctype': "Property Setter",
  306. 'doctype_or_field': args.doctype_or_field or "DocField",
  307. 'doc_type': args.doctype,
  308. 'field_name': args.fieldname,
  309. 'property': args.property,
  310. 'value': args.value,
  311. 'property_type': args.property_type or "Data",
  312. '__islocal': 1
  313. }]).save()
  314. def get_application_home_page(user='Guest'):
  315. """get home page for user"""
  316. hpl = conn.sql("""select home_page
  317. from `tabDefault Home Page`
  318. where parent='Control Panel'
  319. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  320. if hpl:
  321. return hpl[0][0]
  322. else:
  323. from startup import application_home_page
  324. return application_home_page
  325. def copy_doclist(in_doclist):
  326. new_doclist = []
  327. for d in in_doclist:
  328. if isinstance(d, dict):
  329. new_doclist.append(d.copy())
  330. else:
  331. new_doclist.append(doc(d.fields.copy()))
  332. return doclist(new_doclist)
  333. def compare(val1, condition, val2):
  334. import webnotes.utils
  335. return webnotes.utils.compare(val1, condition, val2)
  336. def repsond_as_web_page(title, html):
  337. global message, message_title, response
  338. message_title = title
  339. message = "<h3>" + title + "</h3>" + html
  340. response['type'] = 'page'
  341. response['page_name'] = 'message.html'
  342. def load_json(obj):
  343. if isinstance(obj, basestring):
  344. import json
  345. try:
  346. obj = json.loads(obj)
  347. except ValueError:
  348. pass
  349. return obj
  350. _config = None
  351. def get_config():
  352. global _config
  353. if not _config:
  354. import webnotes.utils, json
  355. _config = _dict({"modules": {}, "web": _dict({"pages": {}, "generators": {}})})
  356. with open(webnotes.utils.get_path("lib", "config.json"), "r") as configf:
  357. framework_config = json.loads(configf.read())
  358. _config.modules.update(framework_config["modules"])
  359. _config.web.pages.update(framework_config["web"]["pages"])
  360. _config.web.generators.update(framework_config["web"]["generators"])
  361. with open(webnotes.utils.get_path("app", "config.json"), "r") as configf:
  362. app_config = json.loads(configf.read())
  363. _config.modules.update(app_config["modules"])
  364. _config.web.pages.update(app_config["web"]["pages"])
  365. _config.web.generators.update(app_config["web"]["generators"])
  366. return _config