Beispiel #1
0
def save_zen(request, project, subproject, lang):
    """Save handler for zen mode."""
    translation = get_translation(request, project, subproject, lang)
    user_locked = translation.is_user_locked(request.user)

    form = TranslationForm(
        request.user.profile, translation, None, request.POST
    )
    if not can_translate(request.user, translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not form.is_valid():
        messages.error(request, _('Failed to save translation!'))
    elif not user_locked:
        unit = form.cleaned_data['unit']

        perform_translation(unit, form, request)

    return render(
        request,
        'zen-response.html',
        {},
    )
Beispiel #2
0
def parse_url(request, project, subproject=None, lang=None):
    context = {}
    if subproject is None:
        obj = get_project(request, project)
        perms = {'project': obj}
        unit_set = Unit.objects.filter(translation__subproject__project=obj)
        context['project'] = obj
    elif lang is None:
        obj = get_subproject(request, project, subproject)
        perms = {'project': obj.project}
        unit_set = Unit.objects.filter(translation__subproject=obj)
        context['subproject'] = obj
        context['project'] = obj.project
    else:
        obj = get_translation(request, project, subproject, lang)
        perms = {'translation': obj}
        unit_set = obj.unit_set
        context['translation'] = obj
        context['subproject'] = obj.subproject
        context['project'] = obj.subproject.project

    if not can_translate(request.user, **perms):
        raise PermissionDenied()

    return obj, unit_set, context
Beispiel #3
0
def show_translation(request, project, subproject, lang):
    obj = get_translation(request, project, subproject, lang)
    last_changes = Change.objects.for_translation(obj)[:10]

    # Check locks
    obj.is_locked(request.user)

    # Get form
    form = get_upload_form(request.user, obj)

    # Is user allowed to do automatic translation?
    if can_automatic_translation(request.user, obj.subproject.project):
        autoform = AutoForm(obj, request.user)
    else:
        autoform = None

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if request.user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm(
            initial={'exclude_user': request.user.username})

    replace_form = None
    if can_translate(request.user, obj):
        replace_form = ReplaceForm()

    return render(
        request, 'translation.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.subproject.project,
            'form':
            form,
            'autoform':
            autoform,
            'search_form':
            search_form,
            'review_form':
            review_form,
            'replace_form':
            replace_form,
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_kwargs()),
            'show_only_component':
            True,
            'other_translations':
            Translation.objects.prefetch().filter(
                subproject__project=obj.subproject.project,
                language=obj.language,
            ).exclude(pk=obj.pk),
        })
Beispiel #4
0
def handle_revert(translation, request, next_unit_url):
    revertform = RevertForm(translation, request.GET)
    if not revertform.is_valid():
        messages.error(request, _('Invalid revert request!'))
        return None

    unit = revertform.cleaned_data['unit']
    change = revertform.cleaned_data['revert_change']

    if not can_translate(request.user, unit):
        messages.error(
            request,
            _('Insufficient privileges for saving translations.')
        )
        return None

    if change.target == "":
        messages.error(request, _('Can not revert to empty translation!'))
        return None
    # Store unit
    unit.translate(
        request, change.target, unit.state,
        change_action=Change.ACTION_REVERT
    )
    # Redirect to next entry
    return HttpResponseRedirect(next_unit_url)
