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.

__init__.py 12 KiB

12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. error_log = []
  67. debug_log = []
  68. message_log = []
  69. mute_emails = False
  70. test_objects = {}
  71. request_method = None
  72. print_messages = False
  73. user_lang = False
  74. lang = 'en'
  75. in_import = False
  76. # memcache
  77. def cache():
  78. global _memc
  79. if not _memc:
  80. from webnotes.memc import MClient
  81. _memc = MClient(['localhost:11211'])
  82. return _memc
  83. class DuplicateEntryError(Exception): pass
  84. class ValidationError(Exception): pass
  85. class AuthenticationError(Exception): pass
  86. class PermissionError(Exception): pass
  87. class OutgoingEmailError(ValidationError): pass
  88. class UnknownDomainError(Exception): pass
  89. class SessionStopped(Exception): pass
  90. class MappingMismatchError(ValidationError): pass
  91. class InvalidStatusError(ValidationError): pass
  92. class DoesNotExistError(ValidationError): pass
  93. def getTraceback():
  94. import utils
  95. return utils.getTraceback()
  96. def errprint(msg):
  97. if not request_method:
  98. print repr(msg)
  99. from utils import cstr
  100. error_log.append(cstr(msg))
  101. def log(msg):
  102. if not request_method:
  103. import conf
  104. if getattr(conf, "logging", False):
  105. print repr(msg)
  106. from utils import cstr
  107. debug_log.append(cstr(msg))
  108. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  109. from utils import cstr
  110. if as_table and type(msg) in (list, tuple):
  111. 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>'
  112. if print_messages:
  113. print "Message: " + repr(msg)
  114. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  115. if raise_exception:
  116. import inspect
  117. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  118. raise raise_exception, msg
  119. else:
  120. raise ValidationError, msg
  121. def create_folder(path):
  122. import os
  123. try:
  124. os.makedirs(path)
  125. except OSError, e:
  126. if e.args[0]!=17:
  127. raise e
  128. def create_symlink(source_path, link_path):
  129. import os
  130. try:
  131. os.symlink(source_path, link_path)
  132. except OSError, e:
  133. if e.args[0]!=17:
  134. raise e
  135. def remove_file(path):
  136. import os
  137. try:
  138. os.remove(path)
  139. except OSError, e:
  140. if e.args[0]!=2:
  141. raise e
  142. def connect(db_name=None, password=None):
  143. import webnotes.db
  144. global conn
  145. conn = webnotes.db.Database(user=db_name, password=password)
  146. global session
  147. session = _dict({'user':'Administrator'})
  148. import webnotes.profile
  149. global user
  150. user = webnotes.profile.Profile('Administrator')
  151. def get_env_vars(env_var):
  152. import os
  153. return os.environ.get(env_var,'None')
  154. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  155. logger = None
  156. def get_db_password(db_name):
  157. """get db password from conf"""
  158. import conf
  159. if hasattr(conf, 'get_db_password'):
  160. return conf.get_db_password(db_name)
  161. elif hasattr(conf, 'db_password'):
  162. return conf.db_password
  163. else:
  164. return db_name
  165. whitelisted = []
  166. guest_methods = []
  167. def whitelist(allow_guest=False, allow_roles=None):
  168. """
  169. decorator for whitelisting a function
  170. Note: if the function is allowed to be accessed by a guest user,
  171. it must explicitly be marked as allow_guest=True
  172. for specific roles, set allow_roles = ['Administrator'] etc.
  173. """
  174. def innerfn(fn):
  175. global whitelisted, guest_methods
  176. whitelisted.append(fn)
  177. if allow_guest:
  178. guest_methods.append(fn)
  179. if allow_roles:
  180. roles = get_roles()
  181. allowed = False
  182. for role in allow_roles:
  183. if role in roles:
  184. allowed = True
  185. break
  186. if not allowed:
  187. raise PermissionError, "Method not allowed"
  188. return fn
  189. return innerfn
  190. def clear_cache(user=None, doctype=None):
  191. """clear cache"""
  192. if doctype:
  193. from webnotes.model.doctype import clear_cache
  194. clear_cache(doctype)
  195. elif user:
  196. from webnotes.sessions import clear_cache
  197. clear_cache(user)
  198. else:
  199. from webnotes.sessions import clear_cache
  200. clear_cache()
  201. def get_roles(user=None, with_standard=True):
  202. """get roles of current user"""
  203. if not user:
  204. user = session.user
  205. if user=='Guest':
  206. return ['Guest']
  207. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  208. where parent=%s and role!='All'""", user)] + ['All']
  209. # filter standard if required
  210. if not with_standard:
  211. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  212. return roles
  213. def has_permission(doctype, ptype="read", doc=None):
  214. """check if user has permission"""
  215. from webnotes.defaults import get_user_default_as_list
  216. if session.user=="Administrator":
  217. return True
  218. if conn.get_value("DocType", doctype, "istable"):
  219. return True
  220. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  221. where p.parent = %s
  222. and ifnull(p.`%s`,0) = 1
  223. and ifnull(p.permlevel,0) = 0
  224. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  225. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  226. if doc:
  227. match_failed = {}
  228. for p in perms:
  229. if p.match:
  230. if ":" in p.match:
  231. keys = p.match.split(":")
  232. else:
  233. keys = [p.match, p.match]
  234. if doc.fields.get(keys[0],"[No Value]") \
  235. in get_user_default_as_list(keys[1]):
  236. return True
  237. else:
  238. match_failed[keys[0]] = doc.fields.get(keys[0],"[No Value]")
  239. else:
  240. # found a permission without a match
  241. return True
  242. # no valid permission found
  243. if match_failed:
  244. doctypelist = get_doctype(doctype)
  245. msg = _("Not allowed for: ")
  246. for key in match_failed:
  247. msg += "\n" + (doctypelist.get_field(key) and doctypelist.get_label(key) or key) \
  248. + " = " + (match_failed[key] or "None")
  249. msgprint(msg)
  250. return False
  251. else:
  252. return perms and True or False
  253. def generate_hash():
  254. """Generates random hash for session id"""
  255. import hashlib, time
  256. return hashlib.sha224(str(time.time())).hexdigest()
  257. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  258. from webnotes.model.code import get_obj
  259. return get_obj(dt, dn, doc, doclist, with_children)
  260. def doc(doctype=None, name=None, fielddata=None):
  261. from webnotes.model.doc import Document
  262. return Document(doctype, name, fielddata)
  263. def doclist(lst=None):
  264. from webnotes.model.doclist import DocList
  265. return DocList(lst)
  266. def bean(doctype=None, name=None, copy=None):
  267. from webnotes.model.bean import Bean
  268. if copy:
  269. return Bean(copy_doclist(copy))
  270. else:
  271. return Bean(doctype, name)
  272. def get_doclist(doctype, name=None):
  273. return bean(doctype, name).doclist
  274. def get_doctype(doctype, processed=False):
  275. import webnotes.model.doctype
  276. return webnotes.model.doctype.get(doctype, processed)
  277. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=[], for_reload=False):
  278. import webnotes.model.utils
  279. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload)
  280. def clear_perms(doctype):
  281. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  282. def reset_perms(doctype):
  283. clear_perms(doctype)
  284. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  285. def reload_doc(module, dt=None, dn=None):
  286. import webnotes.modules
  287. return webnotes.modules.reload_doc(module, dt, dn)
  288. def rename_doc(doctype, old, new, debug=0, force=False):
  289. from webnotes.model.rename_doc import rename_doc
  290. rename_doc(doctype, old, new, force=force)
  291. def insert(doclist):
  292. import webnotes.model
  293. return webnotes.model.insert(doclist)
  294. def get_method(method_string):
  295. modulename = '.'.join(method_string.split('.')[:-1])
  296. methodname = method_string.split('.')[-1]
  297. __import__(modulename)
  298. import sys
  299. moduleobj = sys.modules[modulename]
  300. return getattr(moduleobj, methodname)
  301. def make_property_setter(args):
  302. args = _dict(args)
  303. bean([{
  304. 'doctype': "Property Setter",
  305. 'doctype_or_field': args.doctype_or_field or "DocField",
  306. 'doc_type': args.doctype,
  307. 'field_name': args.fieldname,
  308. 'property': args.property,
  309. 'value': args.value,
  310. 'property_type': args.property_type or "Data",
  311. '__islocal': 1
  312. }]).save()
  313. def get_application_home_page(user='Guest'):
  314. """get home page for user"""
  315. hpl = conn.sql("""select home_page
  316. from `tabDefault Home Page`
  317. where parent='Control Panel'
  318. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  319. if hpl:
  320. return hpl[0][0]
  321. else:
  322. from startup import application_home_page
  323. return application_home_page
  324. def copy_doclist(in_doclist):
  325. new_doclist = []
  326. for d in in_doclist:
  327. if isinstance(d, dict):
  328. new_doclist.append(d.copy())
  329. else:
  330. new_doclist.append(doc(d.fields.copy()))
  331. return doclist(new_doclist)
  332. def map_doclist(from_to_list, from_docname, to_doclist=None):
  333. from_doctype, to_doctype = from_to_list[0][0], from_to_list[0][1]
  334. if to_doclist:
  335. to_doclist = bean(to_doclist).doclist
  336. else:
  337. to_doclist = bean({"doctype": to_doctype}).doclist
  338. mapper = get_obj("DocType Mapper", "-".join(from_to_list[0]))
  339. to_doclist = mapper.dt_map(from_doctype, to_doctype, from_docname, to_doclist[0], to_doclist, from_to_list)
  340. return to_doclist
  341. def compare(val1, condition, val2):
  342. import webnotes.utils
  343. return webnotes.utils.compare(val1, condition, val2)
  344. def repsond_as_web_page(title, html):
  345. global message, message_title, response
  346. message_title = title
  347. message = "<h3>" + title + "</h3>" + html
  348. response['type'] = 'page'
  349. response['page_name'] = 'message.html'
  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