Exemple #1
0
    def get_headers(self, context):
        headers = {
            'Auto-Submitted': 'auto-generated',
            'X-AutoGenerated': 'yes',
            'Precedence': 'bulk',
            'X-Mailer': 'Weblate {0}'.format(VERSION),
            'X-Weblate-Notification': self.get_name()
        }

        # Reply to header
        user = context.get('user')
        if user and not user.is_anonymous and not user.is_demo:
            headers['Reply-To'] = user.email

        # References for unit events
        references = None
        unit = context.get('unit')
        if unit:
            references = '{0}/{1}/{2}/{3}'.format(
                unit.translation.component.project.slug,
                unit.translation.component.slug,
                unit.translation.language.code,
                unit.id
            )
        if references is not None:
            references = '<{0}@{1}>'.format(references, get_site_domain())
            headers['In-Reply-To'] = references
            headers['References'] = references
        return headers
Exemple #2
0
    def get_headers(self, context):
        headers = {
            'Auto-Submitted': 'auto-generated',
            'X-AutoGenerated': 'yes',
            'Precedence': 'bulk',
            'X-Mailer': 'Weblate {0}'.format(VERSION),
            'X-Weblate-Notification': self.get_name(),
        }

        # Set From header to contain user full name
        user = context.get('user')
        if user:
            headers['From'] = email.utils.formataddr(
                (context['user'].get_visible_name(),
                 settings.DEFAULT_FROM_EMAIL))

        # References for unit events
        references = None
        unit = context.get('unit')
        if unit:
            references = '{0}/{1}/{2}/{3}'.format(
                unit.translation.component.project.slug,
                unit.translation.component.slug,
                unit.translation.language.code,
                unit.id,
            )
        if references is not None:
            references = '<{0}@{1}>'.format(references, get_site_domain())
            headers['In-Reply-To'] = references
            headers['References'] = references
        return headers
Exemple #3
0
def weblate_context(request):
    """Context processor to inject various useful variables into context."""
    if url_has_allowed_host_and_scheme(request.GET.get("next", ""), allowed_hosts=None):
        login_redirect_url = request.GET["next"]
    else:
        login_redirect_url = request.get_full_path()

    # Load user translations if user is authenticated
    watched_projects = None
    if hasattr(request, "user") and request.user.is_authenticated:
        watched_projects = request.user.watched_projects

    if settings.OFFER_HOSTING:
        description = _("Hosted Weblate, the place to localize your software project.")
    else:
        description = _(
            "This site runs Weblate for localizing various software projects."
        )

    context = {
        "cache_param": "?v={}".format(weblate.GIT_VERSION)
        if not settings.COMPRESS_ENABLED
        else "",
        "version": weblate.VERSION,
        "bread_image": get_bread_image(request.path),
        "description": description,
        "weblate_link": mark_safe(
            '<a href="{}">weblate.org</a>'.format(escape(WEBLATE_URL))
        ),
        "weblate_name_link": mark_safe(
            '<a href="{}">Weblate</a>'.format(escape(WEBLATE_URL))
        ),
        "weblate_version_link": mark_safe(
            '<a href="{}">Weblate {}</a>'.format(
                escape(WEBLATE_URL), "" if settings.HIDE_VERSION else weblate.VERSION
            )
        ),
        "donate_url": DONATE_URL,
        "site_url": get_site_url(),
        "site_domain": get_site_domain(),
        "current_date": datetime.utcnow().strftime("%Y-%m-%d"),
        "current_year": datetime.utcnow().strftime("%Y"),
        "current_month": datetime.utcnow().strftime("%m"),
        "login_redirect_url": login_redirect_url,
        "has_ocr": weblate.screenshots.views.HAS_OCR,
        "has_antispam": bool(settings.AKISMET_API_KEY),
        "has_sentry": bool(settings.SENTRY_DSN),
        "watched_projects": watched_projects,
        "allow_index": False,
        "configuration_errors": ConfigurationError.objects.filter(
            ignored=False
        ).order_by("-timestamp"),
        "preconnect_list": get_preconnect_list(),
    }

    add_error_logging_context(context)
    add_settings_context(context)
    add_optional_context(context)

    return context
