Esempio n. 1
0
    def test_secure_filename(self):
        self.assertEqual('My_cool_movie.mov',
                         secure_filename('My cool movie.mov'))
        self.assertEqual('etc_passwd', secure_filename('../../../etc/passwd'))
        self.assertEqual('i_contain_cool_umlauts.txt',
                         secure_filename(u'i contain cool \xfcml\xe4uts.txt'))
        self.assertEqual('i_contain_weird_characters.txt',
                         secure_filename(u'i contain weird châräctérs.txt'))

        with self.assertNoException():
            size = open_img(
                join(settings.CREME_ROOT, 'static', 'common', 'images',
                     secure_filename('500_200.png'))).size
        self.assertEqual((200, 200), size)
Esempio n. 2
0
def download_email_template(request, subject):
    subject = CrudityBackend.normalize_subject(subject)
    backend = None

    input = registry.crudity_registry.get_fetcher('email').get_input(
        'raw', 'create')
    if input is not None:
        backend = input.get_backend(subject)

    if backend is None:
        raise Http404(u"This backend is not registered")

    response = HttpResponse(
        render_to_string(
            "crudity/create_email_template.html",  # TODO: rename crudity/create_email_template.eml ??
            {
                'backend': backend,
                'contact': request.user.linked_contact,
                'to': settings.CREME_GET_EMAIL,
            },
            request=request,
        ),
        content_type="application/vnd.sealed.eml",
    )

    response['Content-Disposition'] = 'attachment; filename={}.eml'.format(
        # normalize('NFKD', str(CrudityBackend.normalize_subject(backend.subject))).encode('ascii', 'ignore')
        secure_filename(subject))

    return response