Beispiel #5
0
def save_zen(request, project, subproject, lang):
    """Save handler for zen mode."""
    translation = get_translation(request, project, subproject, lang)
    user_locked = translation.is_user_locked(request.user)

    form = TranslationForm(
        request.user.profile, translation, None, request.POST
    )
    if not can_translate(request.user, translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not form.is_valid():
        messages.error(request, _('Failed to save translation!'))
    elif not user_locked:
        unit = form.cleaned_data['unit']

        perform_translation(unit, form, request)

    return render(
        request,
        'zen-response.html',
        {},
    )
Beispiel #6
0
def handle_revert(translation, request, next_unit_url):
    if not can_translate(request.user, translation):
        messages.error(request,
                       _('You don\'t have privileges to save translations!'))
        return

    revertform = RevertForm(translation, request.GET)
    if not revertform.is_valid():
        return

    unit = revertform.cleaned_data['unit']

    try:
        change = Change.objects.get(pk=revertform.cleaned_data['revert'])
    except Change.DoesNotExist:
        messages.error(request, _('Can not revert to nonexisting change!'))
        return

    if unit.id_hash != change.unit.id_hash:
        messages.error(request, _('Can not revert to different unit!'))
    elif change.target == "":
        messages.error(request, _('Can not revert to empty translation!'))
    else:
        # Store unit
        unit.target = change.target
        unit.save_backend(request, change_action=Change.ACTION_REVERT)
        # Redirect to next entry
        return HttpResponseRedirect(next_unit_url)
Beispiel #7
0
def handle_merge(translation, request, next_unit_url):
    """Handle unit merging."""
    if not can_translate(request.user, translation):
        messages.error(request,
                       _('You don\'t have privileges to save translations!'))
        return

    mergeform = MergeForm(translation, request.GET)
    if not mergeform.is_valid():
        messages.error(request, _('Invalid merge request!'))
        return

    unit = mergeform.cleaned_data['unit']
    merged = mergeform.cleaned_data['merge_unit']

    # Store unit
    unit.target = merged.target
    unit.fuzzy = merged.fuzzy
    saved = unit.save_backend(request)
    # Update stats if there was change
    if saved:
        request.user.profile.translated += 1
        request.user.profile.save()
    # Redirect to next entry
    return HttpResponseRedirect(next_unit_url)
Beispiel #8
0
def handle_merge(translation, request, next_unit_url):
    """Handle unit merging."""
    mergeform = MergeForm(translation, request.GET)
    if not mergeform.is_valid():
        messages.error(request, _('Invalid merge request!'))
        return

    unit = mergeform.cleaned_data['unit']
    merged = mergeform.cleaned_data['merge_unit']

    if not can_translate(request.user, unit):
        messages.error(request,
                       _('Insufficient privileges for saving translations.'))
        return

    # Store unit
    unit.target = merged.target
    unit.state = merged.state
    saved = unit.save_backend(request)
    # Update stats if there was change
    if saved:
        request.user.profile.translated += 1
        request.user.profile.save()
    # Redirect to next entry
    return HttpResponseRedirect(next_unit_url)
Beispiel #9
0
    def merge_translations(self, request, store2, overwrite, add_fuzzy, fuzzy,
                           merge_header):
        """Merge translation unit wise

        Needed for template based translations to add new strings.
        """
        not_found = 0
        skipped = 0
        accepted = 0

        author = get_author_name(request.user)

        # Commit possible prior changes
        self.commit_pending(request, author)

        for set_fuzzy, unit2 in store2.iterate_merge(fuzzy):
            try:
                unit = self.unit_set.get_unit(unit2)
            except Unit.DoesNotExist:
                not_found += 1
                continue

            if ((unit.translated and not overwrite)
                    or (not can_translate(request.user, unit))):
                skipped += 1
                continue

            accepted += 1

            # We intentionally avoid propagating:
            # - in most cases it's not desired
            # - it slows down import considerably
            # - it brings locking issues as import is
            #   executed with lock held and linked repos
            #   can't obtain the lock
            state = STATE_TRANSLATED
            if add_fuzzy or set_fuzzy:
                state = STATE_FUZZY
            unit.translate(request,
                           split_plural(unit2.get_target()),
                           state,
                           change_action=Change.ACTION_UPLOAD,
                           propagate=False)

        if accepted > 0:
            self.invalidate_cache()

            if merge_header:
                self.store.merge_header(store2)
                self.store.save()
            self.store_hash()

            self.git_commit(request,
                            author,
                            timezone.now(),
                            force_commit=True,
                            sync=True)

        return (not_found, skipped, accepted, store2.count_units())
Beispiel #10
0
 def propagate(self, request, change_action=None):
     """Propagate current translation to all others."""
     allunits = Unit.objects.same(self).filter(
         translation__subproject__allow_translation_propagation=True)
     for unit in allunits:
         if not can_translate(request.user, unit):
             continue
         unit.target = self.target
         unit.state = self.state
         unit.save_backend(request, False, change_action=change_action)
Beispiel #11
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    last_changes = Change.objects.for_component(obj)[:10]

    try:
        sample = obj.translation_set.all()[0]
        source_words = sample.total_words
        total_strings = sample.total
    except IndexError:
        source_words = 0
        total_strings = 0

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'subproject.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(obj.translation_set.all()),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'subproject': obj.slug,
                'project': obj.project.slug
            }),
            'unit_count':
            Unit.objects.filter(translation__subproject=obj).count(),
            'words_count':
            obj.get_total_words(),
            'language_count':
            Language.objects.filter(
                translation__subproject=obj).distinct().count(),
            'strings_count':
            total_strings,
            'source_words_count':
            source_words,
            'replace_form':
            replace_form,
            'search_form':
            SearchForm(),
        })
