diff --git a/testbed/wagtail__wagtail/wagtail/admin/admin_url_finder.py b/testbed/wagtail__wagtail/wagtail/admin/admin_url_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf3bd74cebf3f4633808f3655b857aea3ccfdca --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/admin_url_finder.py @@ -0,0 +1,107 @@ +from django.contrib.admin.utils import quote +from django.core.exceptions import ImproperlyConfigured +from django.urls import reverse + +from wagtail.hooks import search_for_hooks +from wagtail.utils.registry import ObjectTypeRegistry + +""" +A mechanism for finding the admin edit URL for an arbitrary object instance, optionally applying +permission checks. + + url_finder = AdminURLFinder(request.user) + url_finder.get_edit_url(some_page) # => "/admin/pages/123/edit/" + url_finder.get_edit_url(some_image) # => "/admin/images/456/" + url_finder.get_edit_url(some_site) # => None (user does not have edit permission for sites) + +If the user parameter is omitted, edit URLs are returned without considering permissions. + +Handlers for new models can be registered via register_admin_url_finder: + + class SprocketAdminURLFinder(ModelAdminURLFinder): + edit_url_name = 'wagtailsprockets:edit' + + register_admin_url_finder(Sprocket, SprocketAdminURLFinder) +""" + + +class ModelAdminURLFinder: + """ + Handles admin edit URL lookups for an individual model + """ + + edit_url_name = None + permission_policy = None + + def __init__(self, user=None): + self.user = user + + def construct_edit_url(self, instance): + """ + Return the edit URL for the given instance - regardless of whether the user can access it - + or None if no edit URL is available. + """ + if self.edit_url_name is None: + raise ImproperlyConfigured( + "%r must define edit_url_name or override construct_edit_url" + % type(self) + ) + return reverse(self.edit_url_name, args=(quote(instance.pk),)) + + def get_edit_url(self, instance): + """ + Return the edit URL for the given instance if one exists and the user has permission for it, + or None otherwise. + """ + if ( + self.user + and self.permission_policy + and not self.permission_policy.user_has_permission_for_instance( + self.user, "change", instance + ) + ): + return None + else: + return self.construct_edit_url(instance) + + +class NullAdminURLFinder: + """ + A dummy AdminURLFinder that always returns None + """ + + def __init__(self, user=None): + pass + + def get_edit_url(self, instance): + return None + + +finder_classes = ObjectTypeRegistry() + + +def register_admin_url_finder(model, handler): + finder_classes.register(model, value=handler) + + +class AdminURLFinder: + """ + The 'main' admin URL finder, which searches across all registered models + """ + + def __init__(self, user=None): + search_for_hooks() # ensure wagtail_hooks files have been loaded + self.user = user + self.finders_by_model = {} + + def get_edit_url(self, instance): + model = type(instance) + try: + # do we already have a finder for this model and user? + finder = self.finders_by_model[model] + except KeyError: + finder_class = finder_classes.get(instance) or NullAdminURLFinder + finder = finder_class(self.user) + self.finders_by_model[model] = finder + + return finder.get_edit_url(instance) diff --git a/testbed/wagtail__wagtail/wagtail/admin/templates/wagtailadmin/home.html b/testbed/wagtail__wagtail/wagtail/admin/templates/wagtailadmin/home.html new file mode 100644 index 0000000000000000000000000000000000000000..28a8a4f3977d8967e167b77d38d180114a66b75b --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/templates/wagtailadmin/home.html @@ -0,0 +1,33 @@ +{% extends "wagtailadmin/generic/base.html" %} +{% load wagtailadmin_tags i18n %} +{% block bodyclass %}homepage{% endblock %} + +{% block extra_css %} + {{ block.super }} + {{ media.css }} +{% endblock %} + +{% block content %} + {% fragment as header_title %} + {% block branding_welcome %}{% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %}{% endblock %} + {% endfragment %} + + +
+ {% avatar_url user 70 as avatar %} + {% include "wagtailadmin/shared/header.html" with title=header_title description=user|user_display_name avatar=avatar merged=1 %} + + {% if panels %} + {% for panel in panels %} + {% component panel fallback_render_method=True %} + {% endfor %} + {% else %} +

{% trans "This is your dashboard on which helpful information about content you've created will be displayed." %}