Esempio n. 3
0
def download_ini_template(request, subject):
    # subject = CrudityBackend.normalize_subject(subject)  ??
    backend = None
    input = registry.crudity_registry.get_fetcher('filesystem').get_input('ini', 'create')

    if input is not None:
        backend = input.get_backend(subject)

    if backend is None:
        raise Http404('This backend is not registered')

    ini = configparser.RawConfigParser()
    ini.add_section('head')
    ini.set('head', 'action', subject)

    if backend.is_sandbox_by_user:
        ini.set('head', 'username', getattr(request.user, get_user_model().USERNAME_FIELD))

    ini.add_section('body')
    for k, v in backend.body_map.items():
        ini.set('body', k, v)

    buffer = StringIO()
    ini.write(buffer)

    response = HttpResponse(buffer.getvalue(), content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename={}.ini'.format(secure_filename(subject))

    return response
Esempio n. 4
0
    def _create_image(self, contact):
        cleaned_data = self.cleaned_data
        image_encoded = cleaned_data['image_encoded']

        if image_encoded:
            img_name = secure_filename('{}_{}_{}'.format(
                contact.last_name, contact.first_name, contact.id))
            img_path = None

            if image_encoded.startswith(URL_START):
                tmp_img_path = None

                try:
                    if int(urlopen(image_encoded).info()
                           ['content-length']) <= settings.VCF_IMAGE_MAX_SIZE:
                        tmp_img_path = path.normpath(
                            path.join(IMG_UPLOAD_PATH, img_name))

                        urlretrieve(
                            image_encoded,
                            path.normpath(
                                path.join(settings.MEDIA_ROOT, tmp_img_path)))
                except:
                    logger.exception('Error with image')
                else:
                    img_path = tmp_img_path
            else:  # TODO: manage urls encoded in base64 ??
                try:
                    # TODO: factorise with activesync ??
                    img_data = base64.decodebytes(image_encoded.encode())
                    img_path = handle_uploaded_file(
                        ContentFile(img_data),
                        path=IMG_UPLOAD_PATH.split('/'),
                        name='{}.{}'.format(
                            img_name,
                            get_image_format(img_data),
                        ),
                    )
                except Exception:
                    logger.exception('VcfImportForm.save()')

            if img_path:
                return Document.objects.create(
                    user=cleaned_data['user'],
                    title=gettext('Image of {contact}').format(
                        contact=contact),
                    filedata=img_path,
                    linked_folder=Folder.objects.get(uuid=UUID_FOLDER_IMAGES),
                    description=gettext('Imported by VCFs'),
                )
Esempio n. 5
0
    def render(self):
        file_name = '{}.xsn'.format(
            secure_filename(
                CrudityBackend.normalize_subject(self.backend.subject)))
        response = HttpResponse(self._render(file_name),
                                content_type='application/vnd.ms-infopath')
        # response['Content-Disposition'] = 'attachment; filename={}.xsn'.format(
        #     normalize('NFKD',
        #               unicode(CrudityBackend.normalize_subject(self.backend.subject))
        #              ).encode('ascii', 'ignore')
        # )
        response['Content-Disposition'] = 'attachment; filename={}'.format(
            file_name)

        return response
Esempio n. 6
0
 def render(self) -> HttpResponse:
     file_name = '{}.xsn'.format(
         secure_filename(
             CrudityBackend.normalize_subject(self.backend.subject)))
     # response = HttpResponse(
     #     self._render(file_name), content_type='application/vnd.ms-infopath',
     # )
     # response['Content-Disposition'] = f'attachment; filename={file_name}'
     #
     # return response
     return HttpResponse(
         self._render(file_name),
         headers={
             'Content-Type': 'application/vnd.ms-infopath',
             'Content-Disposition': f'attachment; filename="{file_name}"',
         },
     )
Esempio n. 7
0
    def export(self, entity, user):
        html_template = get_template(self.html_template_path)
        css_template = get_template(self.css_template_path)
        context = self.get_context_data(object=entity)

        with override(language=self.flavour.language):
            html_content = html_template.render(context)
            css_content = css_template.render(context)

        # NB: before creating file to raise error as soon a possible
        #     & avoid junk files.
        html = HTML(string=html_content)
        css = CSS(string=css_content)

        basename = secure_filename(
            f'{entity._meta.verbose_name}_{entity.id}.pdf')
        final_path = FileCreator(
            dir_path=path.join(settings.MEDIA_ROOT, 'upload', 'billing'),
            name=basename,
        ).create()

        # NB: we create the FileRef instance as soon as possible to get the
        #     smallest duration when a crash causes a file which have to be
        #     removed by hand (not cleaned by the Cleaner job).
        file_ref = FileRef.objects.create(
            user=user,
            filedata=f'upload/billing/{path.basename(final_path)}',
            basename=basename,
        )

        # TODO ?
        # from weasyprint.fonts import FontConfiguration
        # font_config = FontConfiguration()
        html.write_pdf(
            final_path,
            stylesheets=[css],
            # TODO: ???
            # font_config=font_config
        )

        return file_ref
Esempio n. 8
0
    def export(self, entity, user):
        writer = self.get_writer(entity, user)

        basename = secure_filename(
            f'{entity._meta.verbose_name}_{entity.id}.xls')
        final_path = FileCreator(
            dir_path=path.join(settings.MEDIA_ROOT, 'upload', 'billing'),
            name=basename,
        ).create()

        # NB: we create the FileRef instance as soon as possible to get the
        #     smallest duration when a crash causes a file which have to be
        #     removed by hand (not cleaned by the Cleaner job).
        file_ref = FileRef.objects.create(
            user=user,
            filedata='upload/billing/' + path.basename(final_path),
            basename=basename,
        )

        writer.save(final_path)

        return file_ref
Esempio n. 9
0
    def export(self, entity, user):
        template = loader.get_template(self.template_path)
        context = self.get_context_data(object=entity)
        tmp_dir_path = mkdtemp(prefix='creme_billing_latex')

        with override(language=self.flavour.language):
            content = template.render(context)

        final_path, pdf_basename = self.generate_pdf(
            content=content,
            dir_path=tmp_dir_path,
            basename=secure_filename(
                f'{entity._meta.verbose_name}_{entity.id}'),
        )

        # TODO: context manager which can avoid file cleaning on exception ?
        rmtree(tmp_dir_path)

        return FileRef.objects.create(
            user=user,
            filedata='upload/billing/' + path.basename(final_path),
            basename=pdf_basename,
        )
Esempio n. 10
0
def export_as_pdf(request, base_id):
    entity = get_object_or_404(CremeEntity, pk=base_id).get_real_entity()

    has_perm = request.user.has_perm_to_view_or_die
    has_perm(entity)

    template_path = TEMPLATE_PATHS.get(entity.__class__)
    if template_path is None:
        raise ConflictError('This type of entity cannot be exported as pdf')

    source = entity.get_source().get_real_entity()
    has_perm(source)

    target = entity.get_target().get_real_entity()
    has_perm(target)

    document_name = str(entity._meta.verbose_name)

    template = loader.get_template(template_path)
    context = {
        'plines': entity.get_lines(billing.get_product_line_model()),
        'slines': entity.get_lines(billing.get_service_line_model()),
        'source': source,
        'target': target,
        'object': entity,
        'document_name': document_name,
    }

    basename = secure_filename('{}_{}'.format(document_name, entity.id))
    tmp_dir_path = mkdtemp(prefix='creme_billing_latex')
    latex_file_path = path.join(tmp_dir_path, '{}.tex'.format(basename))

    # NB: we precise the encoding or it oddly crashes on some systems...
    with open(latex_file_path, 'w', encoding='utf-8') as f:
        f.write(smart_str(template.render(context)))

    # NB: return code seems always 1 even when there is no error...
    subprocess.call([
        'pdflatex',
        '-interaction=batchmode',
        '-output-directory',
        tmp_dir_path,
        latex_file_path,
    ])

    pdf_basename = '{}.pdf'.format(basename)
    temp_pdf_file_path = path.join(tmp_dir_path, pdf_basename)

    if not path.exists(temp_pdf_file_path):
        logger.critical(
            'It seems the PDF generation has failed. '
            'The temporary directory has not been removed, '
            'so you can inspect the *.log file in "%s"', tmp_dir_path)
        # TODO: use a better exception class ?
        raise ConflictError(
            _('The generation of the PDF file has failed ; please contact your administrator.'
              ))

    final_path = FileCreator(
        dir_path=path.join(settings.MEDIA_ROOT, 'upload', 'billing'),
        name=pdf_basename,
    ).create()
    copy(temp_pdf_file_path, final_path)

    rmtree(tmp_dir_path)

    fileref = FileRef.objects.create(  # user=request.user, TODO
        filedata='upload/billing/' + path.basename(final_path),
        basename=pdf_basename,
    )

    return HttpResponseRedirect(
        reverse(
            'creme_core__dl_file',
            args=(fileref.filedata, ),
        ))