Beispiel #12
0
def show_project(request, project):
    obj = get_project(request, project)

    dict_langs = Language.objects.filter(dictionary__project=obj).annotate(
        Count('dictionary'))

    last_changes = Change.objects.for_project(obj)[:10]

    language_stats = sort_unicode(obj.stats.get_language_stats(),
                                  lambda x: force_text(x.language.name))

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
        mass_state_form = MassStateForm(request.user, obj)
    else:
        replace_form = None
        mass_state_form = None

    return render(
        request, 'project.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj,
            'dicts':
            dict_langs,
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({'project': obj.slug}),
            'language_stats':
            language_stats,
            'unit_count':
            Unit.objects.filter(translation__subproject__project=obj).count(),
            'words_count':
            obj.stats.all_words,
            'language_count':
            Language.objects.filter(
                translation__subproject__project=obj).distinct().count(),
            'strings_count':
            obj.stats.source_strings,
            'source_words_count':
            obj.stats.source_words,
            'search_form':
            SearchForm(),
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'components':
            prefetch_stats(obj.subproject_set.select_related()),
        })
Beispiel #13
0
def search_replace(request, project, component=None, lang=None):
    obj, unit_set, context = parse_url(request, project, component, lang)

    form = ReplaceForm(request.POST)

    if not form.is_valid():
        messages.error(request, _('Failed to process form!'))
        show_form_errors(request, form)
        return redirect(obj)

    search_text = form.cleaned_data['search']
    replacement = form.cleaned_data['replacement']

    matching = unit_set.filter(target__contains=search_text)

    updated = 0
    if matching.exists():
        confirm = ReplaceConfirmForm(matching, request.POST)

        if not confirm.is_valid():
            for unit in matching:
                unit.replacement = unit.target.replace(search_text,
                                                       replacement)
            context.update({
                'matching': matching,
                'search_query': search_text,
                'replacement': replacement,
                'form': form,
                'confirm': ReplaceConfirmForm(matching),
            })
            return render(request, 'replace.html', context)

        matching = confirm.cleaned_data['units']

        obj.commit_pending(request)

        with transaction.atomic():
            for unit in matching.select_for_update():
                if not can_translate(request.user, unit):
                    continue
                unit.translate(request,
                               unit.target.replace(search_text, replacement),
                               unit.state,
                               change_action=Change.ACTION_REPLACE)
                updated += 1

    import_message(
        request, updated,
        _('Search and replace completed, no strings were updated.'),
        ungettext('Search and replace completed, %d string was updated.',
                  'Search and replace completed, %d strings were updated.',
                  updated))

    return redirect(obj)
Beispiel #14
0
def show_project(request, project):
    obj = get_project(request, project)

    dict_langs = Language.objects.filter(
        dictionary__project=obj
    ).annotate(Count('dictionary'))

    last_changes = Change.objects.for_project(obj)[:10]

    language_stats = sort_unicode(
        get_per_language_stats(obj), lambda tup: force_text(tup[0])
    )

    language_stats = [
        (
            tup[0],
            translation_percent(tup[1], tup[2]),
            translation_percent(tup[3], tup[4])
        )
        for tup in language_stats
    ]

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request,
        'project.html',
        {
            'allow_index': True,
            'object': obj,
            'project': obj,
            'dicts': dict_langs,
            'last_changes': last_changes,
            'last_changes_url': urlencode(
                {'project': obj.slug}
            ),
            'language_stats': language_stats,
            'unit_count': Unit.objects.filter(
                translation__subproject__project=obj
            ).count(),
            'words_count': obj.get_total_words(),
            'language_count': Language.objects.filter(
                translation__subproject__project=obj
            ).distinct().count(),
            'strings_count': obj.get_total(),
            'source_words_count': obj.get_source_words(),
            'search_form': SearchForm(),
            'replace_form': replace_form,
        }
    )
Beispiel #15
0
def show_translation(request, project, subproject, lang):
    obj = get_translation(request, project, subproject, lang)
    last_changes = Change.objects.for_translation(obj)[:10]

    # Check locks
    obj.is_locked(request.user)

    # Get form
    form = get_upload_form(request.user, obj)

    # Is user allowed to do automatic translation?
    if can_automatic_translation(request.user, obj.subproject.project):
        autoform = AutoForm(obj, request.user)
    else:
        autoform = None

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if request.user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm()

    replace_form = None
    if can_translate(request.user, obj):
        replace_form = ReplaceForm()

    return render(
        request,
        'translation.html',
        {
            'allow_index': True,
            'object': obj,
            'project': obj.subproject.project,
            'form': form,
            'autoform': autoform,
            'search_form': search_form,
            'review_form': review_form,
            'replace_form': replace_form,
            'last_changes': last_changes,
            'last_changes_url': urlencode(obj.get_kwargs()),
            'show_only_component': True,
            'other_translations': Translation.objects.prefetch().filter(
                subproject__project=obj.subproject.project,
                language=obj.language,
            ).exclude(
                pk=obj.pk
            ),
        }
    )
