Beispiel #1
0
 def debugError(self, entry):
     self.setStatus(404)
     exc = NotFound(entry)
     exc.title = 'Debugging Notice'
     exc.detail = ("Zope has encountered a problem publishing your object. "
                   "<p>%s</p>" % repr(entry))
     raise exc
Beispiel #2
0
    def __call__(self):
        if self.request.method != "POST":
            raise NotFound(self, "library-insert", self.request)
        path = self.request.form.get("path")
        if not path:
            raise NotFound(self, "library-insert",
                           self.request)  # XXX Wrong exception type
        target = aq_inner(self.context)
        app = target.getPhysicalRoot()
        source = app.restrictedTraverse(path)
        if not is_allowed(target, source):
            raise NotFound(self, "library-insert",
                           self.request)  # XXX Wrong exception type
        copy = source._getCopy(target)
        assign_ids(target, copy)
        notify(ObjectCopiedEvent(copy, source))
        target._setObject(copy.id, copy)
        copy = target[copy.id]
        copy._postCopy(target, op=0)
        notify(ObjectClonedEvent(copy))

        api.portal.show_message(
            _(
                'Added a copy of "${title}" to your OiRA tool.',
                mapping={"title": copy.title},
            ),
            request=self.request,
            type="success",
        )
        self.request.RESPONSE.redirect(copy.absolute_url())
Beispiel #3
0
 def debugError(self, entry):
     self.setStatus(404)
     exc = NotFound(entry)
     exc.title = 'Debugging Notice'
     exc.detail = (
         'Zope has encountered a problem publishing your object.<p>'
         '\n%s</p>' % entry)
     raise exc
Beispiel #4
0
 def notFoundError(self, entry='Unknown'):
     self.setStatus(404)
     exc = NotFound(entry)
     exc.title = 'Resource not found'
     exc.detail = ('Sorry, the requested resource does not exist.'
                   '<p>Check the URL and try again.</p>'
                   '<p><b>Resource:</b> %s</p>' % escape(entry, True))
     raise exc
Beispiel #5
0
 def notFoundError(self, entry='Unknown'):
     self.setStatus(404)
     exc = NotFound(entry)
     exc.title = 'Resource not found'
     exc.detail = (
         'Sorry, the requested resource does not exist.'
         '<p>Check the URL and try again.</p>'
         '<p><b>Resource:</b> %s</p>' % escape(entry, True))
     raise exc
Beispiel #6
0
def getObject(
    module,
    name,
    reload=0,
    # The use of a mutable default is intentional here,
    # because modules is a module cache.
    modules={}):
    # The use of modules here is not thread safe, however, there is
    # no real harm in a race condition here.  If two threads
    # update the cache, then one will have simply worked a little
    # harder than need be.  So, in this case, we won't incur
    # the expense of a lock.
    old = modules.get(module)
    if old is not None and name in old and not reload:
        return old[name]

    base, ext = os.path.splitext(module)
    if ext in ('py', 'pyc'):
        # XXX should never happen; splitext() keeps '.' with the extension
        prefix = base
    else:
        prefix = module

    path = getPath('Extensions', prefix, suffixes=('', 'py', 'pyc'))
    if path is None:
        raise NotFound("The specified module, '%s', couldn't be found." %
                       module)

    __traceback_info__ = path, module

    base, ext = os.path.splitext(path)
    if ext == '.pyc':
        file = open(path, 'rb')
        binmod = imp.load_compiled('Extension', path, file)
        file.close()
        module_dict = binmod.__dict__
    else:
        try:
            execsrc = open(path)
        except:
            raise NotFound("The specified module, '%s', "
                           "couldn't be opened." % module)
        module_dict = {}
        exec execsrc in module_dict

    if old is not None:
        # XXX Accretive??
        old.update(module_dict)
    else:
        modules[module] = module_dict

    try:
        return module_dict[name]
    except KeyError:
        raise NotFound("The specified object, '%s', was not found "
                       "in module, '%s'." % (name, module))
Beispiel #7
0
    def _get_and_check_month_and_year(self, month, year):
        if month is None:
            month = DateTime().strftime('%B')
            year = DateTime().year()

        if month not in MONTH_NAMES:
            raise NotFound("Unrecognized month name")
        try:
            year = int(year)
        except ValueError:
            raise NotFound("Unrecognized year number")

        return month, year
