Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

__init__.py 12 KiB

13 anni fa
13 anni fa
13 anni fa
13 anni fa
13 anni fa
13 anni fa
13 anni fa
13 anni fa
12 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. from __future__ import unicode_literals
  23. """
  24. globals attached to webnotes module
  25. + some utility functions that should probably be moved
  26. """
  27. code_fields_dict = {
  28. 'Page':[('script', 'js'), ('content', 'html'), ('style', 'css'), ('static_content', 'html'), ('server_code', 'py')],
  29. 'DocType':[('server_code_core', 'py'), ('client_script_core', 'js')],
  30. 'Search Criteria':[('report_script', 'js'), ('server_script', 'py'), ('custom_query', 'sql')],
  31. 'Patch':[('patch_code', 'py')],
  32. 'Stylesheet':['stylesheet', 'css'],
  33. 'Page Template':['template', 'html'],
  34. 'Control Panel':[('startup_code', 'js'), ('startup_css', 'css')]
  35. }
  36. class _dict(dict):
  37. """dict like object that exposes keys as attributes"""
  38. def __getattr__(self, key):
  39. return self.get(key)
  40. def __setattr__(self, key, value):
  41. self[key] = value
  42. def __getstate__(self):
  43. return self
  44. def __setstate__(self, d):
  45. self.update(d)
  46. def update(self, d):
  47. """update and return self -- the missing dict feature in python"""
  48. super(_dict, self).update(d)
  49. return self
  50. def copy(self):
  51. return _dict(super(_dict, self).copy())
  52. def _(msg):
  53. """translate object in current lang, if exists"""
  54. from webnotes.translate import messages
  55. return messages.get(lang, {}).get(msg, msg)
  56. request = form_dict = _dict()
  57. conn = None
  58. _memc = None
  59. form = None
  60. session = None
  61. user = None
  62. incoming_cookies = {}
  63. add_cookies = {} # append these to outgoing request
  64. cookies = {}
  65. response = _dict({'message':'', 'exc':''})
  66. debug_log = []
  67. message_log = []
  68. mute_emails = False
  69. test_objects = {}
  70. request_method = None
  71. print_messages = False
  72. user_lang = False
  73. lang = 'en'
  74. in_import = False
  75. # memcache
  76. def cache():
  77. global _memc
  78. if not _memc:
  79. from webnotes.memc import MClient
  80. _memc = MClient(['localhost:11211'])
  81. return _memc
  82. class DuplicateEntryError(Exception): pass
  83. class ValidationError(Exception): pass
  84. class AuthenticationError(Exception): pass
  85. class PermissionError(Exception): pass
  86. class OutgoingEmailError(ValidationError): pass
  87. class UnknownDomainError(Exception): pass
  88. class SessionStopped(Exception): pass
  89. class MappingMismatchError(ValidationError): pass
  90. class InvalidStatusError(ValidationError): pass
  91. class DoesNotExistError(ValidationError): pass
  92. def getTraceback():
  93. import utils
  94. return utils.getTraceback()
  95. def errprint(msg):
  96. if not request_method:
  97. print repr(msg)
  98. from utils import cstr
  99. debug_log.append(cstr(msg or ''))
  100. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  101. from utils import cstr
  102. if as_table and type(msg) in (list, tuple):
  103. 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>'
  104. if print_messages:
  105. print "Message: " + repr(msg)
  106. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  107. if raise_exception:
  108. import inspect
  109. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  110. raise raise_exception, msg
  111. else:
  112. raise ValidationError, msg
  113. def create_folder(path):
  114. import os
  115. try:
  116. os.makedirs(path)
  117. except OSError, e:
  118. if e.args[0]!=17:
  119. raise e
  120. def create_symlink(source_path, link_path):
  121. import os
  122. try:
  123. os.symlink(source_path, link_path)
  124. except OSError, e:
  125. if e.args[0]!=17:
  126. raise e
  127. def remove_file(path):
  128. import os
  129. try:
  130. os.remove(path)
  131. except OSError, e:
  132. if e.args[0]!=2:
  133. raise e
  134. def connect(db_name=None, password=None):
  135. import webnotes.db
  136. global conn
  137. conn = webnotes.db.Database(user=db_name, password=password)
  138. global session
  139. session = _dict({'user':'Administrator'})
  140. import webnotes.profile
  141. global user
  142. user = webnotes.profile.Profile('Administrator')
  143. def get_env_vars(env_var):
  144. import os
  145. return os.environ.get(env_var,'None')
  146. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  147. logger = None
  148. def get_db_password(db_name):
  149. """get db password from conf"""
  150. import conf
  151. if hasattr(conf, 'get_db_password'):
  152. return conf.get_db_password(db_name)
  153. elif hasattr(conf, 'db_password'):
  154. return conf.db_password
  155. else:
  156. return db_name
  157. whitelisted = []
  158. guest_methods = []
  159. def whitelist(allow_guest=False, allow_roles=None):
  160. """
  161. decorator for whitelisting a function
  162. Note: if the function is allowed to be accessed by a guest user,
  163. it must explicitly be marked as allow_guest=True
  164. for specific roles, set allow_roles = ['Administrator'] etc.
  165. """
  166. def innerfn(fn):
  167. global whitelisted, guest_methods
  168. whitelisted.append(fn)
  169. if allow_guest:
  170. guest_methods.append(fn)
  171. if allow_roles:
  172. roles = get_roles()
  173. allowed = False
  174. for role in allow_roles:
  175. if role in roles:
  176. allowed = True
  177. break
  178. if not allowed:
  179. raise PermissionError, "Method not allowed"
  180. return fn
  181. return innerfn
  182. def clear_cache(user=None, doctype=None):
  183. """clear cache"""
  184. if doctype:
  185. from webnotes.model.doctype import clear_cache
  186. clear_cache(doctype)
  187. elif user:
  188. from webnotes.sessions import clear_cache
  189. clear_cache(user)
  190. else:
  191. from webnotes.sessions import clear_cache
  192. clear_cache()
  193. def get_roles(user=None, with_standard=True):
  194. """get roles of current user"""
  195. if not user:
  196. user = session.user
  197. if user=='Guest':
  198. return ['Guest']
  199. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  200. where parent=%s and role!='All'""", user)] + ['All']
  201. # filter standard if required
  202. if not with_standard:
  203. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  204. return roles
  205. def has_permission(doctype, ptype="read", doc=None):
  206. """check if user has permission"""
  207. from webnotes.defaults import get_user_default_as_list
  208. if session.user=="Administrator":
  209. return True
  210. if conn.get_value("DocType", doctype, "istable"):
  211. return True
  212. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  213. where p.parent = %s
  214. and ifnull(p.`%s`,0) = 1
  215. and ifnull(p.permlevel,0) = 0
  216. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  217. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  218. if doc:
  219. match_failed = {}
  220. for p in perms:
  221. if p.match:
  222. if ":" in p.match:
  223. keys = p.match.split(":")
  224. else:
  225. keys = [p.match, p.match]
  226. if doc.fields.get(keys[0],"[No Value]") \
  227. in get_user_default_as_list(keys[1]):
  228. return True
  229. else:
  230. match_failed[keys[0]] = doc.fields.get(keys[0],"[No Value]")
  231. else:
  232. # found a permission without a match
  233. return True
  234. # no valid permission found
  235. if match_failed:
  236. doctypelist = get_doctype(doctype)
  237. msg = _("Not allowed for: ")
  238. for key in match_failed:
  239. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  240. + " = " + (match_failed[key] or "None")
  241. msgprint(msg)
  242. return False
  243. else:
  244. return perms and True or False
  245. def generate_hash():
  246. """Generates random hash for session id"""
  247. import hashlib, time
  248. return hashlib.sha224(str(time.time())).hexdigest()
  249. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  250. from webnotes.model.code import get_obj
  251. return get_obj(dt, dn, doc, doclist, with_children)
  252. def doc(doctype=None, name=None, fielddata=None):
  253. from webnotes.model.doc import Document
  254. return Document(doctype, name, fielddata)
  255. def doclist(lst=None):
  256. from webnotes.model.doclist import DocList
  257. return DocList(lst)
  258. def bean(doctype=None, name=None, copy=None):
  259. from webnotes.model.bean import Bean
  260. if copy:
  261. return Bean(copy_doclist(copy))
  262. else:
  263. return Bean(doctype, name)
  264. def get_doclist(doctype, name=None):
  265. return bean(doctype, name).doclist
  266. def get_doctype(doctype, processed=False):
  267. import webnotes.model.doctype
  268. return webnotes.model.doctype.get(doctype, processed)
  269. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=[], for_reload=False):
  270. import webnotes.model.utils
  271. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload)
  272. def clear_perms(doctype):
  273. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  274. def reset_perms(doctype):
  275. clear_perms(doctype)
  276. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  277. def reload_doc(module, dt=None, dn=None):
  278. import webnotes.modules
  279. return webnotes.modules.reload_doc(module, dt, dn)
  280. def rename_doc(doctype, old, new, debug=0, force=False):
  281. from webnotes.model.rename_doc import rename_doc
  282. rename_doc(doctype, old, new, force=force)
  283. def insert(doclist):
  284. import webnotes.model
  285. return webnotes.model.insert(doclist)
  286. def get_method(method_string):
  287. modulename = '.'.join(method_string.split('.')[:-1])
  288. methodname = method_string.split('.')[-1]
  289. __import__(modulename)
  290. import sys
  291. moduleobj = sys.modules[modulename]
  292. return getattr(moduleobj, methodname)
  293. def make_property_setter(args):
  294. args = _dict(args)
  295. bean([{
  296. 'doctype': "Property Setter",
  297. 'doctype_or_field': args.doctype_or_field or "DocField",
  298. 'doc_type': args.doctype,
  299. 'field_name': args.fieldname,
  300. 'property': args.property,
  301. 'value': args.value,
  302. 'property_type': args.property_type or "Data",
  303. '__islocal': 1
  304. }]).save()
  305. def get_application_home_page(user='Guest'):
  306. """get home page for user"""
  307. hpl = conn.sql("""select home_page
  308. from `tabDefault Home Page`
  309. where parent='Control Panel'
  310. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  311. if hpl:
  312. return hpl[0][0]
  313. else:
  314. from startup import application_home_page
  315. return application_home_page
  316. def copy_doclist(in_doclist):
  317. new_doclist = []
  318. for d in in_doclist:
  319. if isinstance(d, dict):
  320. new_doclist.append(d.copy())
  321. else:
  322. new_doclist.append(doc(d.fields.copy()))
  323. return doclist(new_doclist)
  324. def map_doclist(from_to_list, from_docname, to_doclist=None):
  325. from_doctype, to_doctype = from_to_list[0][0], from_to_list[0][1]
  326. if to_doclist:
  327. to_doclist = bean(to_doclist).doclist
  328. else:
  329. to_doclist = bean({"doctype": to_doctype}).doclist
  330. mapper = get_obj("DocType Mapper", "-".join(from_to_list[0]))
  331. to_doclist = mapper.dt_map(from_doctype, to_doctype, from_docname, to_doclist[0], to_doclist, from_to_list)
  332. return to_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. _config = None
  343. def get_config():
  344. global _config
  345. if not _config:
  346. import webnotes.utils, json
  347. _config = _dict({"modules": {}, "web": _dict({"pages": {}, "generators": {}})})
  348. with open(webnotes.utils.get_path("lib", "config.json"), "r") as configf:
  349. framework_config = json.loads(configf.read())
  350. _config.modules.update(framework_config["modules"])
  351. _config.web.pages.update(framework_config["web"]["pages"])
  352. _config.web.generators.update(framework_config["web"]["generators"])
  353. with open(webnotes.utils.get_path("app", "config.json"), "r") as configf:
  354. app_config = json.loads(configf.read())
  355. _config.modules.update(app_config["modules"])
  356. _config.web.pages.update(app_config["web"]["pages"])
  357. _config.web.generators.update(app_config["web"]["generators"])
  358. return _config