Beispiel #16
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    last_changes = Change.objects.for_component(obj)[:10]

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
        mass_state_form = MassStateForm(request.user, obj)
    else:
        replace_form = None
        mass_state_form = None

    return render(
        request, 'subproject.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(prefetch_stats(obj.translation_set.all())),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'subproject': obj.slug,
                'project': obj.project.slug
            }),
            'unit_count':
            Unit.objects.filter(translation__subproject=obj).count(),
            'words_count':
            obj.stats.all_words,
            'language_count':
            Language.objects.filter(
                translation__subproject=obj).distinct().count(),
            'strings_count':
            obj.stats.source_strings,
            'source_words_count':
            obj.stats.source_words,
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'search_form':
            SearchForm(),
        })
Beispiel #17
0
def get_upload_form(user, translation, *args):
    """Return correct upload form based on user permissions."""
    project = translation.subproject.project
    if can_author_translation(user, project):
        form = ExtraUploadForm
    elif can_overwrite_translation(user, project):
        form = UploadForm
    else:
        form = SimpleUploadForm
    result = form(*args)
    if not can_translate(user, translation):
        result.remove_translation_choice('translate')
        result.remove_translation_choice('fuzzy')
    if not can_suggest(user, translation):
        result.remove_translation_choice('suggest')
    return result
Beispiel #18
0
def get_upload_form(user, translation, *args):
    """Return correct upload form based on user permissions."""
    project = translation.subproject.project
    if can_author_translation(user, project):
        form = ExtraUploadForm
    elif can_overwrite_translation(user, project):
        form = UploadForm
    else:
        form = SimpleUploadForm
    result = form(*args)
    if not can_translate(user, translation):
        result.remove_translation_choice('translate')
        result.remove_translation_choice('fuzzy')
    if not can_suggest(user, translation):
        result.remove_translation_choice('suggest')
    return result
Beispiel #19
0
def show_component(request, project, component):
    obj = get_component(request, project, component)

    last_changes = Change.objects.for_component(obj)[:10]

    # Is user allowed to do automatic translation?
    if can_automatic_translation(request.user, obj.project):
        mass_state_form = MassStateForm(request.user, obj)
    else:
        mass_state_form = None

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'component.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(prefetch_stats(obj.translation_set.all())),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'component': obj.slug,
                'project': obj.project.slug
            }),
            'language_count':
            Language.objects.filter(
                translation__component=obj).distinct().count(),
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'search_form':
            SearchForm(),
        })
