Ejemplo n.º 1
0
    def __call__(self,
                 input,
                 surveygroup_title,
                 survey_title,
                 is_etranslate_compatible=False):
        """Import a new survey from the XML data in `input` and create a
        new survey with the given `title`.

        `input` has to be either the raw XML input, or a `lxml.objectify`
        enablde DOM.
        """
        self.is_etranslate_compatible = is_etranslate_compatible
        if isinstance(input, six.string_types + (bytes, )):
            try:
                sector = lxml.objectify.fromstring(safe_bytes(input))
            except Exception:
                # It might be that the file is huge, let's try a different approach
                parser = lxml.etree.XMLParser(huge_tree=True)
                sector_tree = lxml.objectify.parse(BytesIO(safe_bytes(input)),
                                                   parser=parser)
                sector = lxml.objectify.fromstring(
                    lxml.etree.tostring(sector_tree))
        else:
            sector = input

        root = aq_inner(self.context)
        sg = createContentInContainer(
            root,
            "euphorie.surveygroup",
            title=surveygroup_title or six.text_type(sector.survey.title),
        )

        return self.ImportSurvey(sector.survey, sg, survey_title)
Ejemplo n.º 2
0
 def _hash(self, request):
     """
     This hash can be tricked out by changing IP Adresses and might allow
     only a single person of a big company to vote
     """
     hash = md5()
     hash.update(safe_bytes(request.getClientAddr()))
     for key in ["User-Agent", "Accept-Language", "Accept-Encoding"]:
         hash.update(safe_bytes(request.getHeader(key)))
     return hash.hexdigest()
Ejemplo n.º 3
0
 def _hash(self, request):
     """
     We create a hash from the IP address and thus it could be tricked out
     by changing this address. It also allows only one person per (big or small)
     company to vote.
     """
     hash_ = md5()
     hash_.update(safe_bytes(request.getClientAddr()))
     for key in ['User-Agent', 'Accept-Language', 'Accept-Encoding']:
         hash_.update(safe_bytes(request.getHeader(key)))
     return hash_.hexdigest()
Ejemplo n.º 4
0
 def exportImage(self, parent, image, caption=None, tagname="image"):
     """:returns: base64 encoded image."""
     if not self.include_images:
         return
     node = etree.SubElement(parent, tagname)
     if image.contentType:
         node.attrib["content-type"] = image.contentType
     if image.filename:
         node.attrib["filename"] = image.filename
     if caption:
         node.attrib["caption"] = caption
     node.text = encodebytes(safe_bytes(image.data))
     return node
Ejemplo n.º 5
0
    def __call__(self, input, sector_title, sector_login, surveygroup_title,
                 survey_title):
        if isinstance(input, six.string_types + (bytes, )):
            sector = lxml.objectify.fromstring(safe_bytes(input))
        else:
            sector = input

        country = aq_inner(self.context)

        if not sector_title:
            sector_title = six.text_type(sector.title)
        root = createContentInContainer(country,
                                        "euphorie.sector",
                                        title=sector_title)

        account = getattr(sector, "account", None)
        if account is not None:
            root.login = sector_login or account.get("login").lower()
            root.password = account.get("password")
        else:
            root.login = sector_login

        contact = getattr(sector, "contact", None)
        if contact is not None:
            root.contact_name = el_unicode(contact, "name")
            root.contact_email = el_string(contact, "email")

        logo = getattr(sector, "logo", None)
        if logo is not None:
            root.logo = self.ImportImage(logo)[0]

        if hasattr(sector, "survey"):
            sg = createContentInContainer(
                root,
                "euphorie.surveygroup",
                title=surveygroup_title or six.text_type(sector.survey.title),
            )
            self.ImportSurvey(sector.survey, sg, survey_title)

        return root
Ejemplo n.º 6
0
    def ImportImage(self, node):
        """
        Import a base64 encoded image from an XML node.

        :param node: lxml.objectified XML node of image element
        :rtype: (:py:class:`NamedImage`, unicode) tuple
        """
        filename = attr_unicode(node, "filename")
        contentType = node.get("content-type", None)
        if not filename:
            basename = "image%d.%%s" % random.randint(1, 2**16)
            if contentType and "/" in contentType:
                filename = basename % contentType.split("/")[1]
            else:
                filename = basename % "jpg"
        image = NamedBlobImage(
            data=decodebytes(safe_bytes(str(node.text))),
            contentType=contentType,
            filename=filename,
        )
        if image.contentType is None and image.filename:
            image.contentType = mimetypes.guess_type(image.filename)[0]
        return (image, attr_unicode(node, "caption"))
    def test_download_upload(self):
        # Test uploading a download and downloading an upload.

        # 1. Manually add some redirects.
        storage = getUtility(IRedirectionStorage)
        portal_path = self.layer['portal'].absolute_url_path()
        now = DateTime('2019/01/27 10:00:00 GMT-3')
        for i in range(10):
            storage.add(
                '{:s}/foo/{:s}'.format(portal_path, str(i)),
                f'{portal_path:s}/test-folder',
                now=now,
                manual=True,
            )
        transaction.commit()

        # 2. Download the redirects.
        self.browser.open("%s/@@redirection-controlpanel" % self.portal_url)
        self.browser.getControl(name='form.button.Download').click()
        self.assertEqual(
            self.browser.headers['Content-Disposition'],
            'attachment; filename=redirects.csv',
        )
        downloaded_contents = self.browser.contents
        contents = downloaded_contents.splitlines()
        self.assertEqual(contents.pop(0), 'old path,new path,datetime,manual')
        self.assertEqual(len(contents), 10)
        contents.sort()
        self.assertEqual(
            contents[0], '/foo/0,/test-folder,2019/01/27 10:00:00 GMT-3,True'
        )

        # 3. clear the redirect storage
        storage.clear()
        transaction.commit()
        self.browser.open("%s/@@redirection-controlpanel" % self.portal_url)
        self.browser.getControl(name='form.button.Download').click()
        contents = self.browser.contents.splitlines()
        self.assertEqual(len(contents), 1)
        self.assertEqual(contents[0], 'old path,new path,datetime,manual')

        # 4. upload the original download
        self.browser.open("%s/@@redirection-controlpanel" % self.portal_url)
        self.browser.getControl(name='file').add_file(
            io.BytesIO(safe_bytes(downloaded_contents)),
            'text/plain',
            'redirects.csv',
        )
        self.browser.getControl(name='form.button.Upload').click()
        self.assertNotIn(
            'Please pick a file to upload.', self.browser.contents
        )
        self.assertNotIn(
            'The provided target object does not exist.', self.browser.contents
        )
        self.assertNotIn(
            'No alternative urls were added.', self.browser.contents
        )
        self.assertNotIn('Please correct these errors', self.browser.contents)
        self.assertEqual(len(storage), 10)

        # 5. download the upload
        self.browser.getControl(name='form.button.Download').click()
        new_downloaded_contents = self.browser.contents
        contents = downloaded_contents.splitlines()
        self.assertEqual(contents.pop(0), 'old path,new path,datetime,manual')
        self.assertEqual(len(contents), 10)
        contents.sort()
        self.assertEqual(
            contents[0], '/foo/0,/test-folder,2019/01/27 10:00:00 GMT-3,True'
        )
        # and it is actually the same as the original download
        self.assertEqual(new_downloaded_contents, downloaded_contents)