Beispiel #1
0
    def getquicklinks(self):
        """gets a set of quick links to user's project-languages"""
        from pootle_app.models.permissions import check_profile_permission
        projects = self.projects.all()
        quicklinks = []
        for language in self.languages.iterator():
            langlinks = []
            if projects.count():
                for translation_project in language.translationproject_set.filter(project__in=self.projects.iterator()).iterator():
                    isprojectadmin = check_profile_permission(self, 'administrate',
                                                              translation_project.directory)

                    langlinks.append({
                        'code': translation_project.project.code,
                        'name': translation_project.project.fullname,
                        'isprojectadmin': isprojectadmin,
                        })

            islangadmin = check_profile_permission(self, 'administrate', language.directory)
            quicklinks.append({'code': language.code,
                               'name': language.localname(),
                               'islangadmin': islangadmin,
                               'projects': langlinks})
            quicklinks.sort(cmp=locale.strcoll, key=lambda dict: dict['name'])
        return quicklinks
Beispiel #2
0
    def getquicklinks(self):
        """Gets a set of quick links to user's project-languages."""
        from pootle_app.models.permissions import check_profile_permission
        projects = self.projects.all()
        quicklinks = []
        for language in self.languages.iterator():
            langlinks = []
            if projects.count():
                tps = language.translationproject_set.filter(
                    project__in=self.projects.iterator()).iterator()
                for translation_project in tps:
                    isprojectadmin = check_profile_permission(
                        self, 'administrate', translation_project.directory)

                    langlinks.append({
                        'code': translation_project.project.code,
                        'name': translation_project.project.fullname,
                        'isprojectadmin': isprojectadmin,
                    })

            islangadmin = check_profile_permission(self, 'administrate',
                                                   language.directory)
            quicklinks.append({
                'code': language.code,
                'name': language.localname(),
                'islangadmin': islangadmin,
                'projects': langlinks
            })
            quicklinks.sort(cmp=locale.strcoll, key=lambda dict: dict['name'])

        return quicklinks
Beispiel #3
0
def get_edit_unit(request, unit):
    """
    Given a store path C{pootle_path} and unit id C{uid}, gathers all the
    necessary information to build the editing widget.

    @return: A templatised editing widget is returned within the C{editor}
    variable and paging information is also returned if the page number has
    changed.
    """

    json = {}

    translation_project = request.translation_project
    language = translation_project.language

    if unit.hasplural():
        snplurals = len(unit.source.strings)
    else:
        snplurals = None
    form_class = unit_form_factory(language, snplurals)
    form = form_class(instance=unit)
    store = unit.store
    directory = store.parent
    profile = request.profile
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    suggestions, suggestion_details = get_sugg_list(unit)
    template_vars = {'unit': unit,
                     'form': form,
                     'store': store,
                     'directory': directory,
                     'profile': profile,
                     'user': request.user,
                     'language': language,
                     'source_language': translation_project.project.source_language,
                     'cantranslate': check_profile_permission(profile, "translate", directory),
                     'cansuggest': check_profile_permission(profile, "suggest", directory),
                     'canreview': check_profile_permission(profile, "review", directory),
                     'altsrcs': find_altsrcs(unit, alt_src_langs, store=store, project=project),
                     'suggestions': suggestions,
                     'suggestion_detail': suggestion_details,
    }

    if translation_project.project.is_terminology or store.is_terminology:
        t = loader.get_template('unit/term_edit.html')
    else:
        t = loader.get_template('unit/edit.html')
    c = RequestContext(request, template_vars)
    json['editor'] = t.render(c)
    t = loader.get_template('store/dircrumbs.html')
    json['dircrumbs'] = t.render(c)
    t = loader.get_template('store/storecrumbs.html')
    json['storecrumbs'] = t.render(c)

    rcode = 200
    # Return context rows if filtering is applied
    if _is_filtered(request) or request.GET.get('filter', 'all') != 'all':
        json['ctxt'] = _filter_ctxt_units(store.units, unit, 2)
    response = jsonify(json)
    return HttpResponse(response, status=rcode, mimetype="application/json")
def get_edit_unit(request, pootle_path, uid):
    """
    Given a store path C{pootle_path} and unit id C{uid}, gathers all the
    necessary information to build the editing widget.

    @return: A templatised editing widget is returned within the C{editor}
    variable and paging information is also returned if the page number has
    changed.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path

    unit = get_object_or_404(Unit, id=uid, store__pootle_path=pootle_path)
    translation_project = unit.store.translation_project
    language = translation_project.language
    form_class = unit_form_factory(language, len(unit.source.strings))
    form = form_class(instance=unit)
    store = unit.store
    directory = store.parent
    profile = get_profile(request.user)
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    template_vars = {'unit': unit,
                     'form': form,
                     'store': store,
                     'profile': profile,
                     'user': request.user,
                     'language': language,
                     'source_language': translation_project.project.source_language,
                     'cantranslate': check_profile_permission(profile, "translate", directory),
                     'cansuggest': check_profile_permission(profile, "suggest", directory),
                     'canreview': check_profile_permission(profile, "review", directory),
                     'altsrcs': find_altsrcs(unit, alt_src_langs, store=store, project=project),
                     'suggestions': get_sugg_list(unit)}

    t = loader.get_template('unit/edit.html')
    c = RequestContext(request, template_vars)
    json = {'success': True,
            'editor': t.render(c)}

    current_page = int(request.GET.get('page', 1))
    all_units = unit.store.units
    units_qs = _filter_queryset(request.GET, all_units)
    unit_rows = profile.get_unit_rows()
    current_unit = unit
    if current_unit is not None:
        current_index = _get_index_in_qs(units_qs, current_unit)
        preceding = units_qs[:current_index].count()
        page = preceding / unit_rows + 1
        if page != current_page:
            pager = paginate(request, units_qs, items=unit_rows, page=page)
            json["pager"] = _build_pager_dict(pager)
        # Return context rows if filtering is applied
        if 'filter' in request.GET and request.GET.get('filter', 'all') != 'all':
            edit_index = _get_index_in_qs(all_units, current_unit)
            json["ctxt"] = _filter_ctxt_units(all_units, edit_index, 2)

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
def get_view_units(request, pootle_path, limit=0):
    """
    @return: An object in JSON notation that contains the source and target
    texts for units that will be displayed before and after unit C{uid}.

    Success status that indicates if the unit has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}
    page = request.GET.get('page', 1)

    try:
        store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _("You do not have rights to access translation mode.")
        else:
            if not limit:
                limit = profile.get_unit_rows()
            units_qs = _filter_queryset(request.GET, store.units)
            json["units"] = _filter_view_units(units_qs, int(page), int(limit))
            json["success"] = True
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #6
0
def create_notice(creator, message, directory):
    profile = get_profile(creator)
    if not check_profile_permission(profile, 'administrate', directory):
        raise PermissionDenied
    new_notice = Notice(directory=directory, message=message)
    new_notice.save()
    return new_notice