Beispiel #20
0
def handle_translate(translation, request, user_locked,
                     this_unit_url, next_unit_url):
    """Save translation or suggestion to database and backend."""
    # Antispam protection
    antispam = AntispamForm(request.POST)
    if not antispam.is_valid():
        # Silently redirect to next entry
        return HttpResponseRedirect(next_unit_url)

    # Check whether translation is not outdated
    translation.check_sync()

    form = TranslationForm(
        request.user.profile, translation, None, request.POST
    )
    if not form.is_valid():
        show_form_errors(request, form)
        return

    unit = form.cleaned_data['unit']
    go_next = True

    if 'suggest' in request.POST:
        go_next = perform_suggestion(unit, form, request)
    elif not can_translate(request.user, unit.translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not user_locked:
        # Custom commit message
        message = request.POST.get('commit_message')
        if message is not None and message != unit.translation.commit_message:
            # Commit pending changes so that they don't get new message
            unit.translation.commit_pending(request, request.user)
            # Store new commit message
            unit.translation.commit_message = message
            unit.translation.save()

        go_next = perform_translation(unit, form, request)

    # Redirect to next entry
    if go_next:
        return HttpResponseRedirect(next_unit_url)
    else:
        return HttpResponseRedirect(this_unit_url)
Beispiel #21
0
def handle_translate(translation, request, user_locked,
                     this_unit_url, next_unit_url):
    """Save translation or suggestion to database and backend."""
    # Antispam protection
    antispam = AntispamForm(request.POST)
    if not antispam.is_valid():
        # Silently redirect to next entry
        return HttpResponseRedirect(next_unit_url)

    # Check whether translation is not outdated
    translation.check_sync()

    form = TranslationForm(
        request.user.profile, translation, None, request.POST
    )
    if not form.is_valid():
        show_form_errors(request, form)
        return

    unit = form.cleaned_data['unit']
    go_next = True

    if 'suggest' in request.POST:
        go_next = perform_suggestion(unit, form, request)
    elif not can_translate(request.user, unit.translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not user_locked:
        # Custom commit message
        message = request.POST.get('commit_message')
        if message is not None and message != unit.translation.commit_message:
            # Commit pending changes so that they don't get new message
            unit.translation.commit_pending(request, request.user)
            # Store new commit message
            unit.translation.commit_message = message
            unit.translation.save()

        go_next = perform_translation(unit, form, request)

    # Redirect to next entry
    if go_next:
        return HttpResponseRedirect(next_unit_url)
    else:
        return HttpResponseRedirect(this_unit_url)
Beispiel #22
0
def save_zen(request, project, subproject, lang):
    """Save handler for zen mode."""
    def render_mesage(message):
        return render_to_string(
            'message.html',
            {'tags': message.tags, 'message': message.message}
        )

    translation = get_translation(request, project, subproject, lang)

    form = TranslationForm(
        request.user, translation, None, request.POST
    )
    translationsum = ''
    if not form.is_valid():
        show_form_errors(request, form)
    elif not can_translate(request.user, form.cleaned_data['unit']):
        messages.error(
            request, _('Insufficient privileges for saving translations.')
        )
    else:
        unit = form.cleaned_data['unit']

        perform_translation(unit, form, request)

        translationsum = hash_to_checksum(unit.get_target_hash())

    response = {
        'messages': '',
        'state': 'success',
        'translationsum': translationsum,
    }

    storage = get_messages(request)
    if storage:
        response['messages'] = '\n'.join([render_mesage(m) for m in storage])
        tags = set([m.tags for m in storage])
        if 'error' in tags:
            response['state'] = 'danger'
        elif 'warning' in tags:
            response['state'] = 'warning'
        elif 'info' in tags:
            response['state'] = 'info'

    return JsonResponse(data=response)
Beispiel #23
0
def state_change(request, project, subproject=None, lang=None):
    obj, unit_set, context = parse_url(request, project, subproject, lang)

    form = MassStateForm(request.user, obj, request.POST)

    if not form.is_valid():
        messages.error(request, _('Failed to process form!'))
        show_form_errors(request, form)
        return redirect(obj)

    matching = unit_set.filter_type(
        form.cleaned_data['type'],
        context['project'],
        context['translation'].language if 'translation' in context else None,
    ).exclude(
        state=STATE_EMPTY
    )

    obj.commit_pending(request)

    updated = 0
    with transaction.atomic():
        for unit in matching.select_for_update():
            if not can_translate(request.user, unit):
                continue
            unit.translate(
                request,
                unit.target,
                int(form.cleaned_data['state']),
                change_action=Change.ACTION_MASS_STATE,
            )
            updated += 1

    import_message(
        request, updated,
        _('Mass state change completed, no strings were updated.'),
        ungettext(
            'Mass state change completed, %d string was updated.',
            'Mass state change completed, %d strings were updated.',
            updated
        )
    )

    return redirect(obj)
Beispiel #24
0
def search_replace(request, project, subproject=None, lang=None):
    if subproject is None:
        obj = get_project(request, project)
        perms = {'project': obj}
        unit_set = Unit.objects.filter(translation__subproject__project=obj)
    elif lang is None:
        obj = get_subproject(request, project, subproject)
        perms = {'project': obj.project}
        unit_set = Unit.objects.filter(translation__subproject=obj)
    else:
        obj = get_translation(request, project, subproject, lang)
        perms = {'translation': obj}
        unit_set = obj.unit_set

    if not can_translate(request.user, **perms):
        raise PermissionDenied()

    form = ReplaceForm(request.POST)

    if not form.is_valid():
        messages.error(request, _('Failed to process form!'))
        return redirect(obj)

    search_text = form.cleaned_data['search']
    replacement = form.cleaned_data['replacement']

    matching = unit_set.filter(target__contains=search_text)
    updated = matching.count()

    for unit in matching.iterator():
        unit.target = unit.target.replace(search_text, replacement)
        unit.save_backend(request, change_action=Change.ACTION_REPLACE)

    import_message(
        request, updated,
        _('Search and replace completed, no strings were updated.'),
        ungettext(
            'Search and replace completed, %d string was updated.',
            'Search and replace completed, %d strings were updated.',
            updated
        )
    )

    return redirect(obj)
Beispiel #25
0
def search_replace(request, project, subproject=None, lang=None):
    if subproject is None:
        obj = get_project(request, project)
        perms = {'project': obj}
        unit_set = Unit.objects.filter(translation__subproject__project=obj)
    elif lang is None:
        obj = get_subproject(request, project, subproject)
        perms = {'project': obj.project}
        unit_set = Unit.objects.filter(translation__subproject=obj)
    else:
        obj = get_translation(request, project, subproject, lang)
        perms = {'translation': obj}
        unit_set = obj.unit_set

    if not can_translate(request.user, **perms):
        raise PermissionDenied()

    form = ReplaceForm(request.POST)

    if not form.is_valid():
        messages.error(request, _('Failed to process form!'))
        return redirect(obj)

    search_text = form.cleaned_data['search']
    replacement = form.cleaned_data['replacement']

    matching = unit_set.filter(target__contains=search_text)
    updated = matching.count()

    for unit in matching.iterator():
        unit.target = unit.target.replace(search_text, replacement)
        unit.save_backend(request, change_action=Change.ACTION_REPLACE)

    import_message(
        request, updated,
        _('Search and replace completed, no strings were updated.'),
        ungettext(
            'Search and replace completed, %d string was updated.',
            'Search and replace completed, %d strings were updated.',
            updated
        )
    )

    return redirect(obj)
Beispiel #26
0
def save_zen(request, project, subproject, lang):
    """Save handler for zen mode."""
    translation = get_translation(request, project, subproject, lang)

    form = TranslationForm(request.user, translation, None, request.POST)
    if not form.is_valid():
        messages.error(request, _('Failed to save translation!'))
    elif not can_translate(request.user, form.cleaned_data['unit']):
        messages.error(request,
                       _('Insufficient privileges for saving translations.'))
    else:
        unit = form.cleaned_data['unit']

        perform_translation(unit, form, request)

    return render(
        request,
        'zen-response.html',
        {},
    )
Beispiel #27
0
def handle_translate(translation, request, this_unit_url, next_unit_url):
    """Save translation or suggestion to database and backend."""
    # Antispam protection
    antispam = AntispamForm(request.POST)
    if not antispam.is_valid():
        # Silently redirect to next entry
        return HttpResponseRedirect(next_unit_url)

    form = TranslationForm(
        request.user, translation, None, request.POST
    )
    if not form.is_valid():
        show_form_errors(request, form)
        return None

    unit = form.cleaned_data['unit']
    go_next = True

    if 'suggest' in request.POST:
        go_next = perform_suggestion(unit, form, request)
    elif not can_translate(request.user, unit):
        messages.error(
            request,
            _('Insufficient privileges for saving translations.')
        )
    else:
        # Custom commit message
        message = request.POST.get('commit_message')
        if message is not None and message != unit.translation.commit_message:
            # Commit pending changes so that they don't get new message
            unit.translation.commit_pending(request)
            # Store new commit message
            unit.translation.commit_message = message
            unit.translation.save()

        go_next = perform_translation(unit, form, request)

    # Redirect to next entry
    if go_next:
        return HttpResponseRedirect(next_unit_url)
    return HttpResponseRedirect(this_unit_url)
Beispiel #28
0
def handle_revert(translation, request, next_unit_url):
    if not can_translate(request.user, translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
        return

    revertform = RevertForm(translation, request.GET)
    if not revertform.is_valid():
        return

    unit = revertform.cleaned_data['unit']

    try:
        change = Change.objects.get(
            pk=revertform.cleaned_data['revert']
        )
    except Change.DoesNotExist:
        messages.error(
            request,
            _('Can not revert to nonexisting change!')
        )
        return

    if unit.id_hash != change.unit.id_hash:
        messages.error(
            request,
            _('Can not revert to different unit!')
        )
    elif change.target == "":
        messages.error(
            request,
            _('Can not revert to empty translation!')
        )
    else:
        # Store unit
        unit.target = change.target
        unit.save_backend(request, change_action=Change.ACTION_REVERT)
        # Redirect to next entry
        return HttpResponseRedirect(next_unit_url)
Beispiel #29
0
def handle_revert(translation, request, next_unit_url):
    if not can_translate(request.user, translation):
        messages.error(request,
                       _('You don\'t have privileges to save translations!'))
        return

    revertform = RevertForm(translation, request.GET)
    if not revertform.is_valid():
        messages.error(request, _('Invalid revert request!'))
        return

    unit = revertform.cleaned_data['unit']
    change = revertform.cleaned_data['revert_change']

    if change.target == "":
        messages.error(request, _('Can not revert to empty translation!'))
    else:
        # Store unit
        unit.target = change.target
        unit.save_backend(request, change_action=Change.ACTION_REVERT)
        # Redirect to next entry
        return HttpResponseRedirect(next_unit_url)
Beispiel #30
0
def handle_merge(translation, request, next_unit_url):
    """Handle unit merging."""
    if not can_translate(request.user, translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
        return

    mergeform = MergeForm(translation, request.GET)
    if not mergeform.is_valid():
        messages.error(
            request,
            _('Invalid merge request!')
        )
        return

    unit = mergeform.cleaned_data['unit']

    merged = Unit.objects.get(
        pk=mergeform.cleaned_data['merge']
    )

    if unit.id_hash != merged.id_hash:
        messages.error(
            request,
            _('Can not merge different messages!')
        )
    else:
        # Store unit
        unit.target = merged.target
        unit.fuzzy = merged.fuzzy
        saved = unit.save_backend(request)
        # Update stats if there was change
        if saved:
            request.user.profile.translated += 1
            request.user.profile.save()
        # Redirect to next entry
        return HttpResponseRedirect(next_unit_url)
Beispiel #31
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    last_changes = Change.objects.for_component(obj)[:10]

    if (request.method == 'POST'
            and can_edit_subproject(request.user, obj.project)):
        settings_form = SubprojectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!'))
    else:
        settings_form = SubprojectSettingsForm(instance=obj)

    try:
        sample = obj.translation_set.all()[0]
        source_words = sample.total_words
        total_strings = sample.total
    except IndexError:
        source_words = 0
        total_strings = 0

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'subproject.html', {
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(obj.translation_set.enabled()),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'subproject': obj.slug,
                'project': obj.project.slug
            }),
            'settings_form':
            settings_form,
            'unit_count':
            Unit.objects.filter(translation__subproject=obj).count(),
            'words_count':
            obj.get_total_words(),
            'language_count':
            Language.objects.filter(
                translation__subproject=obj).distinct().count(),
            'strings_count':
            total_strings,
            'source_words_count':
            source_words,
            'replace_form':
            replace_form,
            'search_form':
            SearchForm(),
        })
Beispiel #32
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    last_changes = Change.objects.for_component(obj)[:10]

    if (request.method == 'POST' and
            can_edit_subproject(request.user, obj.project)):
        settings_form = SubprojectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!')
            )
    else:
        settings_form = SubprojectSettingsForm(instance=obj)

    try:
        sample = obj.translation_set.all()[0]
        source_words = sample.total_words
        total_strings = sample.total
    except IndexError:
        source_words = 0
        total_strings = 0

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request,
        'subproject.html',
        {
            'allow_index': True,
            'object': obj,
            'project': obj.project,
            'translations': sort_objects(obj.translation_set.enabled()),
            'show_language': 1,
            'reports_form': ReportsForm(),
            'last_changes': last_changes,
            'last_changes_url': urlencode(
                {'subproject': obj.slug, 'project': obj.project.slug}
            ),
            'settings_form': settings_form,
            'unit_count': Unit.objects.filter(
                translation__subproject=obj
            ).count(),
            'words_count': obj.get_total_words(),
            'language_count': Language.objects.filter(
                translation__subproject=obj
            ).distinct().count(),
            'strings_count': total_strings,
            'source_words_count': source_words,
            'replace_form': replace_form,
            'search_form': SearchForm(),
        }
    )