Exemple #4
0
def check_site(app_configs, **kwargs):
    from weblate.utils.site import get_site_domain, check_domain

    errors = []
    if not check_domain(get_site_domain()):
        errors.append(weblate_check("weblate.E017", "Correct the site domain"))
    return errors
Exemple #5
0
    def get_headers(self, context):
        headers = {
            "Auto-Submitted": "auto-generated",
            "X-AutoGenerated": "yes",
            "Precedence": "bulk",
            "X-Mailer": USER_AGENT,
            "X-Weblate-Notification": self.get_name(),
        }

        # Set From header to contain user full name
        user = context.get("user")
        if user:
            headers["From"] = formataddr((context["user"].get_visible_name(),
                                          settings.DEFAULT_FROM_EMAIL))

        # References for unit events
        references = None
        unit = context.get("unit")
        if unit:
            references = "{0}/{1}/{2}/{3}".format(
                unit.translation.component.project.slug,
                unit.translation.component.slug,
                unit.translation.language.code,
                unit.id,
            )
        if references is not None:
            references = "<{0}@{1}>".format(references, get_site_domain())
            headers["In-Reply-To"] = references
            headers["References"] = references
        return headers
Exemple #6
0
def weblate_context(request):
    """Context processor to inject various useful variables into context."""
    if is_safe_url(request.GET.get('next', ''), allowed_hosts=None):
        login_redirect_url = request.GET['next']
    else:
        login_redirect_url = request.get_full_path()

    # Load user translations if user is authenticated
    watched_projects = None
    if hasattr(request, 'user') and request.user.is_authenticated:
        watched_projects = request.user.allowed_projects.filter(
            profile=request.user.profile
        )

    if settings.OFFER_HOSTING:
        description = _('Hosted Weblate, the place to localize your software project.')
    else:
        description = _(
            'This site runs Weblate for localizing various software projects.'
        )

    weblate_url = URL_BASE % weblate.VERSION

    context = {
        'cache_param': '?v={}'.format(weblate.GIT_VERSION),
        'version': weblate.VERSION,
        'bread_image': get_bread_image(request.path),
        'description': description,
        'weblate_link': mark_safe(
            '<a href="{}">weblate.org</a>'.format(escape(weblate_url))
        ),
        'weblate_name_link': mark_safe(
            '<a href="{}">Weblate</a>'.format(escape(weblate_url))
        ),
        'weblate_version_link': mark_safe(
            '<a href="{}">Weblate {}</a>'.format(escape(weblate_url), weblate.VERSION)
        ),
        'donate_url': URL_DONATE % weblate.VERSION,
        'site_url': get_site_url(),
        'site_domain': get_site_domain(),
        'current_date': datetime.utcnow().strftime('%Y-%m-%d'),
        'current_year': datetime.utcnow().strftime('%Y'),
        'current_month': datetime.utcnow().strftime('%m'),
        'login_redirect_url': login_redirect_url,
        'has_ocr': weblate.screenshots.views.HAS_OCR,
        'has_antispam': bool(settings.AKISMET_API_KEY),
        'watched_projects': watched_projects,
        'allow_index': False,
        'configuration_errors': ConfigurationError.objects.filter(
            ignored=False
        ).order_by('-timestamp'),
        'preconnect_list': get_preconnect_list(),
    }

    add_error_logging_context(context)
    add_settings_context(context)
    add_optional_context(context)

    return context
Exemple #7
0
def run_domain(checks, request):
    """Check for domain configuration"""
    checks.append((
        _('Site domain'),
        check_domain(get_site_domain()),
        'production-site',
        get_site_url(),
    ))
Exemple #8
0
def run_domain(checks, request):
    """Check for domain configuration"""
    checks.append((
        _('Site domain'),
        check_domain(get_site_domain()),
        'production-site',
        get_site_url(),
    ))
Exemple #9
0
def check_site(app_configs, **kwargs):
    from weblate.utils.site import get_site_domain, check_domain
    errors = []
    if not check_domain(get_site_domain()):
        errors.append(
            Critical(
                'Configure correct site domain',
                hint=get_doc_url('admin/install', 'production-site'),
                id='weblate.E017',
            ))
    return errors
Exemple #10
0
def check_site(app_configs, **kwargs):
    from weblate.utils.site import get_site_domain, check_domain
    errors = []
    if not check_domain(get_site_domain()):
        errors.append(
            Critical(
                'Configure correct site domain',
                hint=get_doc_url('admin/install', 'production-site'),
                id='weblate.E017',
            )
        )
    return errors