+ {% endif %} +
+{% endblock %} + +{% block extra_js %} + {{ block.super }} + {{ media.js }} +{% endblock %} diff --git a/testbed/wagtail__wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py b/testbed/wagtail__wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..94b3658a8e68198c9806960e5aa8c037b5fa8ea9 --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py @@ -0,0 +1,1130 @@ +import json +from datetime import datetime +from urllib.parse import urljoin + +from django import template +from django.conf import settings +from django.contrib.admin.utils import quote +from django.contrib.humanize.templatetags.humanize import intcomma, naturaltime +from django.contrib.messages.constants import DEFAULT_TAGS as MESSAGE_TAGS +from django.http.request import HttpHeaders +from django.middleware.csrf import get_token +from django.shortcuts import resolve_url as resolve_url_func +from django.template import Context +from django.template.base import token_kwargs +from django.template.defaultfilters import stringfilter +from django.templatetags.static import static +from django.urls import reverse +from django.urls.exceptions import NoReverseMatch +from django.utils import timezone +from django.utils.encoding import force_str +from django.utils.html import avoid_wrapping, format_html, format_html_join, json_script +from django.utils.http import urlencode +from django.utils.safestring import mark_safe +from django.utils.timesince import timesince +from django.utils.translation import gettext_lazy as _ + +from wagtail import hooks +from wagtail.admin.localization import get_js_translation_strings +from wagtail.admin.menu import admin_menu +from wagtail.admin.navigation import get_explorable_root_page +from wagtail.admin.search import admin_search_areas +from wagtail.admin.staticfiles import versioned_static as versioned_static_func +from wagtail.admin.ui import sidebar +from wagtail.admin.utils import get_admin_base_url, get_valid_next_url_from_request +from wagtail.admin.views.bulk_action.registry import bulk_action_registry +from wagtail.admin.widgets import ButtonWithDropdown, PageListingButton +from wagtail.coreutils import camelcase_to_underscore +from wagtail.coreutils import cautious_slugify as _cautious_slugify +from wagtail.coreutils import ( + escape_script, + get_content_type_label, + get_locales_display_names, +) +from wagtail.models import ( + CollectionViewRestriction, + Locale, + Page, + PageViewRestriction, + UserPagePermissionsProxy, +) +from wagtail.telepath import JSContext +from wagtail.users.utils import get_gravatar_url + +register = template.Library() + +register.filter("intcomma", intcomma) +register.filter("naturaltime", naturaltime) + + +@register.inclusion_tag("wagtailadmin/shared/breadcrumbs.html", takes_context=True) +def breadcrumbs( + context, + page, + url_name, + url_root_name=None, + include_self=True, + is_expanded=False, + page_perms=None, + querystring_value=None, + trailing_breadcrumb_title=None, + classname=None, +): + user = context["request"].user + + # find the closest common ancestor of the pages that this user has direct explore permission + # (i.e. add/edit/publish/lock) over; this will be the root of the breadcrumb + cca = get_explorable_root_page(user) + if not cca: + return {"pages": Page.objects.none()} + + return { + "pages": page.get_ancestors(inclusive=include_self) + .descendant_of(cca, inclusive=True) + .specific(), + "current_page": page, + "is_expanded": is_expanded, + "page_perms": page_perms, + "querystring_value": querystring_value or "", + "trailing_breadcrumb_title": trailing_breadcrumb_title, # Only used in collapsible breadcrumb templates + "url_name": url_name, + "url_root_name": url_root_name, + "classname": classname, + } + + +@register.inclusion_tag("wagtailadmin/shared/search_other.html", takes_context=True) +def search_other(context, current=None): + request = context["request"] + + return { + "options_html": admin_search_areas.render_html(request, current), + "request": request, + } + + +@register.filter("ellipsistrim") +def ellipsistrim(value, max_length): + if len(value) > max_length: + truncd_val = value[:max_length] + if not len(value) == (max_length + 1) and value[max_length + 1] != " ": + truncd_val = truncd_val[: truncd_val.rfind(" ")] + return truncd_val + "…" + return value + + +@register.filter +def fieldtype(bound_field): + try: + return camelcase_to_underscore(bound_field.field.__class__.__name__) + except AttributeError: + try: + return camelcase_to_underscore(bound_field.__class__.__name__) + except AttributeError: + return "" + + +@register.filter +def widgettype(bound_field): + try: + return camelcase_to_underscore(bound_field.field.widget.__class__.__name__) + except AttributeError: + try: + return camelcase_to_underscore(bound_field.widget.__class__.__name__) + except AttributeError: + return "" + + +def _get_user_page_permissions(context): + # Create a UserPagePermissionsProxy object to represent the user's global permissions, and + # cache it in the context for the duration of the page request, if one does not exist already + if "user_page_permissions" not in context: + context["user_page_permissions"] = UserPagePermissionsProxy( + context["request"].user + ) + + return context["user_page_permissions"] + + +@register.simple_tag(takes_context=True) +def page_permissions(context, page): + """ + Usage: {% page_permissions page as page_perms %} + Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out + what actions the current logged-in user can perform on the given page. + """ + return _get_user_page_permissions(context).for_page(page) + + +@register.simple_tag +def classnames(*classes): + """ + Usage
+ Returns any args as a space-separated joined string for using in HTML class names. + """ + return " ".join([classname.strip() for classname in classes if classname]) + + +@register.simple_tag(takes_context=True) +def test_collection_is_public(context, collection): + """ + Usage: {% test_collection_is_public collection as is_public %} + Sets 'is_public' to True iff there are no collection view restrictions in place + on this collection. + Caches the list of collection view restrictions in the context, to avoid repeated + DB queries on repeated calls. + """ + if "all_collection_view_restrictions" not in context: + context[ + "all_collection_view_restrictions" + ] = CollectionViewRestriction.objects.select_related("collection").values_list( + "collection__name", flat=True + ) + + is_private = collection.name in context["all_collection_view_restrictions"] + + return not is_private + + +@register.simple_tag(takes_context=True) +def test_page_is_public(context, page): + """ + Usage: {% test_page_is_public page as is_public %} + Sets 'is_public' to True iff there are no page view restrictions in place on + this page. + Caches the list of page view restrictions on the request, to avoid repeated + DB queries on repeated calls. + """ + if not hasattr(context["request"], "all_page_view_restriction_paths"): + context[ + "request" + ].all_page_view_restriction_paths = PageViewRestriction.objects.select_related( + "page" + ).values_list( + "page__path", flat=True + ) + + is_private = any( + [ + page.path.startswith(restricted_path) + for restricted_path in context["request"].all_page_view_restriction_paths + ] + ) + + return not is_private + + +@register.simple_tag +def hook_output(hook_name): + """ + Example: {% hook_output 'insert_editor_css' %} + Whenever we have a hook whose functions take no parameters and return a string, this tag can be used + to output the concatenation of all of those return values onto the page. + Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content. + """ + snippets = [fn() for fn in hooks.get_hooks(hook_name)] + return mark_safe("".join(snippets)) + + +@register.simple_tag +def base_url_setting(default=None): + return get_admin_base_url() or default + + +@register.simple_tag +def allow_unicode_slugs(): + return getattr(settings, "WAGTAIL_ALLOW_UNICODE_SLUGS", True) + + +class EscapeScriptNode(template.Node): + TAG_NAME = "escapescript" + + def __init__(self, nodelist): + super().__init__() + self.nodelist = nodelist + + def render(self, context): + out = self.nodelist.render(context) + return escape_script(out) + + @classmethod + def handle(cls, parser, token): + nodelist = parser.parse(("end" + EscapeScriptNode.TAG_NAME,)) + parser.delete_first_token() + return cls(nodelist) + + +register.tag(EscapeScriptNode.TAG_NAME, EscapeScriptNode.handle) + + +# Helpers for Widget.render_with_errors, our extension to the Django widget API that allows widgets to +# take on the responsibility of rendering their own error messages +@register.filter +def render_with_errors(bound_field): + """ + Usage: {{ field|render_with_errors }} as opposed to {{ field }}. + If the field (a BoundField instance) has errors on it, and the associated widget implements + a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism. + """ + widget = bound_field.field.widget + if bound_field.errors and hasattr(widget, "render_with_errors"): + return widget.render_with_errors( + bound_field.html_name, + bound_field.value(), + attrs={"id": bound_field.auto_id}, + errors=bound_field.errors, + ) + else: + return bound_field.as_widget() + + +@register.filter +def has_unrendered_errors(bound_field): + """ + Return true if this field has errors that were not accounted for by render_with_errors, because + the widget does not support the render_with_errors method + """ + return bound_field.errors and not hasattr( + bound_field.field.widget, "render_with_errors" + ) + + +@register.filter(is_safe=True) +@stringfilter +def cautious_slugify(value): + return _cautious_slugify(value) + + +@register.simple_tag(takes_context=True) +def querystring(context, **kwargs): + """ + Print out the current querystring. Any keyword arguments to this template + tag will be added to the querystring before it is printed out. + + + + Will result in something like: + + + """ + request = context["request"] + querydict = request.GET.copy() + # Can't do querydict.update(kwargs), because QueryDict.update() appends to + # the list of values, instead of replacing the values. + for key, value in kwargs.items(): + if value is None: + # Remove the key if the value is None + querydict.pop(key, None) + else: + # Set the key otherwise + querydict[key] = str(value) + + return "?" + querydict.urlencode() + + +@register.simple_tag(takes_context=True) +def page_table_header_label(context, label=None, parent_page_title=None, **kwargs): + """ + Wraps table_header_label to add a title attribute based on the parent page title and the column label + """ + if label: + translation_context = {"parent": parent_page_title, "label": label} + ascending_title_text = ( + _( + "Sort the order of child pages within '%(parent)s' by '%(label)s' in ascending order." + ) + % translation_context + ) + descending_title_text = ( + _( + "Sort the order of child pages within '%(parent)s' by '%(label)s' in descending order." + ) + % translation_context + ) + else: + ascending_title_text = None + descending_title_text = None + + return table_header_label( + context, + label=label, + ascending_title_text=ascending_title_text, + descending_title_text=descending_title_text, + **kwargs, + ) + + +@register.simple_tag(takes_context=True) +def table_header_label( + context, + label=None, + sortable=True, + ordering=None, + sort_context_var="ordering", + sort_param="ordering", + sort_field=None, + ascending_title_text=None, + descending_title_text=None, +): + """ + A label to go in a table header cell, optionally with a 'sort' link that alternates between + forward and reverse sorting + + label = label text + ordering = current active ordering. If not specified, we will fetch it from the template context variable + given by sort_context_var. (We don't fetch it from the URL because that wouldn't give the view method + the opportunity to set a default) + sort_param = URL parameter that indicates the current active ordering + sort_field = the value for sort_param that indicates that sorting is currently on this column. + For example, if sort_param='ordering' and sort_field='title', then a URL parameter of + ordering=title indicates that the listing is ordered forwards on this column, and a URL parameter + of ordering=-title indicated that the listing is ordered in reverse on this column + ascending_title_text = title attribute to use on the link when the link action will sort in ascending order + descending_title_text = title attribute to use on the link when the link action will sort in descending order + + To disable sorting on this column, set sortable=False or leave sort_field unspecified. + """ + if not sortable or not sort_field: + # render label without a sort link + return label + + if ordering is None: + ordering = context.get(sort_context_var) + reverse_sort_field = "-%s" % sort_field + + if ordering == sort_field: + # currently ordering forwards on this column; link should change to reverse ordering + attrs = { + "href": querystring(context, **{sort_param: reverse_sort_field}), + "class": "icon icon-arrow-down-after teal", + } + if descending_title_text is not None: + attrs["title"] = descending_title_text + + elif ordering == reverse_sort_field: + # currently ordering backwards on this column; link should change to forward ordering + attrs = { + "href": querystring(context, **{sort_param: sort_field}), + "class": "icon icon-arrow-up-after teal", + } + if ascending_title_text is not None: + attrs["title"] = ascending_title_text + + else: + # not currently ordering on this column; link should change to forward ordering + attrs = { + "href": querystring(context, **{sort_param: sort_field}), + "class": "icon icon-arrow-down-after", + } + if ascending_title_text is not None: + attrs["title"] = ascending_title_text + + attrs_string = format_html_join(" ", '{}="{}"', attrs.items()) + + return format_html( + # need whitespace around label for correct positioning of arrow icon + " {label} ", + attrs=attrs_string, + label=label, + ) + + +@register.simple_tag(takes_context=True) +def pagination_querystring(context, page_number, page_key="p"): + """ + Print out a querystring with an updated page number: + + {% if page.has_next_page %} + Next page + {% endif %} + """ + return querystring(context, **{page_key: page_number}) + + +@register.inclusion_tag( + "wagtailadmin/pages/listing/_pagination.html", takes_context=True +) +def paginate(context, page, base_url="", page_key="p", classname=""): + """ + Print pagination previous/next links, and the page count. Take the + following arguments: + + page + The current page of results. This should be a Django pagination `Page` + instance + + base_url + The base URL of the next/previous page, with no querystring. + This is optional, and defaults to the current page by just printing the + querystring for the next/previous page. + + page_key + The name of the page variable in the query string. Defaults to 'p'. + + classname + Extra classes to add to the next/previous links. + """ + request = context["request"] + return { + "base_url": base_url, + "classname": classname, + "request": request, + "page": page, + "page_key": page_key, + "paginator": page.paginator, + } + + +@register.inclusion_tag("wagtailadmin/pages/listing/_buttons.html", takes_context=True) +def page_listing_buttons(context, page, page_perms): + next_url = context.request.path + button_hooks = hooks.get_hooks("register_page_listing_buttons") + + buttons = [] + for hook in button_hooks: + buttons.extend(hook(page, page_perms, next_url)) + + buttons.sort() + + for hook in hooks.get_hooks("construct_page_listing_buttons"): + hook(buttons, page, page_perms, context) + + return {"page": page, "buttons": buttons} + + +@register.inclusion_tag( + "wagtailadmin/pages/listing/_modern_dropdown.html", takes_context=True +) +def page_header_buttons(context, page, page_perms): + next_url = context.request.path + button_hooks = hooks.get_hooks("register_page_header_buttons") + + buttons = [] + for hook in button_hooks: + buttons.extend(hook(page, page_perms, next_url)) + + buttons.sort() + return { + "page": page, + "buttons": buttons, + "title": _("Actions"), + "icon_name": "dots-horizontal", + "classes": [ + "w-flex", + "w-justify-center", + "w-items-center", + "w-h-slim-header", + ], + "button_classes": [ + "w-p-0", + "w-w-12", + "w-h-full", + "w-text-primary", + "w-bg-transparent", + "hover:w-scale-110", + "w-transition", + "w-outline-offset-inside", + "w-relative", + "w-z-30", + ], + "hide_title": True, + } + + +@register.inclusion_tag("wagtailadmin/pages/listing/_buttons.html", takes_context=True) +def bulk_action_choices(context, app_label, model_name): + bulk_actions_list = list( + bulk_action_registry.get_bulk_actions_for_model(app_label, model_name) + ) + bulk_actions_list.sort(key=lambda x: x.action_priority) + + bulk_action_more_list = [] + if len(bulk_actions_list) > 4: + bulk_action_more_list = bulk_actions_list[4:] + bulk_actions_list = bulk_actions_list[:4] + + next_url = get_valid_next_url_from_request(context["request"]) + if not next_url: + next_url = context["request"].path + + bulk_action_buttons = [ + PageListingButton( + action.display_name, + reverse( + "wagtail_bulk_action", args=[app_label, model_name, action.action_type] + ) + + "?" + + urlencode({"next": next_url}), + attrs={"aria-label": action.aria_label}, + priority=action.action_priority, + classes=action.classes | {"bulk-action-btn"}, + ) + for action in bulk_actions_list + ] + + if bulk_action_more_list: + more_button = ButtonWithDropdown( + label=_("More"), + attrs={"title": _("View more bulk actions")}, + classes={"bulk-actions-more", "dropup"}, + button_classes={"button", "button-small"}, + buttons_data=[ + { + "label": action.display_name, + "url": reverse( + "wagtail_bulk_action", + args=[app_label, model_name, action.action_type], + ) + + "?" + + urlencode({"next": next_url}), + "attrs": {"aria-label": action.aria_label}, + "priority": action.action_priority, + "classes": {"bulk-action-btn"}, + } + for action in bulk_action_more_list + ], + ) + bulk_action_buttons.append(more_button) + + return {"buttons": bulk_action_buttons} + + +@register.simple_tag +def message_level_tag(message): + """ + Return the tag for this message's level as defined in + django.contrib.messages.constants.DEFAULT_TAGS, ignoring the project-level + MESSAGE_TAGS setting (which end-users might customise). + """ + return MESSAGE_TAGS.get(message.level) + + +@register.simple_tag +def message_tags(message): + level_tag = message_level_tag(message) + if message.extra_tags and level_tag: + return message.extra_tags + " " + level_tag + elif message.extra_tags: + return message.extra_tags + elif level_tag: + return level_tag + else: + return "" + + +@register.filter("abs") +def _abs(val): + return abs(val) + + +@register.filter +def admin_urlquote(value): + return quote(value) + + +@register.simple_tag +def avatar_url(user, size=50, gravatar_only=False): + """ + A template tag that receives a user and size and return + the appropriate avatar url for that user. + Example usage: {% avatar_url request.user 50 %} + """ + + if ( + not gravatar_only + and hasattr(user, "wagtail_userprofile") + and user.wagtail_userprofile.avatar + ): + return user.wagtail_userprofile.avatar.url + + if hasattr(user, "email"): + gravatar_url = get_gravatar_url(user.email, size=size) + if gravatar_url is not None: + return gravatar_url + + return versioned_static_func("wagtailadmin/images/default-user-avatar.png") + + +@register.simple_tag +def js_translation_strings(): + return mark_safe(json.dumps(get_js_translation_strings())) + + +@register.simple_tag +def notification_static(path): + """ + Variant of the {% static %}` tag for use in notification emails - tries to form + a full URL using WAGTAILADMIN_BASE_URL if the static URL isn't already a full URL. + """ + return urljoin(base_url_setting(), static(path)) + + +@register.simple_tag +def versioned_static(path): + """ + Wrapper for Django's static file finder to append a cache-busting query parameter + that updates on each Wagtail version + """ + return versioned_static_func(path) + + +@register.inclusion_tag("wagtailadmin/shared/icon.html", takes_context=False) +def icon(name=None, classname=None, title=None, wrapped=False, class_name=None): + """ + Abstracts away the actual icon implementation. + + Usage: + {% load wagtailadmin_tags %} + ... + {% icon name="cogs" classname="icon--red" title="Settings" %} + + :param name: the icon name/id, required (string) + :param classname: defaults to 'icon' if not provided (string) + :param title: accessible label intended for screen readers (string) + :return: Rendered template snippet (string) + """ + if not name: + raise ValueError("You must supply an icon name") + + return { + "name": name, + # supporting class_name for backwards compatibility + "classname": classname or class_name or "icon", + "title": title, + "wrapped": wrapped, + } + + +@register.filter() +def timesince_simple(d): + """ + Returns a simplified timesince: + 19 hours, 48 minutes ago -> 19 hours ago + 1 week, 1 day ago -> 1 week ago + 0 minutes ago -> just now + """ + # Note: Duplicate code in timesince_last_update() + time_period = timesince(d).split(",")[0] + if time_period == avoid_wrapping(_("0 minutes")): + return _("just now") + return _("%(time_period)s ago") % {"time_period": time_period} + + +@register.simple_tag +def timesince_last_update( + last_update, show_time_prefix=False, user_display_name="", use_shorthand=True +): + """ + Returns: + - the time of update if last_update is today, if show_time_prefix=True, the output will be prefixed with "at " + - time since last update otherwise. Defaults to the simplified timesince, + but can return the full string if needed + """ + # translation usage below is intentionally verbose to be easier to work with translations + + if last_update.date() == datetime.today().date(): + if timezone.is_aware(last_update): + time_str = timezone.localtime(last_update).strftime("%H:%M") + else: + time_str = last_update.strftime("%H:%M") + + if show_time_prefix: + if user_display_name: + return _("at %(time)s by %(user_display_name)s") % { + "time": time_str, + "user_display_name": user_display_name, + } + else: + return _("at %(time)s") % {"time": time_str} + else: + if user_display_name: + return _("%(time)s by %(user_display_name)s") % { + "time": time_str, + "user_display_name": user_display_name, + } + else: + return time_str + else: + if use_shorthand: + # Note: Duplicate code in timesince_simple() + time_period = timesince(last_update).split(",")[0] + if time_period == avoid_wrapping(_("0 minutes")): + if user_display_name: + return _("just now by %(user_display_name)s") % { + "user_display_name": user_display_name + } + else: + return _("just now") + else: + time_period = timesince(last_update) + + if user_display_name: + return _("%(time_period)s ago by %(user_display_name)s") % { + "time_period": time_period, + "user_display_name": user_display_name, + } + else: + return _("%(time_period)s ago") % {"time_period": time_period} + + +@register.filter +def user_display_name(user): + """ + Returns the preferred display name for the given user object: the result of + user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. + """ + try: + full_name = user.get_full_name().strip() + if full_name: + return full_name + except AttributeError: + pass + + try: + return user.get_username() + except AttributeError: + # we were passed None or something else that isn't a valid user object; return + # empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }} + return "" + + +@register.filter +def format_content_type(content_type): + return get_content_type_label(content_type) + + +@register.simple_tag +def i18n_enabled(): + return getattr(settings, "WAGTAIL_I18N_ENABLED", False) + + +@register.simple_tag +def locales(): + return json.dumps( + [ + { + "code": locale.language_code, + "display_name": force_str(locale.get_display_name()), + } + for locale in Locale.objects.all() + ] + ) + + +@register.simple_tag +def locale_label_from_id(locale_id): + """ + Returns the Locale display name given its id. + """ + return get_locales_display_names().get(locale_id) + + +@register.simple_tag(takes_context=True) +def sidebar_collapsed(context): + request = context.get("request") + collapsed = request.COOKIES.get("wagtail_sidebar_collapsed", "0") + if collapsed == "0": + return False + return True + + +@register.simple_tag(takes_context=True) +def sidebar_props(context): + request = context["request"] + search_areas = admin_search_areas.search_items_for_request(request) + if search_areas: + search_area = search_areas[0] + else: + search_area = None + + account_menu = [ + sidebar.LinkMenuItem( + "account", _("Account"), reverse("wagtailadmin_account"), icon_name="user" + ), + sidebar.LinkMenuItem( + "logout", _("Log out"), reverse("wagtailadmin_logout"), icon_name="logout" + ), + ] + + modules = [ + sidebar.WagtailBrandingModule(), + sidebar.SearchModule(search_area) if search_area else None, + sidebar.MainMenuModule( + admin_menu.render_component(request), account_menu, request.user + ), + ] + modules = [module for module in modules if module is not None] + + return json_script( + { + "modules": JSContext().pack(modules), + }, + element_id="wagtail-sidebar-props", + ) + + +@register.simple_tag +def get_comments_enabled(): + return getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True) + + +@register.simple_tag(takes_context=True) +def wagtail_config(context): + request = context["request"] + config = { + "CSRF_TOKEN": get_token(request), + "CSRF_HEADER_NAME": HttpHeaders.parse_header_name( + getattr(settings, "CSRF_HEADER_NAME") + ), + "ADMIN_URLS": { + "DISMISSIBLES": reverse("wagtailadmin_dismissibles"), + }, + } + + default_settings = { + "WAGTAIL_AUTO_UPDATE_PREVIEW": True, + "WAGTAIL_AUTO_UPDATE_PREVIEW_INTERVAL": 500, + } + config.update( + { + option: getattr(settings, option, default) + for option, default in default_settings.items() + } + ) + + return config + + +@register.simple_tag +def resolve_url(url): + # Used by wagtailadmin/shared/pagination_nav.html - given an input that may be a URL route + # name, or a direct URL path, return it as a direct URL path. On failure (or being passed + # an empty / None value), return empty string + if not url: + return "" + + try: + return resolve_url_func(url) + except NoReverseMatch: + return "" + + +@register.simple_tag(takes_context=True) +def component(context, obj, fallback_render_method=False): + # Render a component by calling its render_html method, passing request and context from the + # calling template. + # If fallback_render_method is true, objects without a render_html method will have render() + # called instead (with no arguments) - this is to provide deprecation path for things that have + # been newly upgraded to use the component pattern. + + has_render_html_method = hasattr(obj, "render_html") + if fallback_render_method and not has_render_html_method and hasattr(obj, "render"): + return obj.render() + elif not has_render_html_method: + raise ValueError("Cannot render %r as a component" % (obj,)) + + return obj.render_html(context) + + +class FragmentNode(template.Node): + def __init__(self, nodelist, target_var): + self.nodelist = nodelist + self.target_var = target_var + + def render(self, context): + fragment = self.nodelist.render(context) if self.nodelist else "" + context[self.target_var] = fragment + return "" + + +@register.tag(name="fragment") +def fragment(parser, token): + """ + Store a template fragment as a variable. + + Usage: + {% fragment as header_title %} + {% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %} + {% endfragment %} + + Copy-paste of slippers’ fragment template tag. + See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L173. + """ + error_message = "The syntax for fragment is {% fragment as variable_name %}" + + try: + tag_name, _, target_var = token.split_contents() + nodelist = parser.parse(("endfragment",)) + parser.delete_first_token() + except ValueError: + if settings.DEBUG: + raise template.TemplateSyntaxError(error_message) + return "" + + return FragmentNode(nodelist, target_var) + + +class BlockInclusionNode(template.Node): + """ + Create template-driven tags like Django’s inclusion_tag / InclusionNode, but for block-level tags. + + Usage: + {% my_tag status="test" label="Alert" %} + Proceed with caution. + {% endmy_tag %} + + Within `my_tag`’s template, the template fragment will be accessible as the {{ children }} context variable. + + The output can also be stored as a variable in the parent context: + + {% my_tag status="test" label="Alert" as my_variable %} + Proceed with caution. + {% endmy_tag %} + + Inspired by slippers’ Component Node. + See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L47. + """ + + def __init__(self, nodelist, template, extra_context, target_var=None): + self.nodelist = nodelist + self.template = template + self.extra_context = extra_context + self.target_var = target_var + + def get_context_data(self, parent_context): + return parent_context + + def render(self, context): + children = self.nodelist.render(context) if self.nodelist else "" + + values = { + # Resolve the tag’s parameters within the current context. + key: value.resolve(context) + for key, value in self.extra_context.items() + } + + t = context.template.engine.get_template(self.template) + # Add the `children` variable in the rendered template’s context. + context_data = self.get_context_data({**values, "children": children}) + output = t.render(Context(context_data, autoescape=context.autoescape)) + + if self.target_var: + context[self.target_var] = output + return "" + + return output + + @classmethod + def handle(cls, parser, token): + tag_name, *remaining_bits = token.split_contents() + + nodelist = parser.parse((f"end{tag_name}",)) + parser.delete_first_token() + + extra_context = token_kwargs(remaining_bits, parser) + + # Allow component fragment to be assigned to a variable + target_var = None + if len(remaining_bits) >= 2 and remaining_bits[-2] == "as": + target_var = remaining_bits[-1] + + return cls(nodelist, cls.template, extra_context, target_var) + + +class DialogNode(BlockInclusionNode): + template = "wagtailadmin/shared/dialog/dialog.html" + + def get_context_data(self, parent_context): + context = super().get_context_data(parent_context) + + if "title" not in context: + raise TypeError("You must supply a title") + if "id" not in context: + raise TypeError("You must supply an id") + + # Used for determining which icon the message will use + message_icon_name = { + "info": "info-circle", + "warning": "warning", + "critical": "warning", + "success": "circle-check", + } + + message_status = context.get("message_status") + + # If there is a message status then determine which icon to use. + if message_status: + context["message_icon_name"] = message_icon_name[message_status] + + return context + + +register.tag("dialog", DialogNode.handle) + + +class HelpBlockNode(BlockInclusionNode): + template = "wagtailadmin/shared/help_block.html" + + +register.tag("help_block", HelpBlockNode.handle) + + +class PanelNode(BlockInclusionNode): + template = "wagtailadmin/shared/panel.html" + + +register.tag("panel", PanelNode.handle) + + +class FieldNode(BlockInclusionNode): + template = "wagtailadmin/shared/field.html" + + +register.tag("field", FieldNode.handle) + + +class FieldRowNode(BlockInclusionNode): + template = "wagtailadmin/shared/forms/field_row.html" + + +register.tag("field_row", FieldRowNode.handle) + + +# Button used to open dialogs +@register.inclusion_tag("wagtailadmin/shared/dialog/dialog_toggle.html") +def dialog_toggle(dialog_id, classname="", text=None): + if not dialog_id: + raise ValueError("You must supply the dialog ID") + + return { + "classname": classname, + "text": text, + # dialog_id must match the ID of the dialog you are toggling + "dialog_id": dialog_id, + } + + +@register.simple_tag() +def workflow_status_with_date(workflow_state): + translation_context = { + "finished_at": naturaltime(workflow_state.current_task_state.finished_at), + "started_at": naturaltime(workflow_state.current_task_state.started_at), + "task_name": workflow_state.current_task_state.task.name, + "status_display": workflow_state.get_status_display, + } + + if workflow_state.status == "needs_changes": + return _("Changes requested %(finished_at)s") % translation_context + + if workflow_state.status == "in_progress": + return _("Sent to %(task_name)s %(started_at)s") % translation_context + + return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context + + +@register.inclusion_tag("wagtailadmin/shared/human_readable_date.html") +def human_readable_date(date, description=None): + return { + "date": date, + "description": description, + } diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/__init__.py b/testbed/wagtail__wagtail/wagtail/admin/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/api/__init__.py b/testbed/wagtail__wagtail/wagtail/admin/tests/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/benches.py b/testbed/wagtail__wagtail/wagtail/admin/tests/benches.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2a34b9891ab281a08b804a1fd64a032b86292f --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/tests/benches.py @@ -0,0 +1,98 @@ +from __future__ import absolute_import, unicode_literals + +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone + +from wagtail.models import Page, Site +from wagtail.test.benchmark import Benchmark +from wagtail.test.testapp.models import SingleEventPage, StreamPage +from wagtail.test.utils import WagtailTestUtils + + +class BenchPageExplorerWith50LargePages(Benchmark, WagtailTestUtils, TestCase): + """ + Creates 50 pages with large body content and benches the explorer. + This will be slow if the body content is being loaded from the database. + """ + + def setUp(self): + self.root_page = Page.objects.get(id=1) + + # Add a site so the URLs render correctly + Site.objects.create(is_default_site=True, root_page=self.root_page) + + # Create a large piece of body text + body = ( + "[" + + ",".join(['{"type": "text", "value": "%s"}' % ("foo" * 2000)] * 100) + + "]" + ) + + # Create 50 simple pages with long content fields + for i in range(50): + self.root_page.add_child( + instance=StreamPage( + title="Page {}".format(i + 1), + slug=str(i + 1), + body=body, + ) + ) + + self.login() + + def bench(self): + response = self.client.get( + reverse("wagtailadmin_explore", args=(self.root_page.id,)) + ) + + # Check the response was good + self.assertEqual(response.status_code, 200) + + # Check every single page was rendered + self.assertContains(response, "Page 1") + self.assertContains(response, "Page 49") + + +class BenchPageExplorerWithCustomURLPages(Benchmark, WagtailTestUtils, TestCase): + """ + Creates 50 pages of a class with a customised the .url property. + This will check how long it takes to generate URLs for all of these + pages. + """ + + def setUp(self): + self.root_page = Page.objects.get(id=1) + + # Add a site so the URLs render correctly + Site.objects.create(is_default_site=True, root_page=self.root_page) + + # Create 50 blog pages + for i in range(50): + self.root_page.add_child( + instance=SingleEventPage( + title="Event {}".format(i + 1), + slug=str(i + 1), + date_from=timezone.now(), + audience="public", + location="reykjavik", + cost="cost", + ) + ) + + self.login() + + def bench(self): + response = self.client.get( + reverse("wagtailadmin_explore", args=(self.root_page.id,)) + ) + + # Check the response was good + self.assertEqual(response.status_code, 200) + + # Check every single page was rendered + self.assertContains(response, "Event 1") + self.assertContains(response, "Event 49") + + # Check the URLs were rendered correctly + self.assertContains(response, 'a href="http:///49/pointless-suffix/"') diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/pages/__init__.py b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/__init__.py b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_action.py b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_action.py new file mode 100644 index 0000000000000000000000000000000000000000..daea25e87149e94c0df2c19488359e4caf1c2410 --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_action.py @@ -0,0 +1,23 @@ +from django.test import TestCase +from django.urls import reverse + +from wagtail.test.utils import WagtailTestUtils + + +class TestBulkActionDispatcher(TestCase, WagtailTestUtils): + def setUp(self): + + # Login + self.user = self.login() + + def test_bulk_action_invalid_action(self): + url = reverse( + "wagtail_bulk_action", + args=( + "wagtailcore", + "page", + "ships", + ), + ) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py new file mode 100644 index 0000000000000000000000000000000000000000..1db62567615fa9c3b63e382ec4f78a1cff7ed7fc --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py @@ -0,0 +1,311 @@ +from unittest import mock + +from django.contrib.auth.models import Permission +from django.http import HttpRequest, HttpResponse +from django.test import TestCase +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ + +from wagtail.admin.views.pages.bulk_actions.page_bulk_action import PageBulkAction +from wagtail.models import Page +from wagtail.signals import page_unpublished +from wagtail.test.testapp.models import SimplePage +from wagtail.test.utils import WagtailTestUtils + + +class TestBulkUnpublish(TestCase, WagtailTestUtils): + def setUp(self): + # Create pages to unpublish + self.root_page = Page.objects.get(id=2) + self.child_pages = [ + SimplePage( + title=f"Hello world!-{i}", slug=f"hello-world-{i}", content=f"hello-{i}" + ) + for i in range(1, 5) + ] + # first three child pages will be unpublished + self.pages_to_be_unpublished = self.child_pages[:3] + self.pages_not_to_be_unpublished = self.child_pages[3:] + for child_page in self.child_pages: + self.root_page.add_child(instance=child_page) + + self.url = ( + reverse( + "wagtail_bulk_action", + args=( + "wagtailcore", + "page", + "unpublish", + ), + ) + + "?" + ) + for child_page in self.pages_to_be_unpublished: + self.url += f"&id={child_page.id}" + self.redirect_url = reverse("wagtailadmin_explore", args=(self.root_page.id,)) + + # Login + self.user = self.login() + + def test_unpublish_view(self): + """ + This tests that the unpublish view responds with an unpublish confirm page + """ + # Request confirm unpublish page + response = self.client.get(self.url) + + # Check that the user received an unpublish confirm page + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed( + response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html" + ) + + def test_unpublish_view_invalid_page_id(self): + """ + This tests that the unpublish view returns an error if the page id is invalid + """ + # Request confirm unpublish page but with illegal page id + response = self.client.get( + reverse( + "wagtail_bulk_action", + args=( + "wagtailcore", + "page", + "unpublish", + ), + ) + ) + + # Check that the user received a 404 response + self.assertEqual(response.status_code, 404) + + def test_unpublish_view_bad_permissions(self): + """ + This tests that the unpublish view doesn't allow users without unpublish permissions + """ + # Remove privileges from user + self.user.is_superuser = False + self.user.user_permissions.add( + Permission.objects.get( + content_type__app_label="wagtailadmin", codename="access_admin" + ) + ) + self.user.save() + + # Request confirm unpublish page + response = self.client.get(self.url) + + # Check that the user received a 200 redirected response + self.assertEqual(response.status_code, 200) + + html = response.content.decode() + + self.assertInHTML( + "