Beispiel #33
0
def show_translation(request, project, subproject, lang):
    obj = get_translation(request, project, subproject, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.for_translation(obj)[:10]

    # Get form
    form = get_upload_form(request.user, obj)

    # Is user allowed to do automatic translation?
    if can_automatic_translation(request.user, obj.subproject.project):
        autoform = AutoForm(obj, request.user)
    else:
        autoform = None

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if request.user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm(
            initial={'exclude_user': request.user.username})

    replace_form = None
    if can_translate(request.user, translation=obj):
        replace_form = ReplaceForm()

    return render(
        request, 'translation.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.subproject.project,
            'form':
            form,
            'autoform':
            autoform,
            'search_form':
            search_form,
            'review_form':
            review_form,
            'replace_form':
            replace_form,
            'new_unit_form':
            NewUnitForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_kwargs()),
            'show_only_component':
            True,
            'pending_fulltext':
            obj.unit_set.filter(id__in=IndexUpdate.objects.filter(
                to_delete=False).values('unitid')).exists(),
            'other_translations':
            prefetch_stats(Translation.objects.prefetch().filter(
                subproject__project=obj.subproject.project,
                language=obj.language,
            ).exclude(pk=obj.pk)),
        })
def search_replace(request, project, subproject=None, lang=None):
    context = {}
    if subproject is None:
        obj = get_project(request, project)
        perms = {'project': obj}
        unit_set = Unit.objects.filter(translation__subproject__project=obj)
        context['project'] = obj
    elif lang is None:
        obj = get_subproject(request, project, subproject)
        perms = {'project': obj.project}
        unit_set = Unit.objects.filter(translation__subproject=obj)
        context['subproject'] = obj
        context['project'] = obj.project
    else:
        obj = get_translation(request, project, subproject, lang)
        perms = {'translation': obj}
        unit_set = obj.unit_set
        context['translation'] = obj
        context['subproject'] = obj.subproject
        context['project'] = obj.subproject.project

    if not can_translate(request.user, **perms):
        raise PermissionDenied()

    form = ReplaceForm(request.POST)

    if not form.is_valid():
        messages.error(request, _('Failed to process form!'))
        return redirect(obj)

    search_text = form.cleaned_data['search']
    replacement = form.cleaned_data['replacement']

    matching = unit_set.filter(target__contains=search_text)

    if matching.count() == 0:
        updated = 0

    else:
        confirm = ReplaceConfirmForm(matching, request.POST)

        if not confirm.is_valid():
            for unit in matching:
                unit.replacement = unit.target.replace(search_text,
                                                       replacement)
            context.update({
                'matching': matching,
                'search_query': search_text,
                'replacement': replacement,
                'form': form,
                'confirm': ReplaceConfirmForm(matching),
            })
            return render(request, 'replace.html', context)

        matching = confirm.cleaned_data['units']
        updated = matching.count()

        for unit in matching.iterator():
            if not can_translate(request.user, unit):
                continue
            unit.target = unit.target.replace(search_text, replacement)
            unit.save_backend(request, change_action=Change.ACTION_REPLACE)

    import_message(
        request, updated,
        _('Search and replace completed, no strings were updated.'),
        ungettext('Search and replace completed, %d string was updated.',
                  'Search and replace completed, %d strings were updated.',
                  updated))

    return redirect(obj)