Beispiel #8
0
 def publishTraverse(self, request, name):
     if self.example_name:
         view = ExampleResponseView(self.context, self.request)
         view.routes = dict()
         for part in self.example:
             routes = part.get('routes', [])
             if name in routes:
                 view.route = routes[name]
                 return view
         raise NotFound()
     if name not in self.example_names:
         raise NotFound()
     self._example_name = name
     return self
Beispiel #9
0
def resolveResource(url):
    """Resolve the given URL to a unicode string. If the URL is an absolute
    path, it will be made relative to the Plone site root.
    """
    if url.startswith('/'):
        site = getSite()
        url = '/'.join(site.getPhysicalPath()) + url

    response = subrequest(url)
    if response.status == 404:
        raise NotFound(url)

    resolved = response.getBody()

    if isinstance(resolved, str):
        charset = extractCharset(response)
        resolved = resolved.decode(charset)

    if response.status in (301, 302):
        site = getSite()
        location = response.headers.get('location') or ''
        if location.startswith(site.absolute_url()):
            return resolveResource(location[len(site.absolute_url()):])

    elif response.status != 200:
        raise RuntimeError(resolved)

    return resolved
Beispiel #10
0
    def publishTraverse(self, request, name):
        """You can traverse to a method called the same way that the
        HTTP method name, or a sub view
        """
        overriden_method = request.getHeader('X-HTTP-Method-Override', None)
        is_valid_overriden_method = overriden_method in ['DELETE', 'PUT']
        is_POST_request = request.method.upper() == 'POST'
        is_valid_override = is_valid_overriden_method and is_POST_request
        request_method = overriden_method if is_valid_override else request.method

        if request_method != request.method:
            request.method = request_method

        if name in ALLOWED_REST_METHODS and name == request.method:
            if hasattr(self, request_method):
                notify(RESTMethodPublishedEvent(self, name))
                return getattr(self, request_method)

        view = queryRESTComponent((self, self.context),
                                  (self.context, request),
                                  name=name,
                                  parent=self)

        placeholder = getattr(self, 'placeholder_type', None)

        if view is None and placeholder is not None:
            placeholder_id = getattr(self, 'placeholder_id')
            view = queryRESTComponent((self, self.context),
                                      (self.context, request),
                                      name=placeholder,
                                      parent=self,
                                      placeholder={placeholder_id: name})
        if view is None:
            raise NotFound(name)
        return view
Beispiel #11
0
    def publishTraverse(self, request, name):

        if self.layout is None:
            self.layout = name
            return self
        else:
            raise NotFound()
    def __call__(self, REQUEST):
        taxonomies = REQUEST.get('taxonomies')
        if not bool(taxonomies):
            raise NotFound()

        stream = BytesIO()
        z_file = zipfile.ZipFile(
            stream, "w", zipfile.ZIP_DEFLATED, True)
        sm = self.context.getSiteManager()
        adapter = TaxonomyImportExportAdapter(self.context)

        for taxonomy in taxonomies.split(","):
            utility = sm.queryUtility(ITaxonomy, name=taxonomy)
            if utility is None:
                continue
            result = adapter.exportDocument(utility)
            z_file.writestr("%s.xml" % taxonomy, result)

        z_file.close()
        self.request.RESPONSE.setHeader(
            'Content-type', 'application/x-zip-compressed')
        self.request.RESPONSE.setHeader(
            'Content-disposition',
            'attachment; filename="taxonomy_export.zip"')
        return stream.getvalue()
Beispiel #13
0
 def __call__(self):
     viewlet = self.setupViewletByName(
         'plone.belowcontentbody.relateditems')
     if viewlet is None:
         raise NotFound(
             "Viewlet does not exist by name %s for theme layer %s" % name)
     return viewlet.related_items()
Beispiel #14
0
    def __call__(self):
        referrer = self.request.environ.get('HTTP_REFERER')
        if referrer:
            parsed = urlparse(referrer)
            obj = self.context.restrictedTraverse(parsed.path, None)
            if obj is not None:
                self.context = obj
                portal = getToolByName(obj, 'portal_url').getPortalObject()
                setSite(portal)

        url = None
        catalog = api.portal.get_tool('portal_catalog')
        res = catalog.unrestrictedSearchResults(UID=self.uuid, trashed=False)
        if res:
            url = res[0].getURL()

        if not url:
            raise NotFound("The link you followed is broken")

        if self.subpath:
            url = '/'.join([url] + self.subpath)

        if self.request.QUERY_STRING:
            url += '?' + self.request.QUERY_STRING

        self.request.response.redirect(url, status=301)

        return ''
