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.
 
 
 
 
 
 

212 line
4.8 KiB

  1. #
  2. # import modules path
  3. #
  4. import os, sys
  5. try:
  6. import webnotes.defs
  7. m = getattr(webnotes.defs,'modules_path',None)
  8. m and sys.path.append(m)
  9. except Exception,e:
  10. raise e
  11. #
  12. # map for identifying which field values come from files
  13. #
  14. code_fields_dict = {
  15. 'Page':[('script', 'js'), ('content', 'html'), ('style', 'css'), ('static_content', 'html'), ('server_code', 'py')],
  16. 'DocType':[('server_code_core', 'py'), ('client_script_core', 'js')],
  17. 'Search Criteria':[('report_script', 'js'), ('server_script', 'py'), ('custom_query', 'sql')],
  18. 'Patch':[('patch_code', 'py')],
  19. 'Stylesheet':['stylesheet', 'css'],
  20. 'Page Template':['template', 'html'],
  21. 'Control Panel':[('startup_code', 'js'), ('startup_css', 'css')]
  22. }
  23. #
  24. # globals
  25. #
  26. #: "v170"
  27. version = 'v170'
  28. form_dict = {}
  29. auth_obj = None
  30. #: The database connection :class:`webnotes.db.Database` setup by :mod:`auth`
  31. conn = None
  32. #: The cgi.FieldStorage() object (Dictionary representing the formdata from the URL)
  33. form = None
  34. session = None
  35. """
  36. Global session dictionary.
  37. * session['user'] - Current user
  38. * session['data'] - Returns a dictionary of the session cache
  39. """
  40. user = None
  41. is_testing = None
  42. """ Flag to identify if system is in :term:`Testing Mode` """
  43. incoming_cookies = {}
  44. add_cookies = {}
  45. """ Dictionary of additional cookies appended by custom code """
  46. cookies = {}
  47. auto_masters = {}
  48. tenant_id = None
  49. from webnotes.utils import cstr
  50. #
  51. # Custom Class (no traceback)
  52. #
  53. class ValidationError(Exception):
  54. pass
  55. #
  56. # HTTP standard response
  57. #
  58. response = {'message':'', 'exc':''}
  59. """
  60. The JSON response object. Default is::
  61. {'message':'', 'exc':''}
  62. """
  63. #
  64. # the logs
  65. #
  66. debug_log = []
  67. """ List of exceptions to be shown in the :term:`Error Console` """
  68. message_log = []
  69. """ List of messages to be shown to the user in a popup box at the end of the request """
  70. def getTraceback():
  71. import webnotes.utils
  72. return webnotes.utils.getTraceback()
  73. def errprint(msg):
  74. """
  75. Append to the :data:`debug log`
  76. """
  77. debug_log.append(cstr(msg or ''))
  78. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  79. """
  80. Append to the :data:`message_log`
  81. """
  82. if as_table and type(msg) in (list, tuple):
  83. 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>'
  84. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  85. if raise_exception:
  86. raise ValidationError
  87. def is_apache_user():
  88. import os
  89. if os.environ.get('USER') == 'apache':
  90. return True
  91. else:
  92. return (not os.environ.get('USER'))
  93. # os.environ does not have user, so allows a security vulnerability,fixed now.
  94. def get_index_path():
  95. import os
  96. return os.sep.join(os.path.dirname(os.path.abspath(__file__)).split(os.sep)[:-2])
  97. def get_files_path():
  98. global conn
  99. import defs, os
  100. if not conn:
  101. raise Exception, 'You must login first'
  102. if defs.files_path:
  103. return os.path.join(defs.files_path, conn.cur_db_name)
  104. else:
  105. return os.path.join(get_index_path(), 'user_files', conn.cur_db_name)
  106. def create_folder(path):
  107. """
  108. Wrapper function for os.makedirs (does not throw exception if directory exists)
  109. """
  110. import os
  111. try:
  112. os.makedirs(path)
  113. except Exception, e:
  114. if e.args[0]==17:
  115. pass
  116. else:
  117. raise e
  118. def connect(db_name):
  119. """
  120. Connect to this db (or db), if called from command prompt
  121. """
  122. if is_apache_user():
  123. raise Exception, 'Not for web users!'
  124. import webnotes.db
  125. global conn
  126. conn = webnotes.db.Database(db_name=db_name)
  127. global session
  128. session = {'user':'Administrator'}
  129. import webnotes.profile
  130. global user
  131. user = webnotes.profile.Profile('Administrator')
  132. # Environment Variables
  133. #-----------------------------------------------------------
  134. def get_env_vars(env_var):
  135. return os.environ.get(env_var,'None')
  136. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  137. # Logging
  138. # -----------------------------------------------------------
  139. logger = None
  140. def setup_logging():
  141. import logging
  142. import logging.handlers
  143. # Also please set umask for apache to 002.
  144. global logger
  145. try:
  146. logger = logging.getLogger('WNLogger')
  147. logger.setLevel(eval(defs.log_level))
  148. log_handler = logging.handlers.RotatingFileHandler(defs.log_file_name, maxBytes = defs.log_file_size, backupCount = defs.log_file_backup_count)
  149. formatter = logging.Formatter('%(name)s - %(asctime)s - %(levelname)s\n%(message)s\n-------------------')
  150. log_handler.setFormatter(formatter)
  151. logger.addHandler(log_handler)
  152. except IOError,e:
  153. if e.args == 13:
  154. open(defs.log_file_name).close()
  155. if getattr(defs, 'log_file_name', None):
  156. setup_logging()
  157. def get_db_password(db_name):
  158. from webnotes import defs
  159. if hasattr(defs, 'get_db_password'):
  160. return defs.get_db_password(db_name)
  161. elif hasattr(defs, 'db_password'):
  162. return defs.db_password
  163. else:
  164. return db_name