Exemple #11
0
    def get_headers(self, context):
        headers = {
            'Auto-Submitted': 'auto-generated',
            'X-AutoGenerated': 'yes',
            'Precedence': 'bulk',
            'X-Mailer': 'Weblate {0}'.format(VERSION),
            'X-Weblate-Notification': self.get_name()
        }

        # References for unit events
        references = None
        unit = context.get('unit')
        if unit:
            references = '{0}/{1}/{2}/{3}'.format(
                unit.translation.component.project.slug,
                unit.translation.component.slug,
                unit.translation.language.code,
                unit.id
            )
        if references is not None:
            references = '<{0}@{1}>'.format(references, get_site_domain())
            headers['In-Reply-To'] = references
            headers['References'] = references
        return headers
Exemple #12
0
def performance(request, admin_site):
    """Show performance tuning tips."""
    if request.method == 'POST':
        return handle_dismiss(request)
    checks = []
    # Check for debug mode
    checks.append((
        _('Debug mode'),
        not settings.DEBUG,
        'production-debug',
        settings.DEBUG,
    ))
    # Check for domain configuration
    checks.append((
        _('Site domain'),
        check_domain(get_site_domain()),
        'production-site',
        get_site_url(),
    ))
    # Check database being used
    checks.append((
        _('Database backend'),
        "sqlite" not in settings.DATABASES['default']['ENGINE'],
        'production-database',
        settings.DATABASES['default']['ENGINE'],
    ))
    # Check configured admins
    checks.append((
        _('Site administrator'),
        len(settings.ADMINS) > 0
        or '*****@*****.**' in [x[1] for x in settings.ADMINS],
        'production-admins',
        ', '.join([x[1] for x in settings.ADMINS]),
    ))
    # Check offloading indexing
    checks.append((
        # Translators: Indexing is postponed to cron job
        _('Indexing offloading'),
        settings.OFFLOAD_INDEXING,
        'production-indexing',
        settings.OFFLOAD_INDEXING))
    if settings.OFFLOAD_INDEXING:
        if IndexUpdate.objects.count() < 20:
            index_updates = True
        elif IndexUpdate.objects.count() < 200:
            index_updates = None
        else:
            index_updates = False

        checks.append((
            # Translators: Indexing is postponed to cron job
            _('Indexing offloading processing'),
            index_updates,
            'production-indexing',
            IndexUpdate.objects.count(),
        ))
    # Check for sane caching
    caches = settings.CACHES['default']['BACKEND'].split('.')[-1]
    if caches in GOOD_CACHE:
        # We consider these good
        caches = True
    elif caches in ['DummyCache']:
        # This one is definitely bad
        caches = False
    else:
        # These might not be that bad
        caches = None
    checks.append((
        _('Django caching'),
        caches,
        'production-cache',
        settings.CACHES['default']['BACKEND'],
    ))
    # Avatar caching
    checks.append((
        _('Avatar caching'),
        'avatar' in settings.CACHES,
        'production-cache-avatar',
        settings.CACHES['avatar']['BACKEND']
        if 'avatar' in settings.CACHES else '',
    ))
    # Check email setup
    default_mails = ('root@localhost', 'webmaster@localhost',
                     '*****@*****.**'
                     '*****@*****.**')
    checks.append((
        _('Email addresses'),
        (settings.SERVER_EMAIL not in default_mails
         and settings.DEFAULT_FROM_EMAIL not in default_mails),
        'production-email',
        ', '.join((settings.SERVER_EMAIL, settings.DEFAULT_FROM_EMAIL)),
    ))
    # libravatar library
    checks.append((
        _('Federated avatar support'),
        HAS_LIBRAVATAR,
        'production-avatar',
        HAS_LIBRAVATAR,
    ))
    # pyuca library
    checks.append((
        _('pyuca library'),
        HAS_PYUCA,
        'production-pyuca',
        HAS_PYUCA,
    ))
    # Cookie signing key
    checks.append((
        _('Secret key'),
        settings.SECRET_KEY != settings_example.SECRET_KEY,
        'production-secret',
        '',
    ))
    # Allowed hosts
    checks.append((
        _('Allowed hosts'),
        len(settings.ALLOWED_HOSTS) > 0,
        'production-hosts',
        ', '.join(settings.ALLOWED_HOSTS),
    ))

    loader = get_first_loader()
    # Cached template loader
    checks.append((
        _('Cached template loader'),
        'cached.Loader' in loader,
        'production-templates',
        loader,
    ))

    # Check for serving static files
    checks.append((
        _('Admin static files'),
        os.path.exists(
            os.path.join(settings.STATIC_ROOT, 'admin', 'js', 'core.js')),
        'production-admin-files',
        settings.STATIC_ROOT,
    ))

    context = admin_site.each_context(request)
    context['checks'] = checks
    context['errors'] = ConfigurationError.objects.filter(ignored=False)

    return render(
        request,
        "admin/performance.html",
        context,
    )
