def action(self, type_name='', id=''): if not type_name: raise UserError(_(u"You must select the type of object to add.")) if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if queryMultiAdapter((self, self.request), name=view_name) is not None: url = "%s/%s=%s" % (absoluteURL(self, self.request), type_name, id) raise Redirect(url) if not self.contentName: self.contentName = id factory = getUtility(IFactory, type_name) content = factory() notify(ObjectCreatedEvent(content)) self.add(content) raise Redirect(self.nextURL())
def redirect(self, location, status=302, lock=0): """Cause a redirection.""" if isinstance(location, HTTPRedirection): raise location exc = Redirect(str(location)) exc.setStatus(status) raise exc
def protect(req, recheck=False): url = req.getURL() login_url = '{}/@@secure-login'.format(api.portal.get().absolute_url()) if '@@secure-login' in url.lower() and url != login_url: raise Redirect(login_url) published = req.PARENTS[0] mt = getattr(getattr(published, 'aq_base', None), 'meta_type', getattr(published, 'meta_type', None)) if mt in _blacklisted_meta_types or mt is None: return published = req.get('PUBLISHED') if ISecureLoginAllowedView.providedBy(published): return registry = queryUtility(IRegistry) setting = (registry and registry.get('plone.login_shield_setting', SHIELD.NONE) or SHIELD.NONE) protect = False if setting == SHIELD.ALL: protect = True elif setting == SHIELD.BACKEND: backend_urls = (registry and registry.get('plone.backend_url', SHIELD.NONE) or []) for backend_url in backend_urls or []: try: protect |= backend_url.startswith(req.SERVER_URL) except AttributeError: pass if protect: if req.getURL().lower().endswith("robots.txt"): return """User-agent: * Disallow: /""" if recheck: portal = api.portal.get() site_plugin = portal.acl_users.session creds = site_plugin.extractCredentials(req) anonymous = not site_plugin.authenticateCredentials(creds) if anonymous: try: app_plugin = aq_parent(portal).acl_users.session anonymous = not app_plugin.authenticateCredentials(creds) except AttributeError: anonymous = True else: anonymous = api.user.is_anonymous() if anonymous: raise Redirect(login_url)
def manage_addPageTemplate(self, id, title='', text='', encoding='utf-8', submit=None, REQUEST=None, RESPONSE=None): "Add a Page Template with optional file content." filename = '' content_type = 'text/html' if REQUEST and 'file' in REQUEST: file = REQUEST['file'] filename = file.filename text = file.read() headers = getattr(file, 'headers', None) if headers and 'content_type' in headers: content_type = headers['content_type'] else: content_type = guess_type(filename, text) else: if hasattr(text, 'read'): filename = getattr(text, 'filename', '') headers = getattr(text, 'headers', None) text = text.read() if headers and 'content_type' in headers: content_type = headers['content_type'] else: content_type = guess_type(filename, text) # ensure that we pass unicode to the constructor to # avoid further hassles with pt_edit() if not isinstance(text, unicode): text = unicode(text, encoding) zpt = ZopePageTemplate(id, text, content_type, output_encoding=encoding) zpt.pt_setTitle(title, encoding) self._setObject(id, zpt) zpt = getattr(self, id) if RESPONSE: if submit == " Add and Edit ": raise Redirect(zpt.absolute_url() + '/pt_editForm') else: raise Redirect(self.absolute_url() + '/manage_main') else: return zpt
def protect(req): published = req.PARENTS[0] mt = getattr( getattr(published, 'aq_base', None), 'meta_type', getattr(published, 'meta_type', None)) if mt in _blacklisted_meta_types or mt is None: return published = req.get('PUBLISHED') if ISecureLoginAllowedView.providedBy(published): return registry = queryUtility(IRegistry) setting = (registry and registry.get('plone.login_shield_setting', SHIELD.NONE) or SHIELD.NONE) protect = False if setting == SHIELD.ALL: protect = True elif setting == SHIELD.BACKEND: backend_url = (registry and registry.get('plone.backend_url', SHIELD.NONE) or '') if backend_url.startswith(req.SERVER_URL): protect = True if protect and api.user.is_anonymous(): raise Redirect('{}/@@secure-login'.format( api.portal.get().absolute_url()))
class OmnikassaPay(BrowserView): def __call__(self): base_url = self.context.absolute_url() order_uid = self.request.get('uid', '') payment_method = self.request.get('payment_method', '') try: site_url = api.portal.get().absolute_url() data = IPaymentData(self.context).data(order_uid) secretKey = SECRET_KEY merchantID = MERCHANT_ID keyVersion = KEYVERSION currencyCode = 978 amount = data['amount'] transactionReference = data['ordernumber'] orderId = data['ordernumber'] normalReturnUrl = "%s/@@omnikassa_payment" %(base_url) automaticResponseUrl = "%s/@@omnikassa_webhook" %(site_url) redirect_url = create_pay_init(secretKey, merchantID, keyVersion, currencyCode, amount, transactionReference, orderId, normalReturnUrl, automaticResponseUrl) print "REDIRECT URL:" print redirect_url except Exception, e: logger.error(u"Could not initialize payment: '%s'" % str(e)) redirect_url = '%s/@@omnikassa_payment_failed?uid=%s' \ % (base_url, order_uid) raise Redirect(redirect_url)
class SaferPay(BrowserView): def __call__(self): base_url = self.context.absolute_url() order_uid = self.request['uid'] try: data = IPaymentData(self.context).data(order_uid) accountid = ACCOUNTID password = PASSWORD vtconfig = VTCONFIG amount = data['amount'] currency = data['currency'] description = data['description'] ordernumber = data['ordernumber'] successlink = '%s/@@six_payment_success' % base_url faillink = '%s/@@six_payment_failed?uid=%s' \ % (base_url, order_uid) backlink = '%s/@@six_payment_aborted?uid=%s' \ % (base_url, order_uid) redirect_url = create_pay_init(accountid, password, vtconfig, amount, currency, description, ordernumber, successlink, faillink, backlink) except Exception, e: logger.error(u"Could not initialize payment: '%s'" % str(e)) redirect_url = '%s/@@six_payment_failed?uid=%s' \ % (base_url, order_uid) raise Redirect(redirect_url)
def sync(self): redirect_url = self.context.absolute_url() messages = IStatusMessage(self.request) # Get API settings from the controlpanel api_settings = get_api_settings() # Create the API connection api_connection = APIConnection(api_settings) # Create the settings for the sync # Initiate the sync manager sync_options = {"api": api_connection, 'core': SYNC_CORE} sync_manager = SyncManager(sync_options) dateFrom = get_datetime_today(as_string=True) dateUntil = get_datetime_future(as_string=True) try: logger("[Status] Start syncing performance list.") performance_list = sync_manager.update_performance_list_by_date( date_from=dateFrom, date_until=dateUntil, create_and_unpublish=True) logger("[Status] Syncing performance list finished.") messages.add(u"Performance list is now synced.", type=u"info") except Exception as err: logger( "[Error] Error while requesting the sync for the performance list.", err) messages.add( u"Performance list failed to sync with the api. Please contact the website administrator.", type=u"error") raise Redirect(redirect_url)
def queue_sync(self): redirect_url = self.context.absolute_url() QUEUE_LIMIT = 1 QUEUE_VIEW = "sync_person" queue_view_path = self.context.getPhysicalPath() queue_size = len(getUtility(ITaskQueue, name='sync')) queue_view_path_url = "/".join(queue_view_path) queue_view_url = "%s/%s" % (queue_view_path_url, QUEUE_VIEW) print("URL: %s" % (queue_view_url)) print("Queue size: %s" % (queue_size)) messages = IStatusMessage(self.request) if queue_size < QUEUE_LIMIT: sync_id = taskqueue.add(url=queue_view_url, queue="sync") print("Run sync with ID: '%s'" % (sync_id)) messages.add(u"Sync ID '%s' is now triggered." % (sync_id), type=u"info") else: messages.add( u"There is one sync currently running. Try again later.", type=u"warning") raise Redirect(redirect_url)
def put_in_place(self): # Redirect a ServiceDescription to its "place". if not ILOSCategory.providedBy(aq_parent(self)): url = self.inplace_url() if url != self.absolute_url(): raise Redirect(url) return ''
class OgonePay(BrowserView): def __call__(self): base_url = self.context.absolute_url() order_uid = self.request['uid'] try: data = IPaymentData(self.context).data(order_uid) pspid = PSPID language = self.getLanguage() currency = data['currency'] amount = data['amount'] description = data['description'] ordernumber = data['ordernumber'] accepturl = "http://plone5.intk.com/Plone/ogone_payment_success" declineurl = '%s/@@ogone_payment_failed?uid=%s' % (base_url, order_uid) exceptionurl = '%s/@@ogone_payment_failed?uid=%s' % (base_url, order_uid) cancelurl = '%s/@@ogone_payment_aborted?uid=%s' % (base_url, order_uid) redirect_url = create_pay_init(pspid, ordernumber, currency, amount, language, accepturl, declineurl, exceptionurl, cancelurl) except Exception, e: logger.error(u"Could not initialize payment: '%s'" % str(e)) redirect_url = '%s/@@ogone_payment_failed?uid=%s' \ % (base_url, order_uid) raise Redirect(redirect_url)
def group_deleted(event): """ Raises exception if group cannot be deleted """ group = event.principal portal = api.portal.get() request = portal.REQUEST parts = group.split('_') if len(parts) == 1: return org_uid = parts[0] group_suffix = '_'.join(parts[1:]) if org_uid in get_registry_organizations( ) and group_suffix in get_all_suffixes(org_uid): orga = api.content.find(UID=org_uid)[0].getObject() api.portal.show_message(message=_( "You cannot delete the group '${group}', linked to used organization " "'${orga}'.", mapping={ 'group': group, 'orga': safe_unicode(orga.Title()) }), request=request, type='error') raise Redirect(request.get('ACTUAL_URL'))
def sync(self): redirect_url = self.context.absolute_url() messages = IStatusMessage(self.request) try: # Get API settings from the controlpanel api_settings = get_api_settings() # Create the API connection api_connection = APIConnectionOrganizations(api_settings) # Create the settings for the sync # Initiate the sync manager sync_options = { "api": api_connection, 'core': SYNC_CORE_ORGANIZATIONS } sync_manager = SyncManagerOrganizations(sync_options) # Trigger the sync to update one organization logger("[Status] Start update of all organization.") person_data = sync_manager.update_organizations( create_and_unpublish=True) logger("[Status] Finished update of all organization.") except Exception as err: logger( "[Error] Error while requesting the sync for all organizations", err) messages.add( u"Sync of all organizations ID failed. Please contact the website administrator.", type=u"error") # Redirect to the original page raise Redirect(redirect_url)
def manage_minimize(self, value=1, REQUEST=None): "Perform a full sweep through the cache" # XXX Add a deprecation warning about value? self._getDB().cacheMinimize() if REQUEST is not None: raise Redirect(REQUEST['URL1'] + '/manage_main')
def user_deleted(event): """ Raises exception if user cannot be deleted """ princ = event.principal portal = api.portal.get() request = portal.REQUEST # is protected user if princ in ('scanner',): api.portal.show_message(message=_("You cannot delete the user name '${user}'.", mapping={'user': princ}), request=request, type='error') raise Redirect(request.get('ACTUAL_URL')) # check groups pg = portal.acl_users.source_groups._principal_groups groups = pg.get(princ, []) if groups: api.portal.show_message(message=_("You cannot delete the user name '${user}', used in following groups.", mapping={'user': princ}), request=request, type='error') titles = [] for groupid in groups: grp = api.group.get(groupname=groupid) titles.append('"%s"' % (grp and safe_unicode(grp.getProperty('title')) or groupid)) api.portal.show_message(message=_('<a href="${url}" target="_blank">Linked groups</a> : ${list}', mapping={'list': ', '.join(titles), 'url': '%s/@@usergroup-usermembership?' 'userid=%s' % (portal.absolute_url(), princ)}), request=request, type='error') raise Redirect(request.get('ACTUAL_URL')) # search in assigned_user index for (idx, domain, criterias) in (('assigned_user', 'collective.eeafaceted.z3ctable', {}), ('Creator', 'plone', {}), ('mail_type', 'collective.eeafaceted.z3ctable', {'object_provides': IPersonnelContact.__identifier__})): criterias.update({idx: princ}) brains = portal.portal_catalog.unrestrictedSearchResults(**criterias) if brains: msg = _("You cannot delete the user name '${user}', used in '${idx}' index.", mapping={'user': princ, 'idx': translate(idx, domain=domain, context=request)}) api.portal.show_message(message=msg, request=request, type='error') logger.error(translate(msg)) msg = _("Linked objects: ${list}", mapping={'list': ', '.join(['<a href="%s" ' 'target="_blank">%s</a>' % (b.getURL(), safe_unicode(b.Title)) for b in brains])}) api.portal.show_message(message=msg, request=request, type='error') logger.error(translate(msg)) raise Redirect(request.get('ACTUAL_URL'))
def check_redirect(site, event): """ Check if we have a custom redirect script in Zope application server root. If we do then call it and see if we get a redirect. The script itself is TTW Python script which may return string in the case of redirect or None if no redirect is needed. For more examples, check http://svn.zope.org/Zope/trunk/src/Zope2/App/tests/testExceptionHook.py?rev=115555&view=markup # noqa """ request = event.request url = request["ACTUAL_URL"] parts = urlparse(url) netloc = parts.netloc.split(":") host = netloc[0] path = parts.path if len(netloc) > 1: port = int(netloc[1]) else: if parts.scheme == "https": port = 443 else: port = 80 if "no_redirect" in request.form: # Use no_redirect query parameter to disable this behavior in the case # you mess up with the redirect script return # Check if we have a redirect handler script in the site root handler = get_redirect_handler_for_site(site, request) if handler: try: # Call the script and get its output value = handler(url=url, host=host, port=port, path=path) if value is not None and value.startswith("http"): # Trigger redirect, but only if the output value looks sane raise Redirect(value) except ConflictError: # Zope 2 retry exception raise except Redirect: # Redirect exceptions are the only legal ones # from above logic raise except Exception as e: # No silent exceptions plz logger.error("Redirect exception for URL:" + url) logger.exception(e) return
def attempt_redirect(self): url = self._url() if not url: return False try: old_path_elements = self.request.physicalPathFromURL(url) except ValueError: return False storage = queryUtility(IRedirectionStorage) if storage is None: return False old_path = '/'.join(old_path_elements) # First lets try with query string in cases or content migration new_path = None query_string = self.request.QUERY_STRING if query_string: new_path = storage.get("%s?%s" % (old_path, query_string)) # if we matched on the query_string we don't want to include it # in redirect if new_path: query_string = '' if not new_path: new_path = storage.get(old_path) if not new_path: new_path = self.find_redirect_if_view(old_path_elements, storage) if not new_path: new_path = self.find_redirect_if_template( url, old_path_elements, storage) if not new_path: return False url = urllib.parse.urlsplit(new_path) if url.netloc: # External URL # avoid double quoting url_path = unquote(url.path) url_path = quote(url_path) url = urllib.parse.SplitResult( *(url[:2] + (url_path, ) + url[3:])).geturl() else: url = self.request.physicalPathToURL(new_path) # some analytics programs might use this info to track if query_string: url += "?" + query_string raise Redirect(url) return True
def ZScriptHTML_tryAction(self, REQUEST, argvars): """Apply the test parameters. """ vv = [] for argvar in argvars: if argvar.value: vv.append(f"{quote(argvar.name)}={quote(argvar.value)}") raise Redirect(f"{REQUEST['URL1']}?{'&'.join(vv)}")
def ZScriptHTML_tryAction(self, REQUEST, argvars): """Apply the test parameters. """ vv = [] for argvar in argvars: if argvar.value: vv.append("%s=%s" % (quote(argvar.name), quote(argvar.value))) raise Redirect("%s?%s" % (REQUEST['URL1'], '&'.join(vv)))
def manage_workspace(self, REQUEST): """return the workspace of the related object using its primary path""" url = REQUEST['URL'] myp = self.getPrimaryUrlPath() if url.find(myp) > 0: Tabs.manage_workspace(self, REQUEST) else: from zExceptions import Redirect raise Redirect(myp + '/manage_workspace')
def redirectUnlessMatches(self, request_value, message, target): """ Helper for use in a PFG form's "Form Setup Script" override. Checks whether a value matches the database value of a given field, and if not, redirects to a given target. """ db_value = self() if request_value != db_value: IStatusMessage(self.request).addStatusMessage(message) raise Redirect(target)
def update(self): super(EditMeetingView, self).update() if self.actions.executedActions: return if not self.is_available_for_current_user(): raise Redirect(self.context.absolute_url()) self.lock()
def update(self): url = self.request.get('enqueue') if url is not None: url = urllib.unquote_plus(url) self.tool.enqueue(url) transaction.commit() location = self.request.getURL() raise Redirect(location) url = self.request.get('remove') if url is not None: url = urllib.unquote_plus(url) self.tool.remove(url) transaction.commit() location = self.request.getURL() raise Redirect(location) super(ControlPanelEditForm, self).update()
def item_copied(obj, event): """OFS.item copying""" if get_site_root_relative_path(event.original) in ('/templates/om', '/templates/oem'): api.portal.show_message(message=_(u"You cannot copy this item '${title}' ! If you are in a table, you have to " u"use the buttons below the table.", mapping={'title': event.original.Title().decode('utf8')}), request=event.original.REQUEST, type='error') raise Redirect(event.original.REQUEST.get('HTTP_REFERER')) # we can't modify obj because it's sometimes the original object, not yet in the target directory event.original.REQUEST.set('_copying_', True)
def item_moved(obj, event): """OFS.item removed, cut or renamed (event also called for added and pasted)""" if (IObjectWillBeRemovedEvent.providedBy(event) # deletion or event.oldParent): # cut or rename if IProtectedItem.providedBy(obj) and not check_zope_admin(): api.portal.show_message( message=_(u"You cannot delete, cut or rename this item '${title}' !", mapping={'title': obj.Title().decode('utf8')}), request=obj.REQUEST, type='error') raise Redirect(obj.REQUEST.get('HTTP_REFERER'))
def manage_workspace(self, REQUEST): """if this has been called on us return our workspace if not redirect to the workspace of a related object""" id = REQUEST['URL'].split('/')[-2] if id == self.id: Tabs.manage_workspace(self, REQUEST) else: obj = self._getOb(self, id) from zExceptions import Redirect raise Redirect((obj.getPrimaryUrlPath() + '/manage_workspace'))
def manage_addVirtualHostMonster(self, id=None, REQUEST=None, **ignored): """ """ container = self.this() vhm = VirtualHostMonster() container._setObject(vhm.getId(), vhm) if REQUEST is not None: goto = '%s/manage_main' % self.absolute_url() qs = 'manage_tabs_message=Virtual+Host+Monster+added.' raise Redirect('%s?%s' % (goto, qs))
def order(self): if not self.uid: err = _( 'statusmessage_err_no_order_uid_given', default= 'Cannot show order information because no order uid was given.' # noqa ) IStatusMessage(self.request).addStatusMessage(err, 'error') raise Redirect(self.context.absolute_url()) return dict(self.order_data.order.attrs)
def test_raises_redirect(self): from zExceptions import Redirect environ = self._makeEnviron() start_response = DummyCallable() _publish = DummyCallable() _publish._raise = Redirect('/redirect_to') try: self._callFUT(environ, start_response, _publish) except Redirect as exc: self.assertEqual(exc.getStatus(), 302) self.assertEqual(exc.headers['Location'], '/redirect_to')
def manage_addUserFolder(self, dtself=None, REQUEST=None, **ignored): """ """ f = UserFolder() self = self.this() try: self._setObject('acl_users', f) except Exception: raise BadRequest('This object already contains a User Folder') self.__allow_groups__ = f if REQUEST is not None: raise Redirect(self.absolute_url() + '/manage_main')