Beispiel #35
0
def show_project(request, project):
    obj = get_project(request, project)

    dict_langs = Language.objects.filter(dictionary__project=obj).annotate(
        Count('dictionary'))

    if request.method == 'POST' and can_edit_project(request.user, obj):
        settings_form = ProjectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!'))
    else:
        settings_form = ProjectSettingsForm(instance=obj)

    last_changes = Change.objects.for_project(obj)[:10]

    language_stats = sort_unicode(get_per_language_stats(obj),
                                  lambda tup: force_text(tup[0]))

    language_stats = [(tup[0], translation_percent(tup[1], tup[2]),
                       translation_percent(tup[3], tup[4]))
                      for tup in language_stats]

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'project.html', {
            'object':
            obj,
            'project':
            obj,
            'dicts':
            dict_langs,
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({'project': obj.slug}),
            'settings_form':
            settings_form,
            'language_stats':
            language_stats,
            'unit_count':
            Unit.objects.filter(translation__subproject__project=obj).count(),
            'words_count':
            obj.get_total_words(),
            'language_count':
            Language.objects.filter(
                translation__subproject__project=obj).distinct().count(),
            'strings_count':
            obj.get_total(),
            'source_words_count':
            obj.get_source_words(),
            'search_form':
            SearchForm(),
            'replace_form':
            replace_form,
        })