def reject_qualitycheck(request, uid, checkid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        if not check_profile_permission(get_profile(request.user), 'review', directory):
            json["success"] = False
            json["msg"] = _("You do not have rights to access review mode.")
        else:
            json["udbid"] = uid
            json["checkid"] = checkid
            if request.POST.get('reject'):
                try:
                    check = unit.qualitycheck_set.get(id=checkid)
                    check.false_positive = True
                    check.save()
                    # update timestamp
                    unit.save()
                    json['success'] = True
                except ObjectDoesNotExist:
                    check = None
                    json['success'] = False
                    json["msg"] = _("Check %(checkid)s does not exist." %
                                    {'checkid': checkid})
    except Unit.DoesNotExist:
        json['success'] = False
        json["msg"] = _("Unit %(uid)s does not exist." %
                        {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #8
0
def reject_suggestion(request, uid, suggid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    translation_project = unit.store.translation_project

    response = {
        'udbid': unit.id,
        'sugid': suggid,
    }
    if request.POST.get('reject'):
        try:
            sugg = unit.suggestion_set.get(id=suggid)
        except ObjectDoesNotExist:
            sugg = None

        profile = get_profile(request.user)
        if not check_profile_permission(profile, 'review', directory) and \
               (not request.user.is_authenticated() or sugg and sugg.user != profile):
            raise PermissionDenied

        response['success'] = unit.reject_suggestion(suggid)

        if sugg is not None and response['success']:
            #FIXME: we need a totally different model for tracking stats, this is just lame
            suggstat, created = SuggestionStat.objects.get_or_create(
                translation_project=translation_project,
                suggester=sugg.user,
                state='pending',
                unit=unit.id)
            suggstat.reviewer = get_profile(request.user)
            suggstat.state = 'rejected'
            suggstat.save()

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #9
0
def reject_qualitycheck(request, uid, checkid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    if not check_profile_permission(
        get_profile(request.user), 'review', directory):
        raise PermissionDenied

    response = {
        'udbid': unit.id,
        'checkid': checkid,
        }
    if request.POST.get('reject'):
        try:
            check = unit.qualitycheck_set.get(id=checkid)
            check.false_positive = True
            check.save()
            # update timestamp
            unit.save()
            response['success'] = True
        except ObjectDoesNotExist:
            check = None
            response['success'] = False

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #10
0
def get_view_units(request, pootle_path, limit=0):
    """
    @return: An object in JSON notation that contains the source and target
    texts for units that will be displayed before and after unit C{uid}.

    Success status that indicates if the unit has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}
    page = request.GET.get('page', 1)

    try:
        store = Store.objects.select_related(
            'translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _(
                "You do not have rights to access translation mode.")
        else:
            if not limit:
                limit = profile.get_unit_rows()
            units_qs = _filter_queryset(request.GET, store.units)
            json["units"] = _filter_view_units(units_qs, int(page), int(limit))
            json["success"] = True
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #11
0
def reject_qualitycheck(request, uid, checkid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    if not check_profile_permission(get_profile(request.user), 'review',
                                    directory):
        raise PermissionDenied

    response = {
        'udbid': unit.id,
        'checkid': checkid,
    }
    if request.POST.get('reject'):
        try:
            check = unit.qualitycheck_set.get(id=checkid)
            check.false_positive = True
            check.save()
            # update timestamp
            unit.save()
            response['success'] = True
        except ObjectDoesNotExist:
            check = None
            response['success'] = False

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #12
0
def reject_suggestion(request, uid, suggid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    translation_project = unit.store.translation_project

    response = {
        'udbid': unit.id,
        'sugid': suggid,
        }
    if request.POST.get('reject'):
        try:
            sugg = unit.suggestion_set.get(id=suggid)
        except ObjectDoesNotExist:
            sugg = None

        profile = get_profile(request.user)
        if not check_profile_permission(profile, 'review', directory) and \
               (not request.user.is_authenticated() or sugg and sugg.user != profile):
            raise PermissionDenied

        response['success'] = unit.reject_suggestion(suggid)

        if sugg is not None and response['success']:
            #FIXME: we need a totally different model for tracking stats, this is just lame
            suggstat, created = SuggestionStat.objects.get_or_create(translation_project=translation_project,
                                                            suggester=sugg.user,
                                                            state='pending',
                                                            unit=unit.id)
            suggstat.reviewer = get_profile(request.user)
            suggstat.state = 'rejected'
            suggstat.save()

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #13
0
def reject_qualitycheck(request, uid, checkid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        if not check_profile_permission(get_profile(request.user), 'review',
                                        directory):
            json["success"] = False
            json["msg"] = _("You do not have rights to access review mode.")
        else:
            json["udbid"] = uid
            json["checkid"] = checkid
            if request.POST.get('reject'):
                try:
                    check = unit.qualitycheck_set.get(id=checkid)
                    check.false_positive = True
                    check.save()
                    # update timestamp
                    unit.save()
                    json['success'] = True
                except ObjectDoesNotExist:
                    check = None
                    json['success'] = False
                    json["msg"] = _("Check %(checkid)s does not exist." %
                                    {'checkid': checkid})
    except Unit.DoesNotExist:
        json['success'] = False
        json["msg"] = _("Unit %(uid)s does not exist." % {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #14
0
def create_notice(creator, message, directory):
    profile = get_profile(creator)
    if not check_profile_permission(profile, 'administrate', directory):
        raise PermissionDenied
    new_notice = Notice(directory=directory, message=message)
    new_notice.save()
    return new_notice
def get_tp_metadata(request, pootle_path, uid=None):
    """
    @return: An object in JSON notation that contains the metadata information
    about the current translation project: source/target language codes,
    the direction of the text and also a initial pager.

    Success status that indicates if the information has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}

    try:
        store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _("You do not have rights to access translation mode.")
        else:
            units_qs = _filter_queryset(request.GET, store.units)
            unit_rows = profile.get_unit_rows()

            try:
                if uid is None:
                    try:
                        current_unit = units_qs[0]
                        json["uid"] = units_qs[0].id
                    except IndexError:
                        current_unit = None
                else:
                    current_unit = units_qs.get(id=uid, store__pootle_path=pootle_path)
                if current_unit is not None:
                    current_index = _get_index_in_qs(units_qs, current_unit)
                    preceding = units_qs[:current_index].count()
                    page = preceding / unit_rows + 1
                    pager = paginate(request, units_qs, items=unit_rows, page=page)
                    json["pager"] = _build_pager_dict(pager)
                tp = store.translation_project
                json["meta"] = {"source_lang": tp.project.source_language.code,
                                "source_dir": tp.project.source_language.get_direction(),
                                "target_lang": tp.language.code,
                                "target_dir": tp.language.get_direction()}
                json["success"] = True
            except Unit.DoesNotExist:
                json["success"] = False
                json["msg"] = _("Unit %(uid)s does not exist on %(path)s." %
                                {'uid': uid, 'path': pootle_path})
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #16
0
def profile_edit(request):
    can_view = check_profile_permission(get_profile(request.user), "view",
                                        Directory.objects.root)

    if can_view:
        excluded = ('user',)
    else:
        excluded = ('user', 'projects')

    return edit_profile(request, form_class=PootleProfileForm,
                        extra_form_args={'exclude_fields': excluded})
Beispiel #17
0
def profile_edit(request):
    can_view = check_profile_permission(get_profile(request.user), "view",
                                        Directory.objects.root)

    if can_view:
        excluded = ('user', )
    else:
        excluded = ('user', 'projects')

    return edit_profile(request,
                        form_class=PootleProfileForm,
                        extra_form_args={'exclude_fields': excluded})
Beispiel #18
0
def get_failing_checks(request, pootle_path):
    """
    Gets a list of failing checks for the current query.

    @return: JSON string representing action status and depending on success,
    returns an error message or a list containing the the name and number of
    failing checks.
    """
    pass
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}

    try:
        store = Store.objects.select_related(
            'translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _(
                "You do not have rights to access translation mode.")
        else:
            # Borrowed from pootle_app.views.language.item_dict.getcheckdetails
            checkopts = []
            try:
                property_stats = store.getcompletestats()
                quick_stats = store.getquickstats()
                total = quick_stats['total']
                keys = property_stats.keys()
                keys.sort()
                for checkname in keys:
                    checkcount = property_stats[checkname]
                    if total and checkcount:
                        stats = ungettext('%(checkname)s (%(checks)d)',
                                          '%(checkname)s (%(checks)d)',
                                          checkcount, {
                                              "checks": checkcount,
                                              "checkname": checkname
                                          })
                        checkopt = {'name': checkname, 'text': stats}
                        checkopts.append(checkopt)
                json["checks"] = checkopts
                json["success"] = True
            except IOError:
                json["success"] = False
                json["msg"] = _("Input/Output error.")
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #19
0
def accept_suggestion(request, uid, suggid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    translation_project = unit.store.translation_project

    if not check_profile_permission(
        get_profile(request.user), 'review', directory):
        raise PermissionDenied

    response = {
        'udbid': unit.id,
        'sugid': suggid,
        }

    if request.POST.get('accept'):
        try:
            suggestion = unit.suggestion_set.get(id=suggid)
        except ObjectDoesNotExist:
            suggestion = None

        response['success'] = unit.accept_suggestion(suggid)
        response['newtargets'] = [
            highlight_whitespace(target) for target in unit.target.strings]
        response['newdiffs'] = {}
        for sugg in unit.get_suggestions():
            response['newdiffs'][sugg.id] = [
                highlight_diffs(unit.target.strings[i], target) \
                for i, target in enumerate(sugg.target.strings)]

        if suggestion is not None and response['success']:
            if suggestion.user:
                translation_submitted.send(
                    sender=translation_project, unit=unit,
                    profile=suggestion.user)
            # FIXME: we need a totally different model for tracking
            # stats, this is just lame
            suggstat, created = SuggestionStat.objects.get_or_create(
                translation_project=translation_project,
                suggester=suggestion.user,
                state='pending',
                unit=unit.id)
            suggstat.reviewer = get_profile(request.user)
            suggstat.state = 'accepted'
            suggstat.save()

            sub = Submission(translation_project=translation_project,
                             submitter=get_profile(request.user),
                             from_suggestion=suggstat)
            sub.save()

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #20
0
def accept_suggestion(request, uid, suggid):
    unit = get_object_or_404(Unit, id=uid)
    directory = unit.store.parent
    translation_project = unit.store.translation_project

    if not check_profile_permission(get_profile(request.user), 'review',
                                    directory):
        raise PermissionDenied

    response = {
        'udbid': unit.id,
        'sugid': suggid,
    }

    if request.POST.get('accept'):
        try:
            suggestion = unit.suggestion_set.get(id=suggid)
        except ObjectDoesNotExist:
            suggestion = None

        response['success'] = unit.accept_suggestion(suggid)
        response['newtargets'] = [
            highlight_whitespace(target) for target in unit.target.strings
        ]
        response['newdiffs'] = {}
        for sugg in unit.get_suggestions():
            response['newdiffs'][sugg.id] = [highlight_diffs(unit.target.strings[i], target) \
                                             for i, target in enumerate(sugg.target.strings)]

        if suggestion is not None and response['success']:
            if suggestion.user:
                translation_submitted.send(sender=translation_project,
                                           unit=unit,
                                           profile=suggestion.user)
            #FIXME: we need a totally different model for tracking stats, this is just lame
            suggstat, created = SuggestionStat.objects.get_or_create(
                translation_project=translation_project,
                suggester=suggestion.user,
                state='pending',
                unit=unit.id)
            suggstat.reviewer = get_profile(request.user)
            suggstat.state = 'accepted'
            suggstat.save()

            sub = Submission(translation_project=translation_project,
                             submitter=get_profile(request.user),
                             from_suggestion=suggstat)
            sub.save()

    response = simplejson.dumps(response)
    return HttpResponse(response, mimetype="application/json")
Beispiel #21
0
def accept_suggestion(request, uid, suggid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        translation_project = unit.store.translation_project
        profile = get_profile(request.user)

        if not check_profile_permission(profile, 'review', directory):
            json["success"] = False
            json["msg"] = _("You do not have rights to access review mode.")
        else:
            json["udbid"] = unit.id
            json["sugid"] = suggid
            if request.POST.get('accept'):
                try:
                    sugg = unit.suggestion_set.get(id=suggid)
                except ObjectDoesNotExist:
                    sugg = None

                json['success'] = unit.accept_suggestion(suggid)
                json['newtargets'] = [
                    highlight_whitespace(target)
                    for target in unit.target.strings
                ]
                json['newdiffs'] = {}
                for sugg in unit.get_suggestions():
                    json['newdiffs'][sugg.id] = [highlight_diffs(unit.target.strings[i], target) \
                                                     for i, target in enumerate(sugg.target.strings)]

                if sugg is not None and json['success']:
                    #FIXME: we need a totally different model for tracking stats, this is just lame
                    suggstat, created = SuggestionStat.objects.get_or_create(
                        translation_project=translation_project,
                        suggester=sugg.user,
                        state='pending',
                        unit=unit.id)
                    suggstat.reviewer = profile
                    suggstat.state = 'accepted'
                    suggstat.save()

                    sub = Submission(translation_project=translation_project,
                                     submitter=profile,
                                     from_suggestion=suggstat)
                    sub.save()
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist." % {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #22
0
def render_latest_news(context, path, num):
    try:
        directory = Directory.objects.get(pootle_path='/%s' % path)
        user = context['user']
        can_view = check_profile_permission(get_profile(user), "view", directory)
        if not can_view:
            directory = None
    except Directory.DoesNotExist:
        directory = None

    if directory is None:
        return {'news_items': None}
    news_items = Notice.objects.filter(directory=directory)[:num]
    return {'news_items': news_items}
Beispiel #23
0
def get_pootle_profile_form(request):
    """return a profile form suitable for creating/editing PootleProfile"""
    can_view = check_profile_permission(get_profile(request.user), "view", Directory.objects.root)

    if can_view:
        excluded = ('user',)
    else:
        excluded = ('user', 'projects')

    class PootleProfileForm(ModelForm):
        class Meta:
            model = PootleProfile
            exclude = excluded
    return PootleProfileForm
Beispiel #24
0
def get_pootle_profile_form(request):
    """return a profile form suitable for creating/editing PootleProfile"""
    can_view = check_profile_permission(get_profile(request.user), "view", Directory.objects.root)

    if can_view:
        excluded = ('user',)
    else:
        excluded = ('user', 'projects')

    class PootleProfileForm(ModelForm):
        class Meta:
            model = PootleProfile
            exclude = excluded
    return PootleProfileForm
def get_failing_checks(request, pootle_path):
    """
    Gets a list of failing checks for the current query.

    @return: JSON string representing action status and depending on success,
    returns an error message or a list containing the the name and number of
    failing checks.
    """
    pass
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}

    try:
        store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _("You do not have rights to access translation mode.")
        else:
            # Borrowed from pootle_app.views.language.item_dict.getcheckdetails
            checkopts = []
            try:
                property_stats = store.getcompletestats()
                quick_stats = store.getquickstats()
                total = quick_stats['total']
                keys = property_stats.keys()
                keys.sort()
                for checkname in keys:
                    checkcount = property_stats[checkname]
                    if total and checkcount:
                        stats = ungettext('%(checkname)s (%(checks)d)',
                                          '%(checkname)s (%(checks)d)', checkcount,
                                          {"checks": checkcount, "checkname": checkname})
                        checkopt = {'name': checkname,
                                    'text': stats}
                        checkopts.append(checkopt)
                json["checks"] = checkopts
                json["success"] = True
            except IOError:
                json["success"] = False
                json["msg"] = _("Input/Output error.")
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #26
0
def render_latest_news(context, path, num):
    try:
        directory = Directory.objects.get(pootle_path='/%s' % path)
        user = context['user']
        can_view = check_profile_permission(get_profile(user), "view",
                                            directory)
        if not can_view:
            directory = None
    except Directory.DoesNotExist:
        directory = None

    if directory is None:
        return {'news_items': None}
    news_items = Notice.objects.filter(directory=directory)[:num]
    return {'news_items': news_items}
def accept_suggestion(request, uid, suggid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        translation_project = unit.store.translation_project
        profile = get_profile(request.user)

        if not check_profile_permission(profile, 'review', directory):
            json["success"] = False
            json["msg"] = _("You do not have rights to access review mode.")
        else:
            json["udbid"] = unit.id
            json["sugid"] = suggid
            if request.POST.get('accept'):
                try:
                    sugg = unit.suggestion_set.get(id=suggid)
                except ObjectDoesNotExist:
                    sugg = None

                json['success'] = unit.accept_suggestion(suggid)
                json['newtargets'] = [highlight_whitespace(target) for target in unit.target.strings]
                json['newdiffs'] = {}
                for sugg in unit.get_suggestions():
                    json['newdiffs'][sugg.id] = [highlight_diffs(unit.target.strings[i], target) \
                                                     for i, target in enumerate(sugg.target.strings)]

                if sugg is not None and json['success']:
                    #FIXME: we need a totally different model for tracking stats, this is just lame
                    suggstat, created = SuggestionStat.objects.get_or_create(translation_project=translation_project,
                                                                    suggester=sugg.user,
                                                                    state='pending',
                                                                    unit=unit.id)
                    suggstat.reviewer = profile
                    suggstat.state = 'accepted'
                    suggstat.save()

                    sub = Submission(translation_project=translation_project,
                                     submitter=profile,
                                     from_suggestion=suggstat)
                    sub.save()
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist." %
                        {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #28
0
def get_recipients(restrict_to_active_users, directory):
    to_list = PootleProfile.objects.all()

    # Take into account 'only active users' flag from the form.
    if restrict_to_active_users:
        to_list = to_list.exclude(submission=None).exclude(suggestion=None).exclude(suggester=None)

    recipients = []
    for person in to_list:
        # Check if the User profile has permissions in the directory.
        if not check_profile_permission(person, "view", directory):
            continue

        if person.user.email:
            recipients.append(person.user.email)

    return recipients
Beispiel #29
0
def get_recipients(restrict_to_active_users, directory):
    to_list = PootleProfile.objects.all()

    # Take into account 'only active users' flag from the form.
    if restrict_to_active_users:
        to_list = to_list.exclude(submission=None).exclude(suggestion=None) \
                                                  .exclude(suggester=None)

    recipients = []
    for person in to_list:
        # Check if the User profile has permissions in the directory.
        if not check_profile_permission(person, 'view', directory):
            continue

        if person.user.email:
            recipients.append(person.user.email)

    return recipients
Beispiel #30
0
def get_more_context(request, pootle_path, uid):
    """
    @return: An object in JSON notation that contains the source and target
    texts for units that are in context of unit C{uid}.

    Success status that indicates if the unit has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}
    gap = int(request.GET.get('gap', 0))

    try:
        store = Store.objects.select_related(
            'translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _(
                "You do not have rights to access translation mode.")
        else:
            try:
                units_qs = store.units
                current_unit = units_qs.get(id=uid,
                                            store__pootle_path=pootle_path)
                edit_index = _get_index_in_qs(units_qs, current_unit)
                json["ctxt"] = _filter_ctxt_units(units_qs, edit_index, 2, gap)
                json["success"] = True
            except Unit.DoesNotExist:
                json["success"] = False
                json["msg"] = _("Unit %(uid)s does not exist on %(path)s." % {
                    'uid': uid,
                    'path': pootle_path
                })
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #31
0
def reject_suggestion(request, uid, suggid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        translation_project = unit.store.translation_project

        json["udbid"] = uid
        json["sugid"] = suggid
        if request.POST.get('reject'):
            try:
                sugg = unit.suggestion_set.get(id=suggid)
            except ObjectDoesNotExist:
                sugg = None

            profile = get_profile(request.user)
            if not check_profile_permission(profile, 'review', directory) and \
                   (not request.user.is_authenticated() or sugg and sugg.user != profile):
                json["success"] = False
                json["msg"] = _(
                    "You do not have rights to access review mode.")
            else:
                json['success'] = unit.reject_suggestion(suggid)
                if sugg is not None and json['success']:
                    #FIXME: we need a totally different model for tracking stats, this is just lame
                    suggstat, created = SuggestionStat.objects.get_or_create(
                        translation_project=translation_project,
                        suggester=sugg.user,
                        state='pending',
                        unit=unit.id)
                    suggstat.reviewer = get_profile(request.user)
                    suggstat.state = 'rejected'
                    suggstat.save()
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist." % {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
def reject_suggestion(request, uid, suggid):
    json = {}
    try:
        unit = Unit.objects.get(id=uid)
        directory = unit.store.parent
        translation_project = unit.store.translation_project

        json["udbid"] = uid
        json["sugid"] = suggid
        if request.POST.get('reject'):
            try:
                sugg = unit.suggestion_set.get(id=suggid)
            except ObjectDoesNotExist:
                sugg = None

            profile = get_profile(request.user)
            if not check_profile_permission(profile, 'review', directory) and \
                   (not request.user.is_authenticated() or sugg and sugg.user != profile):
                json["success"] = False
                json["msg"] = _("You do not have rights to access review mode.")
            else:
                json['success'] = unit.reject_suggestion(suggid)
                if sugg is not None and json['success']:
                    #FIXME: we need a totally different model for tracking stats, this is just lame
                    suggstat, created = SuggestionStat.objects.get_or_create(translation_project=translation_project,
                                                                    suggester=sugg.user,
                                                                    state='pending',
                                                                    unit=unit.id)
                    suggstat.reviewer = get_profile(request.user)
                    suggstat.state = 'rejected'
                    suggstat.save()
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist." %
                        {'uid': uid})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
def get_more_context(request, pootle_path, uid):
    """
    @return: An object in JSON notation that contains the source and target
    texts for units that are in context of unit C{uid}.

    Success status that indicates if the unit has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}
    gap = int(request.GET.get('gap', 0))

    try:
        store = Store.objects.select_related('translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _("You do not have rights to access translation mode.")
        else:
            try:
                units_qs = store.units
                current_unit = units_qs.get(id=uid, store__pootle_path=pootle_path)
                edit_index = _get_index_in_qs(units_qs, current_unit)
                json["ctxt"] = _filter_ctxt_units(units_qs, edit_index, 2, gap)
                json["success"] = True
            except Unit.DoesNotExist:
                json["success"] = False
                json["msg"] = _("Unit %(uid)s does not exist on %(path)s." %
                                {'uid': uid, 'path': pootle_path})
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #34
0
def handle_form(request, current_directory, current_project, current_language, template_vars):

    current_project_pk = None
    if current_project != None:
        current_project_pk = current_project.pk
        
    current_language_pk = None
    if current_language != None:
        current_language_pk = current_language.pk
    
    # Check if the user submitted the form    
    if request.method == 'POST':

        # Reconstruct the NoticeForm with the user data.
        form = NoticeForm(request.POST)
        template_vars['notices_published'] = None

        # Basic validation, only proceed if the form data is valid.
        if form.is_valid():
            
            # Lets save this NoticeForm as a Notice (an RSS item on the website)
            # if it is requsted we do that - ie 'publish_rss' is true.
            if form.cleaned_data['publish_rss'] == True:
            
                proj_filter = Q()
                lang_filter = Q()
                # Find the Projects we want to publish this news to.
                if form.cleaned_data['project_all'] == True:
                    projs = Project.objects.all()
                else:
                    projs = form.cleaned_data['project_selection']

                # Find the Languages we want to publish this news to.
                if form.cleaned_data['language_all'] == True:
                    langs = Language.objects.all()
                else:
                    langs = form.cleaned_data['language_selection']
                # construct the language OR filter
                for lang in langs:
                    lang_filter|=Q(language__exact=lang)

                #
                # We use all the projects that we want to publish this News to.
                #
                # For each project, depending on language selection, publish news into that Directory
                #
                for p in projs:
                    # If the user selected no language, and not "every lang", then just use the project's directory.    
                    if form.cleaned_data['language_selection'] == [] and form.cleaned_data['language_all'] == False:
                        # Publish this Notice, using the project's Directory object
                        new_notice = Notice()
                        new_notice.message = form.cleaned_data['message']
                        new_notice.directory = p.directory
                        new_notice.save()

                        if template_vars['notices_published'] == None:
                            template_vars['notices_published'] = []
                        template_vars['notices_published'].append("Published to Project %s" % p.fullname)
                            
                    else:
                        # Find the languages we want to restrict publishing News to, for this particular Project.
                        # Lets find the TranslationProject to find the directory object to use.
                        translationprojects_to_publish_to = TranslationProject.objects.filter(lang_filter,project__exact=p).distinct()
                        for tp in translationprojects_to_publish_to:
                            # Publish this Notice, using the translation project's Directory obejct
                            new_notice = Notice()
                            new_notice.message = form.cleaned_data['message']
                            new_notice.directory = tp.directory
                            new_notice.save()

                            if template_vars['notices_published'] == None:
                                template_vars['notices_published'] = []
                            template_vars['notices_published'].append("Published to Translation Project %s" % tp.fullname)

                #
                # We use all the languages that we want to publish this News to, and for each lang, publish news into that Directory
                # We only need to check if the user selected no projects - the case of selected projects and languages is covered above.

                # If the user selected no project, and not "every proj", then just use the languages's directory.   
                if form.cleaned_data['project_selection'] == [] and form.cleaned_data['project_all'] == False:
                    for l in langs:
                        # Publish this Notice, using the languages's Directory object
                        new_notice = Notice()
                        new_notice.message = form.cleaned_data['message']
                        new_notice.directory = l.directory
                        new_notice.save()

                        if template_vars['notices_published'] == None:
                            template_vars['notices_published'] = []
                        template_vars['notices_published'].append("Published to Language %s" % l.fullname)
                            

            # If we want to email it , then do that.
            if form.cleaned_data['send_email'] == True:

                email_header = form.cleaned_data['email_header']
                proj_filter = Q()
                lang_filter = Q()
                # Find users to send email too, based on project
                if form.cleaned_data['project_all'] == True:
                    projs = Project.objects.all()
                else:
                    projs = form.cleaned_data['project_selection']
                # Construct the project OR filter
                for proj in projs:
                    proj_filter|=Q(projects__exact=proj)

                # Find users to send email too, based on language
                if form.cleaned_data['language_all'] == True:
                    langs = Language.objects.all()
                else:
                    langs = form.cleaned_data['language_selection']
                # construct the language OR filter
                for lang in langs:
                    lang_filter|=Q(languages__exact=lang)
            
                # Generate a list of pootleprofile objects, which are linked to Users and their emails. 
                #

                # Take into account 'only active users' flag from the form.
                if form.cleaned_data['restrict_to_active_users'] == True:
                    to_list = PootleProfile.objects.filter(lang_filter,proj_filter).distinct().exclude(submission=None).exclude(suggestion=None).exclude(suggester=None)
                else:
                    # Grab all appropriate Profiles.
                    to_list = PootleProfile.objects.filter(lang_filter,proj_filter).distinct()

                to_list_emails = []
                for person in to_list:
                    #Check if the User object here as permissions
                    if not check_profile_permission(person, 'view', form.cleaned_data['directory']):
                        continue
                    if person.user.email != '':
                        to_list_emails.append(person.user.email)        
                        if template_vars['notices_published'] == None:
                            template_vars['notices_published'] = []
                        template_vars['notices_published'].append("Sent an email to %s" % person.user.email)
    
                # The rest of the email settings 
                from_email = DEFAULT_FROM_EMAIL
                message = form.cleaned_data['message']

                # Send the email to the list of people
                send_mail(email_header, message, from_email, to_list_emails, fail_silently=True)        

        # Finally return a blank Form to allow user to continue publishing notices
        # with our defaults
        form = NoticeForm(initial = noticeform_initial_dict(current_directory,\
                current_project_pk, current_language_pk) )

    else:
        # Not a POST method. Return a default starting state of the form
        form = NoticeForm(initial = noticeform_initial_dict(current_directory,\
                current_project_pk, current_language_pk) )

    return form
Beispiel #35
0
def handle_form(request, current_directory, current_project, current_language, template_vars):
    # Check if the user submitted the form
    if request.method != "POST":
        # Not a POST method. Return a default starting state of the form
        form = form_factory(current_directory)()
        return form

    # Reconstruct the NoticeForm with the user data.
    form = form_factory(current_directory)(request.POST)
    if not form.is_valid():
        return form

    message = form.cleaned_data["message"]
    languages = form.cleaned_data.get("language_selection", [])
    projects = form.cleaned_data.get("project_selection", [])
    publish_dirs = []
    template_vars["notices_published"] = []

    # Figure out which directories, projects, and languages are involved
    if current_language and current_project:
        # The current translation project
        publish_dirs = [current_directory]
    elif current_language:
        languages = [current_language]
        if form.cleaned_data["project_all"] == True:
            # The current language
            publish_dirs = [current_language.directory]
        else:
            # Certain projects in the current language
            translation_projects = TranslationProject.objects.filter(language=current_language, project__in=projects)
            publish_dirs = [tp.directory for tp in translation_projects]
    elif current_project:
        projects = [current_project]
        if form.cleaned_data["language_all"] == True:
            # The current project
            publish_dirs = [current_project.directory]
        else:
            # Certain languages in the current project
            translation_projects = TranslationProject.objects.filter(language__in=languages, project=current_project)
            publish_dirs = [tp.directory for tp in translation_projects]
    else:
        # The form is top-level (server-wide)
        if form.cleaned_data["project_all"] == True:
            if form.cleaned_data["language_all"] == True:
                # Publish at server root
                publish_dirs = [current_directory]
            else:
                # Certain languages
                publish_dirs = [l.directory for l in languages]
        else:
            if form.cleaned_data["language_all"] == True:
                # Certain projects
                publish_dirs = [p.directory for p in projects]
            else:
                # Specific translation projects
                translation_projects = TranslationProject.objects.filter(language__in=languages, project__in=projects)
                publish_dirs = [tp.directory for tp in translation_projects]

    # RSS (notices)
    if form.cleaned_data["publish_rss"] == True:
        for d in publish_dirs:
            create_notice(request.user, message, d)
        # template_vars['notices_published'].append(ungettext(
        #        "Published %d news item",
        #        "Published %d news items",
        #        len(publish_dirs),
        #        len(publish_dirs),
        # ))

    # E-mail
    if form.cleaned_data["send_email"] == True:
        email_header = form.cleaned_data["email_header"]
        if languages:
            lang_filter = Q(languages__in=languages)
        else:
            lang_filter = Q(languages__isnull=False)
        if projects:
            proj_filter = Q(projects__in=projects)
        else:
            proj_filter = Q(projects__isnull=False)

        to_list = PootleProfile.objects.filter(lang_filter, proj_filter)
        to_list = to_list.distinct()
        # Take into account 'only active users' flag from the form.
        if form.cleaned_data["restrict_to_active_users"] == True:
            to_list = to_list.exclude(submission=None)
            to_list = to_list.exclude(suggestion=None)
            to_list = to_list.exclude(suggester=None)

        to_list_emails = []
        for person in to_list:
            # Check if the User object here as permissions
            directory = form.cleaned_data["directory"]
            if not check_profile_permission(person, "view", directory):
                continue
            if person.user.email != "":
                to_list_emails.append(person.user.email)
                # template_vars['notices_published'].append(
                #        _("Sent an email to %s", person.user.email)
                # )

        # The rest of the email settings
        from_email = DEFAULT_FROM_EMAIL

        # Send the email to the list of people
        send_mail(email_header, message, from_email, to_list_emails, fail_silently=True)

    if not template_vars["notices_published"]:
        template_vars["notices_published"] = None

    form = form_factory(current_directory)()

    return form
def process_submit(request, pootle_path, uid, type):
    """
    @return: An object in JSON notation that contains the previous
    and last units for the unit next to unit C{uid}.

    This object also contains success status that indicates if the submission
    has been succesfully saved or not.
    """
    json = {}
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path

    try:
        unit = Unit.objects.get(id=uid, store__pootle_path=pootle_path)
        directory = unit.store.parent
        profile = get_profile(request.user)
        cantranslate = check_profile_permission(profile, "translate", directory)
        cansuggest = check_profile_permission(profile, "suggest", directory)
        if type == 'submission' and not cantranslate or \
           type == 'suggestion' and not cansuggest:
            json["success"] = False
            json["msg"] = _("You do not have rights to access translation mode.")
        else:
            translation_project = unit.store.translation_project
            language = translation_project.language
            form_class = unit_form_factory(language, len(unit.source.strings))
            form = form_class(request.POST, instance=unit)
            if form.is_valid():
                if type == 'submission':
                    if form.instance._target_updated or \
                       form.instance._translator_comment_updated or \
                       form.instance._state_updated:
                        form.save()
                        sub = Submission(translation_project=translation_project,
                                         submitter=get_profile(request.user))
                        sub.save()
                elif type == 'suggestion':
                    if form.instance._target_updated:
                        #HACKISH: django 1.2 stupidly modifies instance on
                        # model form validation, reload unit from db
                        unit = Unit.objects.get(id=unit.id)
                        sugg = unit.add_suggestion(form.cleaned_data['target_f'], get_profile(request.user))
                        if sugg:
                            SuggestionStat.objects.get_or_create(translation_project=translation_project,
                                                                 suggester=get_profile(request.user),
                                                                 state='pending', unit=unit.id)

                current_page = int(request.POST.get('page', 1))
                all_units = unit.store.units
                units_qs = _filter_queryset(request.POST, all_units)
                unit_rows = profile.get_unit_rows()
                current_unit = unit
                if current_unit is not None:
                    current_index = _get_index_in_qs(units_qs, current_unit)
                    preceding = units_qs[:current_index].count()
                    page = preceding / unit_rows + 1
                    if page != current_page:
                        pager = paginate(request, units_qs, items=unit_rows, page=page)
                        json["pager"] = _build_pager_dict(pager)
                    try:
                        new_index = current_index + 1
                        json["new_uid"] = units_qs[new_index].id
                    except IndexError:
                        # End of set: let's assume the new unit is the last we had
                        new_unit = unit
                        json["new_uid"] = None
                    json["success"] = True
            else:
                # Form failed
                json["success"] = False
                json["msg"] = _("Failed to process submit.")
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist on %(path)s." %
                        {'uid': uid, 'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #37
0
def handle_form(request, current_directory, current_project,
                current_language, template_vars):
    if request.method != 'POST':
        # Not a POST method. Return a default starting state of the form
        return form_factory(current_directory)()

    # Reconstruct the NoticeForm with the user data.
    form = form_factory(current_directory)(request.POST)
    if not form.is_valid():
        return form

    message = form.cleaned_data['message']
    languages = form.cleaned_data.get('language_selection', [])
    projects = form.cleaned_data.get('project_selection', [])
    publish_dirs = []
    template_vars['notices_published'] = []

    # Figure out which directories, projects, and languages are involved
    if current_language and current_project:
        # The current translation project
        publish_dirs = [current_directory]
        languages = [current_language]
        projects = [current_project]
    elif current_language:
        languages = [current_language]
        if form.cleaned_data['project_all']:
            # The current language
            publish_dirs = [current_language.directory]
        else:
            # Certain projects in the current language
            translation_projects = TranslationProject.objects.filter(
                    language=current_language, project__in=projects)
            publish_dirs = [tp.directory for tp in translation_projects]
    elif current_project:
        projects = [current_project]
        if form.cleaned_data['language_all']:
            # The current project
            publish_dirs = [current_project.directory]
        else:
            # Certain languages in the current project
            translation_projects = TranslationProject.objects.filter(
                    language__in=languages, project=current_project)
            publish_dirs = [tp.directory for tp in translation_projects]
    else:
        # The form is top-level (server-wide)
        if form.cleaned_data['project_all']:
            if form.cleaned_data['language_all']:
                # Publish at server root
                publish_dirs = [current_directory]
            else:
                # Certain languages
                publish_dirs = [l.directory for l in languages]
        else:
            if form.cleaned_data['language_all']:
                # Certain projects
                publish_dirs = [p.directory for p in projects]
            else:
                # Specific translation projects
                translation_projects = TranslationProject.objects.filter(
                        language__in=languages, project__in=projects)
                publish_dirs = [tp.directory for tp in translation_projects]

    # RSS (notices)
    if form.cleaned_data['publish_rss']:
        for d in publish_dirs:
            create_notice(request.user, message, d)

    # E-mail
    if form.cleaned_data['send_email']:
        email_header = form.cleaned_data['email_header']

        if languages:
            lang_filter = Q(languages__in=languages)
        else:
            lang_filter = Q(languages__isnull=False)

        if projects:
            proj_filter = Q(projects__in=projects)
        else:
            proj_filter = Q(projects__isnull=False)

        to_list = PootleProfile.objects.filter(lang_filter, proj_filter)
        to_list = to_list.distinct()

        # Take into account 'only active users' flag from the form.
        if form.cleaned_data['restrict_to_active_users']:
            to_list = to_list.exclude(submission=None)
            to_list = to_list.exclude(suggestion=None)
            to_list = to_list.exclude(suggester=None)

        recipients = []
        for person in to_list:
            # Check if the User object here as permissions
            directory = form.cleaned_data['directory']

            if not check_profile_permission(person, 'view', directory):
                continue

            if person.user.email != '':
                recipients.append(person.user.email)

        # Send the email to the recipients, ensuring addresses are hidden
        send_mail(email_header, message, bcc=recipients, fail_silently=True)

    if not template_vars['notices_published']:
        template_vars['notices_published'] = None

    form = form_factory(current_directory)()

    return form
Beispiel #38
0
def handle_form(request, current_directory, current_project, current_language,
                template_vars):
    if request.method != 'POST':
        # Not a POST method. Return a default starting state of the form
        return form_factory(current_directory)()

    # Reconstruct the NoticeForm with the user data.
    form = form_factory(current_directory)(request.POST)
    if not form.is_valid():
        return form

    message = form.cleaned_data['message']
    languages = form.cleaned_data.get('language_selection', [])
    projects = form.cleaned_data.get('project_selection', [])
    publish_dirs = []
    template_vars['notices_published'] = []

    # Figure out which directories, projects, and languages are involved
    if current_language and current_project:
        # The current translation project
        publish_dirs = [current_directory]
        languages = [current_language]
        projects = [current_project]
    elif current_language:
        languages = [current_language]
        if form.cleaned_data['project_all']:
            # The current language
            publish_dirs = [current_language.directory]
        else:
            # Certain projects in the current language
            translation_projects = TranslationProject.objects.filter(
                language=current_language, project__in=projects)
            publish_dirs = [tp.directory for tp in translation_projects]
    elif current_project:
        projects = [current_project]
        if form.cleaned_data['language_all']:
            # The current project
            publish_dirs = [current_project.directory]
        else:
            # Certain languages in the current project
            translation_projects = TranslationProject.objects.filter(
                language__in=languages, project=current_project)
            publish_dirs = [tp.directory for tp in translation_projects]
    else:
        # The form is top-level (server-wide)
        if form.cleaned_data['project_all']:
            if form.cleaned_data['language_all']:
                # Publish at server root
                publish_dirs = [current_directory]
            else:
                # Certain languages
                publish_dirs = [l.directory for l in languages]
        else:
            if form.cleaned_data['language_all']:
                # Certain projects
                publish_dirs = [p.directory for p in projects]
            else:
                # Specific translation projects
                translation_projects = TranslationProject.objects.filter(
                    language__in=languages, project__in=projects)
                publish_dirs = [tp.directory for tp in translation_projects]

    # RSS (notices)
    if form.cleaned_data['publish_rss']:
        for d in publish_dirs:
            create_notice(request.user, message, d)

    # E-mail
    if form.cleaned_data['send_email']:
        email_header = form.cleaned_data['email_header']

        if languages:
            lang_filter = Q(languages__in=languages)
        else:
            lang_filter = Q(languages__isnull=False)

        if projects:
            proj_filter = Q(projects__in=projects)
        else:
            proj_filter = Q(projects__isnull=False)

        to_list = PootleProfile.objects.filter(lang_filter, proj_filter)
        to_list = to_list.distinct()

        # Take into account 'only active users' flag from the form.
        if form.cleaned_data['restrict_to_active_users']:
            to_list = to_list.exclude(submission=None)
            to_list = to_list.exclude(suggestion=None)
            to_list = to_list.exclude(suggester=None)

        recipients = []
        for person in to_list:
            # Check if the User object here as permissions
            directory = form.cleaned_data['directory']

            if not check_profile_permission(person, 'view', directory):
                continue

            if person.user.email != '':
                recipients.append(person.user.email)

        # Send the email to the recipients, ensuring addresses are hidden
        send_mail(email_header, message, bcc=recipients, fail_silently=True)

    if not template_vars['notices_published']:
        template_vars['notices_published'] = None

    form = form_factory(current_directory)()

    return form
Beispiel #39
0
def get_tp_metadata(request, pootle_path, uid=None):
    """
    @return: An object in JSON notation that contains the metadata information
    about the current translation project: source/target language codes,
    the direction of the text and also a initial pager.

    Success status that indicates if the information has been succesfully
    retrieved or not is returned as well.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path
    profile = get_profile(request.user)
    json = {}

    try:
        store = Store.objects.select_related(
            'translation_project', 'parent').get(pootle_path=pootle_path)
        if not check_profile_permission(profile, 'view', store.parent):
            json["success"] = False
            json["msg"] = _(
                "You do not have rights to access translation mode.")
        else:
            units_qs = _filter_queryset(request.GET, store.units)
            unit_rows = profile.get_unit_rows()

            try:
                if uid is None:
                    try:
                        current_unit = units_qs[0]
                        json["uid"] = units_qs[0].id
                    except IndexError:
                        current_unit = None
                else:
                    current_unit = units_qs.get(id=uid,
                                                store__pootle_path=pootle_path)
                if current_unit is not None:
                    current_index = _get_index_in_qs(units_qs, current_unit)
                    preceding = units_qs[:current_index].count()
                    page = preceding / unit_rows + 1
                    pager = paginate(request,
                                     units_qs,
                                     items=unit_rows,
                                     page=page)
                    json["pager"] = _build_pager_dict(pager)
                tp = store.translation_project
                json["meta"] = {
                    "source_lang": tp.project.source_language.code,
                    "source_dir": tp.project.source_language.get_direction(),
                    "target_lang": tp.language.code,
                    "target_dir": tp.language.get_direction()
                }
                json["success"] = True
            except Unit.DoesNotExist:
                json["success"] = False
                json["msg"] = _("Unit %(uid)s does not exist on %(path)s." % {
                    'uid': uid,
                    'path': pootle_path
                })
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #40
0
def get_edit_unit(request, pootle_path, uid):
    """
    Given a store path C{pootle_path} and unit id C{uid}, gathers all the
    necessary information to build the editing widget.

    @return: A templatised editing widget is returned within the C{editor}
    variable and paging information is also returned if the page number has
    changed.
    """
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path

    unit = get_object_or_404(Unit, id=uid, store__pootle_path=pootle_path)
    translation_project = unit.store.translation_project
    language = translation_project.language
    form_class = unit_form_factory(language, len(unit.source.strings))
    form = form_class(instance=unit)
    store = unit.store
    directory = store.parent
    profile = get_profile(request.user)
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    template_vars = {
        'unit': unit,
        'form': form,
        'store': store,
        'profile': profile,
        'user': request.user,
        'language': language,
        'source_language': translation_project.project.source_language,
        'cantranslate': check_profile_permission(profile, "translate",
                                                 directory),
        'cansuggest': check_profile_permission(profile, "suggest", directory),
        'canreview': check_profile_permission(profile, "review", directory),
        'altsrcs': find_altsrcs(unit,
                                alt_src_langs,
                                store=store,
                                project=project),
        'suggestions': get_sugg_list(unit)
    }

    t = loader.get_template('unit/edit.html')
    c = RequestContext(request, template_vars)
    json = {'success': True, 'editor': t.render(c)}

    current_page = int(request.GET.get('page', 1))
    all_units = unit.store.units
    units_qs = _filter_queryset(request.GET, all_units)
    unit_rows = profile.get_unit_rows()
    current_unit = unit
    if current_unit is not None:
        current_index = _get_index_in_qs(units_qs, current_unit)
        preceding = units_qs[:current_index].count()
        page = preceding / unit_rows + 1
        if page != current_page:
            pager = paginate(request, units_qs, items=unit_rows, page=page)
            json["pager"] = _build_pager_dict(pager)
        # Return context rows if filtering is applied
        if 'filter' in request.GET and request.GET.get('filter',
                                                       'all') != 'all':
            edit_index = _get_index_in_qs(all_units, current_unit)
            json["ctxt"] = _filter_ctxt_units(all_units, edit_index, 2)

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #41
0
def submit(request, unit):
    """Processes translation submissions and stores them in the database.

    :return: An object in JSON notation that contains the previous and last
             units for the unit next to unit ``uid``.
    """
    json = {}

    translation_project = request.translation_project
    language = translation_project.language

    if unit.hasplural():
        snplurals = len(unit.source.strings)
    else:
        snplurals = None

    # Store current time so that it is the same for all submissions
    current_time = timezone.now()

    # Update current unit instance's attributes
    unit.submitted_by = request.profile
    unit.submitted_on = current_time

    form_class = unit_form_factory(language, snplurals, request)
    form = form_class(request.POST, instance=unit, request=request)

    if form.is_valid():
        if form.updated_fields:
            for field, old_value, new_value in form.updated_fields:
                sub = Submission(
                        creation_time=current_time,
                        translation_project=translation_project,
                        submitter=request.profile,
                        unit=unit,
                        field=field,
                        type=SubmissionTypes.NORMAL,
                        old_value=old_value,
                        new_value=new_value,
                )
                sub.save()
            form.instance._log_user = request.profile
            form.save()
            translation_submitted.send(
                    sender=translation_project,
                    unit=form.instance,
                    profile=request.profile,
            )

            has_critical_checks = unit.qualitycheck_set.filter(
                category=Category.CRITICAL
            ).exists()

            if has_critical_checks:
                can_review = check_profile_permission(request.profile,
                                                      'review',
                                                      unit.store.parent)
                ctx = {
                    'canreview': can_review,
                    'unit': unit
                }
                template = loader.get_template('editor/units/xhr_checks.html')
                context = RequestContext(request, ctx)
                json['checks'] = template.render(context)

        rcode = 200
    else:
        # Form failed
        #FIXME: we should display validation errors here
        rcode = 400
        json["msg"] = _("Failed to process submission.")

    response = jsonify(json)
    return HttpResponse(response, status=rcode, mimetype="application/json")
Beispiel #42
0
def get_edit_unit(request, unit):
    """
    Given a store path C{pootle_path} and unit id C{uid}, gathers all the
    necessary information to build the editing widget.

    @return: A templatised editing widget is returned within the C{editor}
    variable and paging information is also returned if the page number has
    changed.
    """

    json = {}

    translation_project = request.translation_project
    language = translation_project.language

    if unit.hasplural():
        snplurals = len(unit.source.strings)
    else:
        snplurals = None

    form_class = unit_form_factory(language, snplurals, request)
    form = form_class(instance=unit)
    store = unit.store
    directory = store.parent
    profile = request.profile
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    report_target = ensure_uri(project.report_target)

    suggestions, suggestion_details = get_sugg_list(unit)
    template_vars = {
        "unit": unit,
        "form": form,
        "store": store,
        "directory": directory,
        "profile": profile,
        "user": request.user,
        "language": language,
        "source_language": translation_project.project.source_language,
        "cantranslate": check_profile_permission(profile, "translate", directory),
        "cansuggest": check_profile_permission(profile, "suggest", directory),
        "canreview": check_profile_permission(profile, "review", directory),
        "altsrcs": find_altsrcs(unit, alt_src_langs, store=store, project=project),
        "report_target": report_target,
        "suggestions": suggestions,
        "suggestion_detail": suggestion_details,
    }

    if translation_project.project.is_terminology or store.is_terminology:
        t = loader.get_template("unit/term_edit.html")
    else:
        t = loader.get_template("unit/edit.html")
    c = RequestContext(request, template_vars)
    json["editor"] = t.render(c)
    t = loader.get_template("store/dircrumbs.html")
    json["dircrumbs"] = t.render(c)
    t = loader.get_template("store/storecrumbs.html")
    json["storecrumbs"] = t.render(c)

    rcode = 200
    # Return context rows if filtering is applied
    if _is_filtered(request) or request.GET.get("filter", "all") != "all":
        if translation_project.project.is_terminology or store.is_terminology:
            json["ctxt"] = _filter_ctxt_units(store.units, unit, 0)
        else:
            json["ctxt"] = _filter_ctxt_units(store.units, unit, 2)
    response = jsonify(json)
    return HttpResponse(response, status=rcode, mimetype="application/json")
Beispiel #43
0
def get_edit_unit(request, unit):
    """Given a store path ``pootle_path`` and unit id ``uid``, gathers all the
    necessary information to build the editing widget.

    :return: A templatised editing widget is returned within the ``editor``
             variable and paging information is also returned if the page
             number has changed.
    """
    json = {}

    translation_project = request.translation_project
    language = translation_project.language

    if unit.hasplural():
        snplurals = len(unit.source.strings)
    else:
        snplurals = None

    form_class = unit_form_factory(language, snplurals, request)
    form = form_class(instance=unit)
    comment_form_class = unit_comment_form_factory(language)
    comment_form = comment_form_class({}, instance=unit)

    store = unit.store
    directory = store.parent
    profile = request.profile
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    report_target = ensure_uri(project.report_target)

    suggestions = get_sugg_list(unit)
    template_vars = {
        'unit': unit,
        'form': form,
        'comment_form': comment_form,
        'store': store,
        'directory': directory,
        'profile': profile,
        'user': request.user,
        'language': language,
        'source_language': translation_project.project.source_language,
        'cantranslate': check_profile_permission(profile, "translate",
                                                 directory),
        'cansuggest': check_profile_permission(profile, "suggest", directory),
        'canreview': check_profile_permission(profile, "review", directory),
        'altsrcs': find_altsrcs(unit, alt_src_langs, store=store,
                                project=project),
        'report_target': report_target,
        'suggestions': suggestions,
    }

    if translation_project.project.is_terminology or store.is_terminology:
        t = loader.get_template('unit/term_edit.html')
    else:
        t = loader.get_template('unit/edit.html')
    c = RequestContext(request, template_vars)
    json['editor'] = t.render(c)

    rcode = 200

    # Return context rows if filtering is applied but
    # don't return any if the user has asked not to have it
    current_filter = request.GET.get('filter', 'all')
    show_ctx = request.COOKIES.get('ctxShow', 'true')

    if ((_is_filtered(request) or current_filter not in ('all',)) and
        show_ctx == 'true'):
        # TODO: review if this first 'if' branch makes sense
        if translation_project.project.is_terminology or store.is_terminology:
            json['ctx'] = _filter_ctx_units(store.units, unit, 0)
        else:
            ctx_qty = int(request.COOKIES.get('ctxQty', 1))
            json['ctx'] = _filter_ctx_units(store.units, unit, ctx_qty)

    response = jsonify(json)
    return HttpResponse(response, status=rcode, mimetype="application/json")
Beispiel #44
0
def process_submit(request, pootle_path, uid, type):
    """
    @return: An object in JSON notation that contains the previous
    and last units for the unit next to unit C{uid}.

    This object also contains success status that indicates if the submission
    has been succesfully saved or not.
    """
    json = {}
    if pootle_path[0] != '/':
        pootle_path = '/' + pootle_path

    try:
        unit = Unit.objects.get(id=uid, store__pootle_path=pootle_path)
        directory = unit.store.parent
        profile = get_profile(request.user)
        cantranslate = check_profile_permission(profile, "translate",
                                                directory)
        cansuggest = check_profile_permission(profile, "suggest", directory)
        if type == 'submission' and not cantranslate or \
           type == 'suggestion' and not cansuggest:
            json["success"] = False
            json["msg"] = _(
                "You do not have rights to access translation mode.")
        else:
            translation_project = unit.store.translation_project
            language = translation_project.language
            form_class = unit_form_factory(language, len(unit.source.strings))
            form = form_class(request.POST, instance=unit)
            if form.is_valid():
                if type == 'submission':
                    if form.instance._target_updated or \
                       form.instance._translator_comment_updated or \
                       form.instance._state_updated:
                        form.save()
                        sub = Submission(
                            translation_project=translation_project,
                            submitter=get_profile(request.user))
                        sub.save()
                elif type == 'suggestion':
                    if form.instance._target_updated:
                        #HACKISH: django 1.2 stupidly modifies instance on
                        # model form validation, reload unit from db
                        unit = Unit.objects.get(id=unit.id)
                        sugg = unit.add_suggestion(
                            form.cleaned_data['target_f'],
                            get_profile(request.user))
                        if sugg:
                            SuggestionStat.objects.get_or_create(
                                translation_project=translation_project,
                                suggester=get_profile(request.user),
                                state='pending',
                                unit=unit.id)

                current_page = int(request.POST.get('page', 1))
                all_units = unit.store.units
                units_qs = _filter_queryset(request.POST, all_units)
                unit_rows = profile.get_unit_rows()
                current_unit = unit
                if current_unit is not None:
                    current_index = _get_index_in_qs(units_qs, current_unit)
                    preceding = units_qs[:current_index].count()
                    page = preceding / unit_rows + 1
                    if page != current_page:
                        pager = paginate(request,
                                         units_qs,
                                         items=unit_rows,
                                         page=page)
                        json["pager"] = _build_pager_dict(pager)
                    try:
                        new_index = current_index + 1
                        json["new_uid"] = units_qs[new_index].id
                    except IndexError:
                        # End of set: let's assume the new unit is the last we had
                        new_unit = unit
                        json["new_uid"] = None
                    json["success"] = True
            else:
                # Form failed
                json["success"] = False
                json["msg"] = _("Failed to process submit.")
    except Store.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Store %(path)s does not exist." %
                        {'path': pootle_path})
    except Unit.DoesNotExist:
        json["success"] = False
        json["msg"] = _("Unit %(uid)s does not exist on %(path)s." % {
            'uid': uid,
            'path': pootle_path
        })

    response = simplejson.dumps(json)
    return HttpResponse(response, mimetype="application/json")
Beispiel #45
0
def get_edit_unit(request, unit):
    """
    Given a store path C{pootle_path} and unit id C{uid}, gathers all the
    necessary information to build the editing widget.

    @return: A templatised editing widget is returned within the C{editor}
    variable and paging information is also returned if the page number has
    changed.
    """

    json = {}

    translation_project = request.translation_project
    language = translation_project.language

    if unit.hasplural():
        snplurals = len(unit.source.strings)
    else:
        snplurals = None

    form_class = unit_form_factory(language, snplurals, request)
    form = form_class(instance=unit)
    store = unit.store
    directory = store.parent
    profile = request.profile
    alt_src_langs = get_alt_src_langs(request, profile, translation_project)
    project = translation_project.project
    report_target = ensure_uri(project.report_target)

    suggestions, suggestion_details = get_sugg_list(unit)
    template_vars = {
        'unit': unit,
        'form': form,
        'store': store,
        'directory': directory,
        'profile': profile,
        'user': request.user,
        'language': language,
        'source_language': translation_project.project.source_language,
        'cantranslate': check_profile_permission(profile, "translate",
                                                 directory),
        'cansuggest': check_profile_permission(profile, "suggest", directory),
        'canreview': check_profile_permission(profile, "review", directory),
        'altsrcs': find_altsrcs(unit,
                                alt_src_langs,
                                store=store,
                                project=project),
        'report_target': report_target,
        'suggestions': suggestions,
        'suggestion_detail': suggestion_details,
    }

    if translation_project.project.is_terminology or store.is_terminology:
        t = loader.get_template('unit/term_edit.html')
    else:
        t = loader.get_template('unit/edit.html')
    c = RequestContext(request, template_vars)
    json['editor'] = t.render(c)
    t = loader.get_template('store/dircrumbs.html')
    json['dircrumbs'] = t.render(c)
    t = loader.get_template('store/storecrumbs.html')
    json['storecrumbs'] = t.render(c)

    rcode = 200
    # Return context rows if filtering is applied
    if _is_filtered(request) or request.GET.get('filter', 'all') != 'all':
        if translation_project.project.is_terminology or store.is_terminology:
            json['ctxt'] = _filter_ctxt_units(store.units, unit, 0)
        else:
            json['ctxt'] = _filter_ctxt_units(store.units, unit, 2)
    response = jsonify(json)
    return HttpResponse(response, status=rcode, mimetype="application/json")