Beispiel #15
0
    def update(self):
        if not self.context.allow_feeds():
            raise NotFound()

        entries = []
        service_metadata = component.getUtility(IMetadataService)
        metadata = service_metadata.getMetadata(self.context)
        date_updated = metadata.get('silva-extra', 'creationtime')

        provider = component.getMultiAdapter(
            (self.context.aq_inner, self.request),
            interfaces.IFeedEntryProvider)
        for entry in provider.entries():
            entry_updated = entry.date_published()
            entries.append((entry_updated.asdatetime(), entry))

        entries.sort(key=lambda x: x[0], reverse=True)
        feed = [entry[1] for entry in entries]

        if len(feed) > 0:
            last_published = feed[0].date_published()
            if last_published > date_updated:
                date_updated = last_published

        self.data = {
            'title': self.context.get_title(),
            'description': metadata.get('silva-extra', 'content_description'),
            'url': absoluteURL(self.context, self.request),
            'authors': [self.context.get_creator_info().fullname()],
            'date_updated': date_updated,
            'entries': feed
        }

        self.response.setHeader('Content-Type', 'text/xml;charset=UTF-8')
Beispiel #16
0
 def debugError(self, entry):
     raise NotFound(self._error_html(
         "Debugging Notice",
         "Zope has encountered a problem publishing your object.<p>"
         "\n" +
         entry +
         "</p>"))
    def __call__(self):
        if not self.is_allowed():
            raise NotFound()

        self.settings = OrderedDict((
            ("KeepConnector", "true"),
            ("CreateConnectorResult", "true"),
            ("CreateConnectorResultOnError", "true"),
        ))

        self.commands = OrderedDict((
            ("DefaultProcess", (("start", "false"), )),
            ("ConvertToDocument", tuple()),
            ("SaveAs", (
                ("Overwrite", "true"),
                ("CreateFolder", "true"),
                ("AllowUpdateDocumentPart", "false"),
                ("Filename", ""),
            )),
            ("InvokeProcess", (
                ("Name", "OfficeConnector"),
                ("Arguments", create_oc_url(self.request, self.context, {"action": "checkout"})),
            )),
        ))

        self.document_properties = getMultiAdapter((self.context, self.request), IDocProperties).get_properties()

        self.request.RESPONSE.setHeader("Content-type", "application/xml")
        return self.generate_xml()
Beispiel #18
0
 def notFoundError(self, entry='Unknown'):
     self.setStatus(404)
     raise NotFound(self._error_html(
         "Resource not found",
         ("Sorry, the requested resource does not exist."
          "<p>Check the URL and try again.</p>"
          "<p><b>Resource:</b> " + escape(entry) + "</p>")))
    def getObjectPosition(self, id):
        try:
            pos = OrderSupport.getObjectPosition(self, id)
        except ValueError:
            raise NotFound('Object %s was not found' % str(id))

        return pos
Beispiel #20
0
 def __call__(self):
     """ Redirect to prenotazioni or raise not found
     """
     target_url = self.get_target_url()
     if not target_url:
         raise NotFound("Can't find a PrenotazioniFolder container")
     return self.request.response.redirect(target_url)
Beispiel #21
0
def dummyUnrestrictedTraverse(self, path):
    if path == (
            '',
            'lexicon',
    ):
        return self.lexicon
    raise NotFound(path)
Beispiel #22
0
 def render(self):
     if not self.enabled():
         raise NotFound()
     if self.import_successful:
         IStatusMessage(self.request).addStatusMessage(
             _(u"Message has been imported"), type='info')
         self.request.response.redirect(self.context.absolute_url())
     return super(ECH0147ImportForm, self).render()
Beispiel #23
0
def verify_token(context, request):
    if not context.state == 'preview':
        return

    token_access = getAdapter(context, ITokenAccess)

    if not token_access.has_access(request):
        raise NotFound()