Beispiel #36
0
def show_project(request, project):
    obj = get_project(request, project)

    dict_langs = Language.objects.filter(
        dictionary__project=obj
    ).annotate(Count('dictionary'))

    if request.method == 'POST' and can_edit_project(request.user, obj):
        settings_form = ProjectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!')
            )
    else:
        settings_form = ProjectSettingsForm(instance=obj)

    last_changes = Change.objects.for_project(obj)[:10]

    language_stats = sort_unicode(
        get_per_language_stats(obj), lambda tup: force_text(tup[0])
    )

    language_stats = [
        (
            tup[0],
            translation_percent(tup[1], tup[2]),
            translation_percent(tup[3], tup[4])
        )
        for tup in language_stats
    ]

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request,
        'project.html',
        {
            'allow_index': True,
            'object': obj,
            'project': obj,
            'dicts': dict_langs,
            'last_changes': last_changes,
            'last_changes_url': urlencode(
                {'project': obj.slug}
            ),
            'settings_form': settings_form,
            'language_stats': language_stats,
            'unit_count': Unit.objects.filter(
                translation__subproject__project=obj
            ).count(),
            'words_count': obj.get_total_words(),
            'language_count': Language.objects.filter(
                translation__subproject__project=obj
            ).distinct().count(),
            'strings_count': obj.get_total(),
            'source_words_count': obj.get_source_words(),
            'search_form': SearchForm(),
            'replace_form': replace_form,
        }
    )