Exemple #13
0
def get_notification_email(language, email, notification,
                           translation_obj=None, context=None, headers=None,
                           user=None, info=None):
    """Render notification email."""
    cur_language = django_translation.get_language()
    context = context or {}
    headers = headers or {}
    references = None
    if 'unit' in context:
        unit = context['unit']
        references = '{0}/{1}/{2}/{3}'.format(
            unit.translation.component.project.slug,
            unit.translation.component.slug,
            unit.translation.language.code,
            unit.id
        )
    if references is not None:
        references = '<{0}@{1}>'.format(references, get_site_domain())
        headers['In-Reply-To'] = references
        headers['References'] = references
    try:
        if info is None:
            info = force_text(translation_obj)
        LOGGER.info(
            'sending notification %s on %s to %s',
            notification,
            info,
            email
        )

        # Load user language
        if language is not None:
            django_translation.activate(language)

        # Template name
        context['subject_template'] = 'mail/{0}_subject.txt'.format(
            notification
        )
        context['LANGUAGE_CODE'] = django_translation.get_language()
        context['LANGUAGE_BIDI'] = django_translation.get_language_bidi()

        # Adjust context
        context['current_site_url'] = get_site_url()
        if translation_obj is not None:
            context['translation'] = translation_obj
            context['translation_url'] = get_site_url(
                translation_obj.get_absolute_url()
            )
        context['site_title'] = settings.SITE_TITLE

        # Render subject
        subject = render_to_string(
            context['subject_template'],
            context
        ).strip()

        # Render body
        body = render_to_string(
            'mail/{0}.txt'.format(notification),
            context
        )
        html_body = render_to_string(
            'mail/{0}.html'.format(notification),
            context
        )

        # Define headers
        headers['Auto-Submitted'] = 'auto-generated'
        headers['X-AutoGenerated'] = 'yes'
        headers['Precedence'] = 'bulk'
        headers['X-Mailer'] = 'Weblate {0}'.format(VERSION)

        # Reply to header
        if user is not None:
            headers['Reply-To'] = user.email

        # List of recipients
        if email == 'ADMINS':
            emails = [a[1] for a in settings.ADMINS]
        else:
            emails = [email]

        # Create message
        email = EmailMultiAlternatives(
            settings.EMAIL_SUBJECT_PREFIX + subject,
            body,
            to=emails,
            headers=headers,
        )
        email.attach_alternative(
            html_body,
            'text/html'
        )

        # Return the mail
        return email
    finally:
        django_translation.activate(cur_language)