You don't have permission to unpublish these pages

", html + ) + + for child_page in self.pages_to_be_unpublished: + self.assertInHTML( + "
  • {page_title}
  • ".format(page_title=child_page.title), html + ) + + def test_unpublish_view_post(self): + """ + This posts to the unpublish view and checks that the page was unpublished + """ + # Connect a mock signal handler to page_unpublished signal + mock_handler = mock.MagicMock() + page_unpublished.connect(mock_handler) + + # Post to the unpublish page + response = self.client.post(self.url) + + # Should be redirected to explorer page + self.assertEqual(response.status_code, 302) + + # Check that the child pages were unpublished + for child_page in self.pages_to_be_unpublished: + self.assertFalse(SimplePage.objects.get(id=child_page.id).live) + + # Check that the child pages not to be unpublished remain + for child_page in self.pages_not_to_be_unpublished: + self.assertTrue(SimplePage.objects.get(id=child_page.id).live) + + # Check that the page_unpublished signal was fired + self.assertEqual(mock_handler.call_count, len(self.pages_to_be_unpublished)) + + for i, child_page in enumerate(self.pages_to_be_unpublished): + mock_call = mock_handler.mock_calls[i][2] + self.assertEqual(mock_call["sender"], child_page.specific_class) + self.assertEqual(mock_call["instance"], child_page) + self.assertIsInstance(mock_call["instance"], child_page.specific_class) + + def test_after_unpublish_page(self): + def hook_func(request, action_type, pages, action_class_instance): + self.assertEqual(action_type, "unpublish") + self.assertIsInstance(request, HttpRequest) + self.assertIsInstance(action_class_instance, PageBulkAction) + for i, page in enumerate(pages): + self.assertEqual(page.id, self.pages_to_be_unpublished[i].id) + + return HttpResponse("Overridden!") + + with self.register_hook("after_bulk_action", hook_func): + response = self.client.post(self.url) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, b"Overridden!") + + for child_page in self.pages_to_be_unpublished: + child_page.refresh_from_db() + self.assertEqual(child_page.status_string, _("draft")) + + def test_before_unpublish_page(self): + def hook_func(request, action_type, pages, action_class_instance): + self.assertEqual(action_type, "unpublish") + self.assertIsInstance(request, HttpRequest) + self.assertIsInstance(action_class_instance, PageBulkAction) + for i, page in enumerate(pages): + self.assertEqual(page.id, self.pages_to_be_unpublished[i].id) + + return HttpResponse("Overridden!") + + with self.register_hook("before_bulk_action", hook_func): + response = self.client.post(self.url) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, b"Overridden!") + + def test_unpublish_descendants_view(self): + """ + This tests that the unpublish view responds with an unpublish confirm page that does not contain the form field 'include_descendants' + """ + # Get unpublish page for page with no descendants + response = self.client.get(self.url) + + # Check that the user received an unpublish confirm page + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed( + response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html" + ) + # Check the form does not contain the checkbox field include_descendants + self.assertContains( + response, + 'name="include_descendants"', + count=0, + ) + + +class TestBulkUnpublishIncludingDescendants(TestCase, WagtailTestUtils): + def setUp(self): + # Find root page + self.root_page = Page.objects.get(id=2) + + self.child_pages = [ + SimplePage( + title=f"Hello world!-{i}", slug=f"hello-world-{i}", content=f"hello-{i}" + ) + for i in range(1, 5) + ] + # first three child pages will be unpublished + self.pages_to_be_unpublished = self.child_pages[:3] + self.pages_not_to_be_unpublished = self.child_pages[3:] + for child_page in self.child_pages: + self.root_page.add_child(instance=child_page) + + # map of the form { page: [child_pages] } to be added + self.grandchildren_pages = { + self.pages_to_be_unpublished[0]: [ + SimplePage( + title="Hello world!-a", slug="hello-world-a", content="hello-a" + ) + ], + self.pages_to_be_unpublished[1]: [ + SimplePage( + title="Hello world!-b", slug="hello-world-b", content="hello-b" + ), + SimplePage( + title="Hello world!-c", slug="hello-world-c", content="hello-c" + ), + ], + } + + for child_page, grandchild_pages in self.grandchildren_pages.items(): + for grandchild_page in grandchild_pages: + child_page.add_child(instance=grandchild_page) + + self.url = ( + reverse( + "wagtail_bulk_action", + args=( + "wagtailcore", + "page", + "unpublish", + ), + ) + + "?" + ) + for child_page in self.pages_to_be_unpublished: + self.url += f"&id={child_page.id}" + self.redirect_url = reverse("wagtailadmin_explore", args=(self.root_page.id,)) + + self.user = self.login() + + def test_unpublish_descendants_view(self): + """ + This tests that the unpublish view responds with an unpublish confirm page that contains the form field 'include_descendants' + """ + # Get unpublish page + response = self.client.get(self.url) + + # Check that the user received an unpublish confirm page + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed( + response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html" + ) + # Check the form contains the checkbox field include_descendants + self.assertContains( + response, + 'name="include_descendants"', + ) + + def test_unpublish_include_children_view_post(self): + """ + This posts to the unpublish view and checks that the page and its descendants were unpublished + """ + # Post to the unpublish page + response = self.client.post(self.url, {"include_descendants": "on"}) + + # Should be redirected to explorer page + self.assertEqual(response.status_code, 302) + + # Check that the child pages were unpublished + for child_page in self.pages_to_be_unpublished: + self.assertFalse(SimplePage.objects.get(id=child_page.id).live) + + # Check that the child pages not to be unpublished remain + for child_page in self.pages_not_to_be_unpublished: + self.assertTrue(SimplePage.objects.get(id=child_page.id).live) + + for grandchild_pages in self.grandchildren_pages.values(): + for grandchild_page in grandchild_pages: + self.assertFalse(SimplePage.objects.get(id=grandchild_page.id).live) + + def test_unpublish_not_include_children_view_post(self): + """ + This posts to the unpublish view and checks that the page was unpublished but its descendants were not + """ + # Post to the unpublish page + response = self.client.post(self.url, {}) + + # Should be redirected to explorer page + self.assertEqual(response.status_code, 302) + + # Check that the child pages were unpublished + for child_page in self.pages_to_be_unpublished: + self.assertFalse(SimplePage.objects.get(id=child_page.id).live) + + # Check that the descendant pages were not unpublished + for grandchild_pages in self.grandchildren_pages.values(): + for grandchild_page in grandchild_pages: + self.assertTrue(SimplePage.objects.get(id=grandchild_page.id).live) diff --git a/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_create_page.py b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_create_page.py new file mode 100644 index 0000000000000000000000000000000000000000..0c91484bf29fa6d8f63c5caa06ee07b8075b8904 --- /dev/null +++ b/testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_create_page.py @@ -0,0 +1,1762 @@ +import datetime +import unittest +from unittest import mock + +from django.contrib.auth.models import Group, Permission +from django.http import HttpRequest, HttpResponse +from django.test import TestCase +from django.test.utils import override_settings +from django.urls import reverse +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ + +from wagtail.models import GroupPagePermission, Locale, Page, Revision +from wagtail.signals import page_published +from wagtail.test.testapp.models import ( + BusinessChild, + BusinessIndex, + BusinessSubIndex, + DefaultStreamPage, + PersonPage, + SimpleChildPage, + SimplePage, + SimpleParentPage, + SingletonPage, + SingletonPageViaMaxCount, + StandardChild, + StandardIndex, +) +from wagtail.test.utils import WagtailTestUtils +from wagtail.test.utils.timestamps import submittable_timestamp + + +class TestPageCreation(TestCase, WagtailTestUtils): + def setUp(self): + # Find root page + self.root_page = Page.objects.get(id=2) + + # Login + self.user = self.login() + + def test_add_subpage(self): + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,)) + ) + self.assertEqual(response.status_code, 200) + + self.assertContains(response, "Simple page") + target_url = reverse( + "wagtailadmin_pages:add", args=("tests", "simplepage", self.root_page.id) + ) + self.assertContains(response, 'href="%s"' % target_url) + self.assertContains(response, "A simple page description") + # List of available page types should not contain pages with is_creatable = False + self.assertNotContains(response, "MTI base page") + # List of available page types should not contain abstract pages + self.assertNotContains(response, "Abstract page") + # List of available page types should not contain pages whose parent_page_types forbid it + self.assertNotContains(response, "Business child") + + def test_add_subpage_with_subpage_types(self): + # Add a BusinessIndex to test business rules in + business_index = BusinessIndex( + title="Hello world!", + slug="hello-world", + ) + self.root_page.add_child(instance=business_index) + + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(business_index.id,)) + ) + self.assertEqual(response.status_code, 200) + + self.assertContains(response, "Business child") + self.assertContains(response, "A lazy business child page description") + # List should not contain page types not in the subpage_types list + self.assertNotContains(response, "Simple page") + + def test_no_subpage_type_available_to_create(self): + # Test if all subpages have reached their max_count_per_parent limit + simple_parent_page = SimpleParentPage( + title="Hello World!", + slug="hello-world", + ) + self.root_page.add_child(instance=simple_parent_page) + simple_child_page = SimpleChildPage( + title="Hello World!", + slug="hello-world", + ) + simple_parent_page.add_child(instance=simple_child_page) + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(simple_parent_page.id,)) + ) + self.assertEqual(response.status_code, 200) + # if there is no page_type available then this message should be shown. + self.assertContains( + response, "Sorry, you cannot create a page at this location." + ) + self.assertNotContains( + response, "Choose which type of page you'd like to create." + ) + + def test_add_subpage_with_one_valid_subpage_type(self): + # Add a BusinessSubIndex to test business rules in + business_index = BusinessIndex( + title="Hello world!", + slug="hello-world", + ) + self.root_page.add_child(instance=business_index) + business_subindex = BusinessSubIndex( + title="Hello world!", + slug="hello-world", + ) + business_index.add_child(instance=business_subindex) + + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(business_subindex.id,)) + ) + # Should be redirected to the 'add' page for BusinessChild, the only valid subpage type + self.assertRedirects( + response, + reverse( + "wagtailadmin_pages:add", + args=("tests", "businesschild", business_subindex.id), + ), + ) + + def test_add_subpage_bad_permissions(self): + # Remove privileges from user + self.user.is_superuser = False + self.user.user_permissions.add( + Permission.objects.get( + content_type__app_label="wagtailadmin", codename="access_admin" + ) + ) + self.user.save() + + # Get add subpage page + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,)) + ) + + # Check that the user received a 403 response + self.assertEqual(response.status_code, 302) + + def test_add_subpage_nonexistantparent(self): + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(100000,)) + ) + self.assertEqual(response.status_code, 404) + + def test_add_subpage_with_next_param(self): + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,)), + {"next": "/admin/users/"}, + ) + self.assertEqual(response.status_code, 200) + + self.assertContains(response, "Simple page") + target_url = reverse( + "wagtailadmin_pages:add", args=("tests", "simplepage", self.root_page.id) + ) + self.assertContains(response, 'href="%s?next=/admin/users/"' % target_url) + + def test_create_simplepage(self): + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "simplepage", self.root_page.id), + ) + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(response["Content-Type"], "text/html; charset=utf-8") + self.assertContains( + response, + '', + ) + self.assertContains( + response, + '', + ) + # test register_page_action_menu_item hook + self.assertContains( + response, + '', + ) + self.assertContains(response, "testapp/js/siren.js") + # test construct_page_action_menu hook + self.assertContains( + response, + '', + ) + # test that workflow actions are shown + self.assertContains( + response, + '", + ) + + @override_settings(WAGTAIL_MODERATION_ENABLED=False) + def test_hide_moderation_button(self): + """ + Tests that if WAGTAIL_MODERATION_ENABLED is set to False, the "Submit for Moderation" button is not shown. + """ + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "simplepage", self.root_page.id), + ) + ) + self.assertNotContains( + response, + '', + ) + + def test_create_sets_locale_to_parent_locale(self): + # We need to make sure the page's locale it set to the parent in the create view so that any customisations + # for that language will take effect. + fr_locale = Locale.objects.create(language_code="fr") + fr_homepage = self.root_page.add_child( + instance=Page( + title="Home", + slug="home-fr", + locale=fr_locale, + ) + ) + + response = self.client.get( + reverse( + "wagtailadmin_pages:add", args=("tests", "simplepage", fr_homepage.id) + ) + ) + + self.assertEqual(response.context["page"].locale, fr_locale) + + +class TestPermissionedFieldPanels(TestCase, WagtailTestUtils): + fixtures = ["test.json"] + + def setUp(self): + # Find root page + self.root_page = Page.objects.get(id=2) + GroupPagePermission.objects.create( + group=Group.objects.get(name="Site-wide editors"), + page=self.root_page, + permission_type="add", + ) + + def test_create_page_with_permissioned_field_panel(self): + """ + Test that permission rules on field panels are honoured + """ + # non-superusers should not see secret_data + self.login(username="siteeditor", password="password") + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "secretpage", self.root_page.id), + ) + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, '"boring_data"') + self.assertNotContains(response, '"secret_data"') + + # superusers should see secret_data + self.login(username="superuser", password="password") + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "secretpage", self.root_page.id), + ) + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, '"boring_data"') + self.assertContains(response, '"secret_data"') + + +class TestSubpageBusinessRules(TestCase, WagtailTestUtils): + def setUp(self): + # Find root page + self.root_page = Page.objects.get(id=2) + + # Add standard page (allows subpages of any type) + self.standard_index = StandardIndex() + self.standard_index.title = "Standard Index" + self.standard_index.slug = "standard-index" + self.root_page.add_child(instance=self.standard_index) + + # Add business page (allows BusinessChild and BusinessSubIndex as subpages) + self.business_index = BusinessIndex() + self.business_index.title = "Business Index" + self.business_index.slug = "business-index" + self.root_page.add_child(instance=self.business_index) + + # Add business child (allows no subpages) + self.business_child = BusinessChild() + self.business_child.title = "Business Child" + self.business_child.slug = "business-child" + self.business_index.add_child(instance=self.business_child) + + # Add business subindex (allows only BusinessChild as subpages) + self.business_subindex = BusinessSubIndex() + self.business_subindex.title = "Business Subindex" + self.business_subindex.slug = "business-subindex" + self.business_index.add_child(instance=self.business_subindex) + + # Login + self.login() + + def test_standard_subpage(self): + add_subpage_url = reverse( + "wagtailadmin_pages:add_subpage", args=(self.standard_index.id,) + ) + + # explorer should contain a link to 'add child page' + response = self.client.get( + reverse("wagtailadmin_explore", args=(self.standard_index.id,)) + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, add_subpage_url) + + # add_subpage should give us choices of StandardChild, and BusinessIndex. + # BusinessSubIndex and BusinessChild are not allowed + response = self.client.get(add_subpage_url) + self.assertEqual(response.status_code, 200) + self.assertContains(response, StandardChild.get_verbose_name()) + self.assertContains(response, BusinessIndex.get_verbose_name()) + self.assertNotContains(response, BusinessSubIndex.get_verbose_name()) + self.assertNotContains(response, BusinessChild.get_verbose_name()) + + def test_business_subpage(self): + add_subpage_url = reverse( + "wagtailadmin_pages:add_subpage", args=(self.business_index.id,) + ) + + # explorer should contain a link to 'add child page' + response = self.client.get( + reverse("wagtailadmin_explore", args=(self.business_index.id,)) + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, add_subpage_url) + + # add_subpage should give us a cut-down set of page types to choose + response = self.client.get(add_subpage_url) + self.assertEqual(response.status_code, 200) + self.assertNotContains(response, StandardIndex.get_verbose_name()) + self.assertNotContains(response, StandardChild.get_verbose_name()) + self.assertContains(response, BusinessSubIndex.get_verbose_name()) + self.assertContains(response, BusinessChild.get_verbose_name()) + + def test_business_child_subpage(self): + add_subpage_url = reverse( + "wagtailadmin_pages:add_subpage", args=(self.business_child.id,) + ) + + # explorer should not contain a link to 'add child page', as this page doesn't accept subpages + response = self.client.get( + reverse("wagtailadmin_explore", args=(self.business_child.id,)) + ) + self.assertEqual(response.status_code, 200) + self.assertNotContains(response, add_subpage_url) + + # this also means that fetching add_subpage is blocked at the permission-check level + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(self.business_child.id,)) + ) + self.assertEqual(response.status_code, 302) + + def test_cannot_add_invalid_subpage_type(self): + # cannot add StandardChild as a child of BusinessIndex, as StandardChild is not present in subpage_types + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "standardchild", self.business_index.id), + ) + ) + self.assertRedirects(response, "/admin/") + + # likewise for BusinessChild which has an empty subpage_types list + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "standardchild", self.business_child.id), + ) + ) + self.assertRedirects(response, "/admin/") + + # cannot add BusinessChild to StandardIndex, as BusinessChild restricts is parent page types + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "businesschild", self.standard_index.id), + ) + ) + self.assertRedirects(response, "/admin/") + + # but we can add a BusinessChild to BusinessIndex + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "businesschild", self.business_index.id), + ) + ) + self.assertEqual(response.status_code, 200) + + def test_not_prompted_for_page_type_when_only_one_choice(self): + response = self.client.get( + reverse("wagtailadmin_pages:add_subpage", args=(self.business_subindex.id,)) + ) + # BusinessChild is the only valid subpage type of BusinessSubIndex, so redirect straight there + self.assertRedirects( + response, + reverse( + "wagtailadmin_pages:add", + args=("tests", "businesschild", self.business_subindex.id), + ), + ) + + +class TestInlinePanelMedia(TestCase, WagtailTestUtils): + """ + Test that form media required by InlinePanels is correctly pulled in to the edit page + """ + + def test_inline_panel_media(self): + homepage = Page.objects.get(id=2) + self.login() + + # simplepage does not need draftail... + response = self.client.get( + reverse("wagtailadmin_pages:add", args=("tests", "simplepage", homepage.id)) + ) + self.assertEqual(response.status_code, 200) + self.assertNotContains(response, "wagtailadmin/js/draftail.js") + + # but sectionedrichtextpage does + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "sectionedrichtextpage", homepage.id), + ) + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "wagtailadmin/js/draftail.js") + + +class TestInlineStreamField(TestCase, WagtailTestUtils): + """ + Test that streamfields inside an inline child work + """ + + def test_inline_streamfield(self): + homepage = Page.objects.get(id=2) + self.login() + + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "inlinestreampage", homepage.id), + ) + ) + self.assertEqual(response.status_code, 200) + + # response should include HTML declarations for streamfield child blocks + self.assertContains(response, '