25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

228 satır
6.4 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe
  5. from frappe import _
  6. import frappe.utils
  7. import frappe.sessions
  8. import frappe.desk.form.run_method
  9. from frappe.utils.response import build_response
  10. from frappe.api import validate_auth
  11. from frappe.utils import cint
  12. from frappe.core.doctype.server_script.server_script_utils import run_server_script_api
  13. from werkzeug.wrappers import Response
  14. from six import string_types
  15. ALLOWED_MIMETYPES = ('image/png', 'image/jpeg', 'application/pdf', 'application/msword',
  16. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  17. 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  18. 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet')
  19. def handle():
  20. """handle request"""
  21. validate_auth()
  22. cmd = frappe.local.form_dict.cmd
  23. data = None
  24. if cmd!='login':
  25. data = execute_cmd(cmd)
  26. # data can be an empty string or list which are valid responses
  27. if data is not None:
  28. if isinstance(data, Response):
  29. # method returns a response object, pass it on
  30. return data
  31. # add the response to `message` label
  32. frappe.response['message'] = data
  33. return build_response("json")
  34. def execute_cmd(cmd, from_async=False):
  35. """execute a request as python module"""
  36. for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
  37. # override using the first hook
  38. cmd = hook
  39. break
  40. # via server script
  41. if run_server_script_api(cmd):
  42. return None
  43. try:
  44. method = get_attr(cmd)
  45. except Exception as e:
  46. if frappe.local.conf.developer_mode:
  47. raise e
  48. else:
  49. frappe.respond_as_web_page(title='Invalid Method', html='Method not found',
  50. indicator_color='red', http_status_code=404)
  51. return
  52. if from_async:
  53. method = method.queue
  54. is_whitelisted(method)
  55. is_valid_http_method(method)
  56. return frappe.call(method, **frappe.form_dict)
  57. def is_valid_http_method(method):
  58. http_method = frappe.local.request.method
  59. if http_method not in frappe.allowed_http_methods_for_whitelisted_func[method]:
  60. frappe.throw(_("Not permitted"), frappe.PermissionError)
  61. def is_whitelisted(method):
  62. # check if whitelisted
  63. if frappe.session['user'] == 'Guest':
  64. if (method not in frappe.guest_methods):
  65. frappe.throw(_("Not permitted"), frappe.PermissionError)
  66. if method not in frappe.xss_safe_methods:
  67. # strictly sanitize form_dict
  68. # escapes html characters like <> except for predefined tags like a, b, ul etc.
  69. for key, value in frappe.form_dict.items():
  70. if isinstance(value, string_types):
  71. frappe.form_dict[key] = frappe.utils.sanitize_html(value)
  72. else:
  73. if not method in frappe.whitelisted:
  74. frappe.throw(_("Not permitted"), frappe.PermissionError)
  75. @frappe.whitelist(allow_guest=True)
  76. def version():
  77. return frappe.__version__
  78. @frappe.whitelist()
  79. def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
  80. frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
  81. @frappe.whitelist(allow_guest=True)
  82. def logout():
  83. frappe.local.login_manager.logout()
  84. frappe.db.commit()
  85. @frappe.whitelist(allow_guest=True)
  86. def web_logout():
  87. frappe.local.login_manager.logout()
  88. frappe.db.commit()
  89. frappe.respond_as_web_page(_("Logged Out"), _("You have been successfully logged out"),
  90. indicator_color='green')
  91. @frappe.whitelist(allow_guest=True)
  92. def run_custom_method(doctype, name, custom_method):
  93. """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}"""
  94. doc = frappe.get_doc(doctype, name)
  95. if getattr(doc, custom_method, frappe._dict()).is_whitelisted:
  96. frappe.call(getattr(doc, custom_method), **frappe.local.form_dict)
  97. else:
  98. frappe.throw(_("Not permitted"), frappe.PermissionError)
  99. @frappe.whitelist()
  100. def uploadfile():
  101. ret = None
  102. try:
  103. if frappe.form_dict.get('from_form'):
  104. try:
  105. ret = frappe.get_doc({
  106. "doctype": "File",
  107. "attached_to_name": frappe.form_dict.docname,
  108. "attached_to_doctype": frappe.form_dict.doctype,
  109. "attached_to_field": frappe.form_dict.docfield,
  110. "file_url": frappe.form_dict.file_url,
  111. "file_name": frappe.form_dict.filename,
  112. "is_private": frappe.utils.cint(frappe.form_dict.is_private),
  113. "content": frappe.form_dict.filedata,
  114. "decode": True
  115. })
  116. ret.save()
  117. except frappe.DuplicateEntryError:
  118. # ignore pass
  119. ret = None
  120. frappe.db.rollback()
  121. else:
  122. if frappe.form_dict.get('method'):
  123. method = frappe.get_attr(frappe.form_dict.method)
  124. is_whitelisted(method)
  125. ret = method()
  126. except Exception:
  127. frappe.errprint(frappe.utils.get_traceback())
  128. frappe.response['http_status_code'] = 500
  129. ret = None
  130. return ret
  131. @frappe.whitelist(allow_guest=True)
  132. def upload_file():
  133. user = None
  134. if frappe.session.user == 'Guest':
  135. if frappe.get_system_settings('allow_guests_to_upload_files'):
  136. ignore_permissions = True
  137. else:
  138. return
  139. else:
  140. user = frappe.get_doc("User", frappe.session.user)
  141. ignore_permissions = False
  142. files = frappe.request.files
  143. is_private = frappe.form_dict.is_private
  144. doctype = frappe.form_dict.doctype
  145. docname = frappe.form_dict.docname
  146. fieldname = frappe.form_dict.fieldname
  147. file_url = frappe.form_dict.file_url
  148. folder = frappe.form_dict.folder or 'Home'
  149. method = frappe.form_dict.method
  150. content = None
  151. filename = None
  152. if 'file' in files:
  153. file = files['file']
  154. content = file.stream.read()
  155. filename = file.filename
  156. frappe.local.uploaded_file = content
  157. frappe.local.uploaded_filename = filename
  158. if frappe.session.user == 'Guest' or (user and not user.has_desk_access()):
  159. import mimetypes
  160. filetype = mimetypes.guess_type(filename)[0]
  161. if filetype not in ALLOWED_MIMETYPES:
  162. frappe.throw(_("You can only upload JPG, PNG, PDF, or Microsoft documents."))
  163. if method:
  164. method = frappe.get_attr(method)
  165. is_whitelisted(method)
  166. return method()
  167. else:
  168. ret = frappe.get_doc({
  169. "doctype": "File",
  170. "attached_to_doctype": doctype,
  171. "attached_to_name": docname,
  172. "attached_to_field": fieldname,
  173. "folder": folder,
  174. "file_name": filename,
  175. "file_url": file_url,
  176. "is_private": cint(is_private),
  177. "content": content
  178. })
  179. ret.save(ignore_permissions=ignore_permissions)
  180. return ret
  181. def get_attr(cmd):
  182. """get method object from cmd"""
  183. if '.' in cmd:
  184. method = frappe.get_attr(cmd)
  185. else:
  186. method = globals()[cmd]
  187. frappe.log("method:" + cmd)
  188. return method
  189. @frappe.whitelist(allow_guest = True)
  190. def ping():
  191. return "pong"