Exemple #14
0
def get_notification_email(language,
                           email,
                           notification,
                           translation_obj=None,
                           context=None,
                           headers=None,
                           user=None,
                           info=None):
    """Render notification email."""
    context = context or {}
    headers = headers or {}
    references = None
    if 'unit' in context:
        unit = context['unit']
        references = '{0}/{1}/{2}/{3}'.format(
            unit.translation.component.project.slug,
            unit.translation.component.slug, unit.translation.language.code,
            unit.id)
    if references is not None:
        references = '<{0}@{1}>'.format(references, get_site_domain())
        headers['In-Reply-To'] = references
        headers['References'] = references

    if info is None:
        info = force_text(translation_obj)

    LOGGER.info('sending notification %s on %s to %s', notification, info,
                email)

    with django_translation.override('en' if language is None else language):
        # Template name
        context['subject_template'] = 'mail/{0}_subject.txt'.format(
            notification)
        context['LANGUAGE_CODE'] = django_translation.get_language()
        context['LANGUAGE_BIDI'] = django_translation.get_language_bidi()

        # Adjust context
        context['current_site_url'] = get_site_url()
        if translation_obj is not None:
            context['translation'] = translation_obj
            context['translation_url'] = get_site_url(
                translation_obj.get_absolute_url())
        context['site_title'] = settings.SITE_TITLE

        # Render subject
        subject = render_to_string(context['subject_template'],
                                   context).strip()

        # Render body
        body = render_to_string('mail/{0}.txt'.format(notification), context)
        html_body = render_to_string('mail/{0}.html'.format(notification),
                                     context)

        # Define headers
        headers['Auto-Submitted'] = 'auto-generated'
        headers['X-AutoGenerated'] = 'yes'
        headers['Precedence'] = 'bulk'
        headers['X-Mailer'] = 'Weblate {0}'.format(VERSION)

        # Reply to header
        if user is not None:
            headers['Reply-To'] = user.email

        # List of recipients
        if email == 'ADMINS':
            emails = [a[1] for a in settings.ADMINS]
        else:
            emails = [email]

        # Return the mail content
        return {
            'subject': subject,
            'body': body,
            'to': emails,
            'headers': headers,
            'html_body': html_body,
        }
def get_notification_email(language,
                           email,
                           notification,
                           translation_obj=None,
                           context=None,
                           headers=None,
                           user=None,
                           info=None):
    """Render notification email."""
    cur_language = django_translation.get_language()
    context = context or {}
    headers = headers or {}
    references = None
    if 'unit' in context:
        unit = context['unit']
        references = '{0}/{1}/{2}/{3}'.format(
            unit.translation.component.project.slug,
            unit.translation.component.slug, unit.translation.language.code,
            unit.id)
    if references is not None:
        references = '<{0}@{1}>'.format(references, get_site_domain())
        headers['In-Reply-To'] = references
        headers['References'] = references
    try:
        if info is None:
            info = force_text(translation_obj)
        LOGGER.info('sending notification %s on %s to %s', notification, info,
                    email)

        # Load user language
        if language is not None:
            django_translation.activate(language)

        # Template name
        context['subject_template'] = 'mail/{0}_subject.txt'.format(
            notification)
        context['LANGUAGE_CODE'] = django_translation.get_language()
        context['LANGUAGE_BIDI'] = django_translation.get_language_bidi()

        # Adjust context
        context['current_site_url'] = get_site_url()
        if translation_obj is not None:
            context['translation'] = translation_obj
            context['translation_url'] = get_site_url(
                translation_obj.get_absolute_url())
        context['site_title'] = settings.SITE_TITLE

        # Render subject
        subject = render_to_string(context['subject_template'],
                                   context).strip()

        # Render body
        body = render_to_string('mail/{0}.txt'.format(notification), context)
        html_body = render_to_string('mail/{0}.html'.format(notification),
                                     context)

        # Define headers
        headers['Auto-Submitted'] = 'auto-generated'
        headers['X-AutoGenerated'] = 'yes'
        headers['Precedence'] = 'bulk'
        headers['X-Mailer'] = 'Weblate {0}'.format(VERSION)

        # Reply to header
        if user is not None:
            headers['Reply-To'] = user.email

        # List of recipients
        if email == 'ADMINS':
            emails = [a[1] for a in settings.ADMINS]
        else:
            emails = [email]

        # Create message
        email = EmailMultiAlternatives(
            settings.EMAIL_SUBJECT_PREFIX + subject,
            body,
            to=emails,
            headers=headers,
        )
        email.attach_alternative(html_body, 'text/html')

        # Return the mail
        return email
    finally:
        django_translation.activate(cur_language)