Beispiel #24
0
 def debugError(self, entry):
     raise NotFound(self._error_html(
         "Debugging Notice",
         (
             "Zope has encountered a problem publishing your object. "
             "<p>%s</p>" % repr(entry)
         )
     ))
Beispiel #25
0
 def __getitem__(self, name):
     """Allow travering intoviewlets by viewlet name.
     """
     viewlet = self.setupViewletByName(name)
     if viewlet is None:
         raise NotFound("Viewlet {} not found".format(name))
     viewlet.update()
     return viewlet.render()
Beispiel #26
0
 def __call__(self):
     userid = self.request.form.get('userid')
     if userid:
         mt = getToolByName(self.context, 'portal_membership')
         if mt.getMemberById(userid) is None:
             raise NotFound('User does not exist.')
     self.request.set('disable_border', 1)
     return super(UserDataPanel, self).__call__()
Beispiel #27
0
    def generic_query(self,
                      script_path='all-documents',
                      output_format='json',
                      deserialize_json=False,
                      **kw):
        """ Public query API for calling xquery scripts through RESTXQ.
            The related xquery script must expose is functionality through
            http://host:port/exist/restxq/<script_path>.<output_format>.
            The result is then returned as text (html, xml) or deserialized
            JSON data structure.
            Note that <script_path> must start with '/db/' or 'db/'.
        """

        if self.context and not self.context.api_enabled:
            raise Forbidden('API not enabled')

        if output_format not in ('json', 'xml', 'html'):
            raise NotFound(
                'Unsupported output format "{}"'.format(output_format))

        registry = getUtility(IRegistry)
        settings = registry.forInterface(IConnectorSettings)
        pr = urlparse.urlparse(settings.connector_url)
        url = '{}://{}/exist/restxq/{}.{}'.format(pr.scheme, pr.netloc,
                                                  script_path, output_format)

        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(max_retries=3)
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        result = session.get(url,
                             auth=HTTPBasicAuth(
                                 settings.connector_username,
                                 settings.connector_password or ''),
                             params=kw)
        if result.status_code != 200:
            raise APIError(
                'eXist-db return an response with HTTP code {} for {}'.format(
                    result.status_code, url))

        if output_format == 'json':
            data = result.json()
            if deserialize_json:
                # called internally (and not through the web)
                data = result.json()
                return data
            else:
                data = result.text
                self.request.response.setHeader('content-type',
                                                'application/json')
                self.request.response.setHeader('content-length', len(data))
                return data
        else:
            data = result.text
            self.request.response.setHeader('content-type',
                                            'text/{}'.format(output_format))
            self.request.response.setHeader('content-length', len(data))
            return data
Beispiel #28
0
 def getObject(self):
     if self.id == 'missing':
         if self.ob.GETOBJECT_RAISES:
             raise NotFound("missing")
         else:
             return None
     if self.id == 'hop':
         raise ValueError("security problem for this object")
     return self.ob
Beispiel #29
0
    def publishTraverse(self, request, name):

        #         import pdb
        #         pdb.set_trace()
        if self.layout is None:
            self.layout = name
            return self
        else:
            raise NotFound()
 def update(self):
     applySkin(self.request, IPrintSkin)
     self.html = None
     view = queryMultiAdapter(
         (self.context, self.request), name='content.html')
     if view is None:
         raise NotFound('content.html')
     if IView.providedBy(view) and view.content is not None:
         self.html = view()
Beispiel #31
0
    def traverse(self, name, remaining):
        portal_type = getattr(self.context, 'portal_type', None)
        if not portal_type:
            raise NotFound(self.context, name, self.request)

        types_tool = getToolByName(self.context, 'portal_types')
        fti = getattr(types_tool, portal_type, None)
        if fti is None:
            raise NotFound(self.context, name, self.request)

        aliases = fti.getMethodAliases() or {}
        layout = '++layout++{0:s}'.format(name)
        resource_path = aliases.get(layout)

        if resource_path is None:
            raise NotFound(self.context, name, self.request)
        else:
            return ContentLayoutView(self.context, self.request, resource_path)
Beispiel #32
0
 def publishTraverse(self, request, name):
     """ This method is called if someone appends the shortcode to the end
         of the url. To prevent the silliness of multiple parts being
         appended, we raise NotFound if we already have one. """
     if self.traversecode is None:
         self.traversecode = name
     else:
         raise NotFound(name)
     return self