Exemple #16
0
def weblate_context(request):
    """Context processor to inject various useful variables into context."""
    if is_safe_url(request.GET.get('next', ''), allowed_hosts=None):
        login_redirect_url = request.GET['next']
    else:
        login_redirect_url = request.get_full_path()

    # Load user translations if user is authenticated
    subscribed_projects = None
    if request.user.is_authenticated:
        subscribed_projects = request.user.profile.subscriptions.all()

    if settings.OFFER_HOSTING:
        description = _(
            'Hosted Weblate, the place to translate your software project.'
        )
    else:
        description = _(
            'This site runs Weblate for translating various software projects.'
        )

    weblate_url = URL_BASE % weblate.VERSION

    context = {
        'cache_param': '?v={}'.format(weblate.GIT_VERSION),
        'version': weblate.VERSION,
        'description': description,

        'weblate_link': mark_safe(
            '<a href="{}">weblate.org</a>'.format(escape(weblate_url))
        ),
        'weblate_name_link': mark_safe(
            '<a href="{}">Weblate</a>'.format(escape(weblate_url))
        ),
        'weblate_version_link': mark_safe(
            '<a href="{}">Weblate {}</a>'.format(
                escape(weblate_url), weblate.VERSION
            )
        ),
        'donate_url': URL_DONATE % weblate.VERSION,

        'site_url': get_site_url(),
        'site_domain': get_site_domain(),

        'current_date': datetime.utcnow().strftime('%Y-%m-%d'),
        'current_year': datetime.utcnow().strftime('%Y'),
        'current_month': datetime.utcnow().strftime('%m'),

        'login_redirect_url': login_redirect_url,

        'has_ocr': weblate.screenshots.views.HAS_OCR,
        'has_antispam': bool(settings.AKISMET_API_KEY),

        'subscribed_projects': subscribed_projects,

        'allow_index': False,
        'configuration_errors': ConfigurationError.objects.filter(
            ignored=False
        ),
    }

    add_error_logging_context(context)
    add_settings_context(context)
    add_optional_context(context)

    return context
Exemple #17
0
def weblate_context(request):
    """Context processor to inject various useful variables into context."""
    if url_has_allowed_host_and_scheme(request.GET.get("next", ""), allowed_hosts=None):
        login_redirect_url = request.GET["next"]
    else:
        login_redirect_url = request.get_full_path()

    # Load user translations if user is authenticated
    watched_projects = None
    if hasattr(request, "user") and request.user.is_authenticated:
        watched_projects = request.user.watched_projects

    if settings.OFFER_HOSTING:
        description = _("Hosted Weblate, the place to localize your software project.")
    else:
        description = _(
            "This site runs Weblate for localizing various software projects."
        )

    if hasattr(request, "_weblate_has_support"):
        has_support = request._weblate_has_support
    else:
        has_support_cache_key = "weblate:has:support"
        has_support = cache.get(has_support_cache_key)
        if has_support is None:
            support_status = SupportStatus.objects.get_current()
            has_support = support_status.name != "community"
            cache.set(has_support_cache_key, has_support, 86400)
        request._weblate_has_support = has_support

    utcnow = datetime.utcnow()

    context = {
        "has_support": has_support,
        "cache_param": f"?v={weblate.utils.version.GIT_VERSION}"
        if not settings.COMPRESS_ENABLED
        else "",
        "version": weblate.utils.version.VERSION,
        "bread_image": get_bread_image(request.path),
        "description": description,
        "weblate_link": mark_safe(f'<a href="{escape(WEBLATE_URL)}">weblate.org</a>'),
        "weblate_name_link": mark_safe(f'<a href="{escape(WEBLATE_URL)}">Weblate</a>'),
        "weblate_version_link": format_html(
            '<a href="{}">Weblate {}</a>',
            WEBLATE_URL,
            "" if settings.HIDE_VERSION else weblate.utils.version.VERSION,
        ),
        "donate_url": DONATE_URL,
        "site_url": get_site_url(),
        "site_domain": get_site_domain(),
        "current_date": utcnow.strftime("%Y-%m-%d"),
        "current_year": utcnow.strftime("%Y"),
        "current_month": utcnow.strftime("%m"),
        "login_redirect_url": login_redirect_url,
        "has_ocr": weblate.screenshots.views.HAS_OCR,
        "has_antispam": bool(settings.AKISMET_API_KEY),
        "has_sentry": bool(settings.SENTRY_DSN),
        "watched_projects": watched_projects,
        "allow_index": False,
        "configuration_errors": ConfigurationError.objects.filter(
            ignored=False
        ).order_by("-timestamp"),
        "preconnect_list": get_preconnect_list(),
        "custom_css_hash": CustomCSSView.get_hash(request),
        "interledger_payment_pointer": get_interledger_payment_pointer(),
    }

    add_error_logging_context(context)
    add_settings_context(context)
    add_optional_context(context)

    return context