Utils

This package contains utilities which facilitate specific tasks and can be re-used and imported from different locations.

Account Activation Token Generator

This module contains helpers for the account activation process (also see AccountActivationView).

class integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator[source]

Bases: PasswordResetTokenGenerator

This token generator is identical to the default password reset token generator of django.contrib.auth with the exception of the used HMAC salt. This means password reset tokens are no longer accepted for the account activation and vice versa.

key_salt = 'integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator'[source]

The key salt which is passed to the HMAC function

integreat_cms.cms.utils.account_activation_token_generator.account_activation_token_generator = <integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator object>[source]

The token generator for the account activation process (an instance of AccountActivationTokenGenerator)

Content Edit Lock

This file contains a mechanism to lock a content editor for other people while a person is using it.

integreat_cms.cms.utils.content_edit_lock.get_cache_key(id_: int | str, type_: str) str[source]

This function returns the key that is used to lock a content object in the cache. It should not be used outside of this module.

Parameters:
  • id – The id of the content object

  • type – The type of the content object

  • id_ (int | str) –

  • type_ (str) –

Returns:

The key to use

Return type:

str

integreat_cms.cms.utils.content_edit_lock.get_locking_user(id_: int | str | None, type_: str) User | None[source]

This function returns the user that locks a specific object

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • id_ (int | str | None) –

  • type_ (str) –

Returns:

The user that holds the lock for this content object or None

Return type:

User | None

integreat_cms.cms.utils.content_edit_lock.lock_content(id_: int | None, type_: str, user: User) bool[source]

This function tries to lock a content object for a user. If it is already locked by someone else, nothing will happen. If it is already locked by the same user, the timeout gets reset.

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • user (User) – The user that should get unique access to this content object

  • id_ (int | None) –

  • type_ (str) –

Returns:

Whether the content object could be locked

Return type:

bool

integreat_cms.cms.utils.content_edit_lock.unlock_content(id_: int | None, type_: str, user: User) bool[source]

This function tries to unlock a content object for a user. If it is not locked by the passed user, nothing will happen.

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • user (User) – The user that wants to release the lock

  • id_ (int | None) –

  • type_ (str) –

Returns:

Whether the content object could be unlocked

Return type:

bool

Email Utils

integreat_cms.cms.utils.email_utils.send_mail(subject: str, email_template_name: str, html_email_template_name: str, context: dict[str, Any], recipient: str) None[source]

Sends welcome email to user with new account.

Making use of EmailMultiAlternatives and MIMEImage to send a multipart email with plain text and html version and also attach the branding logo.

Parameters:
  • subject (str) – The subject of the email

  • email_template_name (str) – The template to be used to render the text email

  • html_email_template_name (str) – The template to be used to render the HTML email

  • subject – The subject of the email

  • context (dict[str, Any]) – The template context variables

  • recipient (str) – The email address of the recipient

Return type:

None

File Utils

This module contains helpers for file handling.

integreat_cms.cms.utils.file_utils.create_zip_archive(source_file_paths: list[str], zip_file_path: str) None[source]

Create zip file from list of source files

Parameters:
  • source_file_paths (list[str]) – list of files to be zipped

  • zip_file_path (str) – path to zipped file

Return type:

None

integreat_cms.cms.utils.file_utils.extract_zip_archive(zip_file_path: str, target_directory: str, allowed_file_extensions: Any | None = None) tuple[list[str], list][source]

Extract zip file and return file paths of content. Returns a tuple of extracted and invalid files:

extracted_files, invalid_files = extract_zip_archive(zip_file_path, target_directory, allowed_file_extensions)

If want to extract all files regardless of their extension, discard the second return value:

extracted_files, _ = extract_zip_archive(zip_file_path, target_directory)
Parameters:
  • zip_file_path (str) – path to zip file

  • target_directory (str) – directory to where the files should be extracted

  • allowed_file_extensions (Any | None) – list of allowed file extensions. If None or empty list, all extensions are allowed.

Returns:

a tuple of two lists of the valid and invalid filenames

Return type:

tuple[list[str], list]

Linkcheck Utils

integreat_cms.cms.utils.linkcheck_utils.filter_urls(region_slug: str | None = None, url_filter: str | None = None, prefetch_content_objects: bool = True) tuple[list[Url], dict[str, int]][source]

Filter all urls of one region by the given category

Parameters:
  • region_slug (str | None) – The slug of the current region

  • url_filter (str | None) – Which urls should be returned (one of valid, invalid, ignored, unchecked). If parameter is not in these choices or omitted, all urls are returned by default.

  • prefetch_content_objects (bool) – Whether or not content objects should be prefetched

Returns:

A tuple of the requested urls and a dict containing the counters of all remaining urls

Return type:

tuple[list[Url], dict[str, int]]

integreat_cms.cms.utils.linkcheck_utils.fix_content_link_encoding(content: str) str[source]

Fix the encoding of punycode domains in an html content string

Parameters:

content (str) – The input content

Returns:

The fixed content

Return type:

str

integreat_cms.cms.utils.linkcheck_utils.fix_domain_encoding(url: Match[str]) str[source]

Fix the encoding of punycode domains

Parameters:

url (Match[str]) – The input url match

Returns:

The fixed url

Return type:

str

integreat_cms.cms.utils.linkcheck_utils.get_region_links(region: Region) Query[source]

Returns the links of translations of the given region :param region: The region :return: A query containing the relevant links

Parameters:

region (Region) –

Return type:

Query

integreat_cms.cms.utils.linkcheck_utils.get_url_count(region_slug: str | None = None) dict[str, int][source]

Count all urls by status. The content objects are not prefetched because they are not needed for the counter.

Parameters:

region_slug (str | None) – The slug of the current region

Returns:

A dictionary containing the counters of all remaining urls

Return type:

dict[str, int]

integreat_cms.cms.utils.linkcheck_utils.get_urls(region_slug: str | None = None, url_ids: Any | None = None, prefetch_content_objects: bool = True) list[Url][source]

Collect all the urls which appear in the latest versions of the contents of the region, filtered by ID or region if given.

Parameters:
  • region_slug (str | None) – The slug of the current region

  • url_ids (Any | None) – The list of requested url ids

  • prefetch_content_objects (bool) – Whether or not content objects should be prefetched

Returns:

The list (or queryset) of urls

Return type:

list[Url]

integreat_cms.cms.utils.linkcheck_utils.replace_link_helper(old_url: str, new_url: str, link: str) str[source]

A small helper function which can be passed to lxml.html.HtmlMixin.rewrite_links()

Parameters:
  • old_url (str) – The url which should be replaced

  • new_url (str) – The url which should be inserted instead of the old url

  • link (str) – The current link

Returns:

The replaced link

Return type:

str

integreat_cms.cms.utils.linkcheck_utils.replace_links(search: str, replace: str, *, region: Region | None = None, user: User | None = None, commit: bool = True, link_types: list[str] | None = None) None[source]

Perform search & replace in the content links

Parameters:
  • search (str) – The (partial) URL to search

  • replace (str) – The (partial) URL to replace

  • region (Region | None) – Optionally limit the replacement to one region (None means a global replacement)

  • user (User | None) – The creator of the replaced translations

  • commit (bool) – Whether changes should be written to the database

  • link_types (list[str] | None) – Which kind of links should be replaced

Return type:

None

integreat_cms.cms.utils.linkcheck_utils.save_new_version(translation: AbstractContentTranslation, new_translation: AbstractContentTranslation, user: Any | None) None[source]

Save a new translation version

Parameters:
Return type:

None

Media Utils

Utility functions for the media management. Most of the functions are used to transform media data to other data types.

integreat_cms.cms.utils.media_utils.generate_thumbnail(original_image: InMemoryUploadedFile, size: int = 300, crop: bool = False) InMemoryUploadedFile | None[source]

Creates a thumbnail for a given media_file.

Parameters:
  • original_image (InMemoryUploadedFile) – Original image for the thumbnail

  • size (int) – Desired size of the thumbnail (maximum for height and with), defaults to MEDIA_THUMBNAIL_SIZE

  • crop (bool) – Whether the thumbnail should be cropped (resulting in a square regardless of the initial aspect ratio), defaults to MEDIA_THUMBNAIL_CROP

Returns:

The created thumbnail in memory

Return type:

InMemoryUploadedFile | None

MFA Utils

This module contains helpers for multi-factor-authentication tasks.

integreat_cms.cms.utils.mfa_utils.generate_challenge(challenge_len: int) str[source]

This function generates a random challenge of the given length. It consists of ascii letters and digits.

Example usage: GetMfaChallengeView

Parameters:

challenge_len (int) – The desired length of the challenge

Returns:

A random string of the requested length

Return type:

str

integreat_cms.cms.utils.mfa_utils.get_mfa_user(request: HttpRequest) User | None[source]

Get the user from the session if it exists. This method can be used for the passwordless login, as well as the usual login mode.

Parameters:

request (HttpRequest) – The current request

Returns:

The user

Return type:

User | None

PDF Utils

integreat_cms.cms.utils.pdf_utils.generate_pdf(region: Region, language_slug: str, pages: PageQuerySet) HttpResponseRedirect[source]

Function for handling a pdf export request for pages. The pages were either selected by cms user or by API request (see pdf_export()) For more information on xhtml2pdf, see Welcome to xhtml2pdf’s documentation!

Parameters:
  • region (Region) – region which requested the pdf document

  • language_slug (str) – bcp47 slug of the current language

  • pages (PageQuerySet) – at least on page to render as PDF document

Returns:

Redirection to PDF document

Return type:

HttpResponseRedirect

integreat_cms.cms.utils.pdf_utils.link_callback(uri: str, rel: str) str | None[source]

According to xhtml2pdf documentation (see Usage), this function is necessary for resolving the django static files references. It returns the absolute paths to the files on the file system.

Parameters:
  • uri (str) – URI that is generated by django template tag ‘static’

  • rel (str) – The relative path directory

Returns:

The absolute path on the file system according to django’s static file settings

Return type:

str | None

Slug Utils

This module contains helpers regarding unique string identifiers without special characters (“slugs”).

integreat_cms.cms.utils.slug_utils.generate_unique_slug(**kwargs: Unpack[SlugKwargs]) str[source]

This function can be used in forms to clean slug fields. It will make sure the slug field contains a unique identifier per region and language. It can also be used for region slugs (foreign_model is None in this case). If the slug field is empty, it creates a fallback value from either the title or the name field. In case the slug exists already, it appends a counter which is increased until the slug is unique.

Example usages:

Parameters:

**kwargs (Unpack[SlugKwargs]) – The supplied keyword arguments

Raises:

ValidationError – When no slug is given and there is also no field which can be used as fallback (either title or name).

Returns:

An unique slug identifier

Return type:

str

integreat_cms.cms.utils.slug_utils.generate_unique_slug_helper(form_object: ModelForm, foreign_model: ForeignModelType) str[source]

This function acts like an interface and extracts all parameters of the form_object before actually generating the unique slug, so that unique slug generation can be performed without any cleaned form data after a form submission.

Parameters:
  • form_object (ModelForm) – The form which contains the slug field

  • foreign_model (ForeignModelType) – If the form instance has a foreign key to another model (e.g. because it is a translation of a content-object), this parameter contains the model of the foreign related object.

Raises:

ValidationError – When no slug is given and there is also no field which can be used as fallback (either title or name).

Returns:

An unique slug identifier

Return type:

str

Stringify List

integreat_cms.cms.utils.stringify_list.iter_to_string(iterable: Iterable, *, quotation_char: str = '"', max_items: int = 5) str[source]

This is a helper function that turns a list into a string using different delimiters.

Parameters:
  • iterable (Iterable) – List of items

  • quotation_char (str) – The character that is added around each item in the list

  • max_items (int) – The maximum number of items in the iterable to display

Returns:

Returns string with the single items separated by comma expect the last item which is separated by ‘and’.

Return type:

str

Text Utils

This module contains helpers for strings.

integreat_cms.cms.utils.text_utils.lowfirst(string: Promise) str[source]

Make the first letter of a string lowercase (counterpart of capfirst(), see also capfirst).

Parameters:

string (Promise) – The input text

Returns:

The lowercase text

Return type:

str

integreat_cms.cms.utils.text_utils.truncate_bytewise(string: str, length: int) str[source]

Truncate a UTF-8 encoded string to a maximum byte length.

Parameters:
  • string (str) – The input text

  • length (int) – The maximum length of the text in byte representation

Returns:

The truncated text

Return type:

str

Totp Utils

This module contains helper functions that are used within the TOTP registration and authentication.

integreat_cms.cms.utils.totp_utils.check_totp_code(given_totp_code: str, key: str) bool[source]

Helper method to check the given code with the initial key

Parameters:
  • given_totp_code (str) – The entered TOTP code form the user

  • key (str) – The key that is used for the generation of the true code

Returns:

True if the given code matches the initiated

Return type:

bool

integreat_cms.cms.utils.totp_utils.generate_totp_qrcode(key: str, user: User) str[source]

Render event form for HTTP GET requests

Parameters:
  • key (str) – The required key to generate the QR code

  • user (User) – The user account that is trying to add TOTP to its account

Returns:

The QR code as a base64-encoded string

Return type:

str

Translation Utils

This module contains helpers for the gettext translation process of UI languages.

integreat_cms.cms.utils.translation_utils.gettext_many_lazy(*strings: Any) Promise[source]

This function is a wrapper for django.utils.text.format_lazy() for the special case that the given strings should be concatenated with a space in between. This is useful for splitting lazy translated strings by sentences which improves the translation memory.

Parameters:

*strings (Any) – A list of lazy translated strings which should be concatenated

Returns:

A lazy formatted string

Return type:

Promise

integreat_cms.cms.utils.translation_utils.translate_link(message: Promise | str, attributes: dict[str, str]) SafeString[source]

Translate a link with keeping the HTML tags and still escaping all unknown parts of the message

Parameters:
  • message (Promise | str) – The translated message that contains the link placeholder <a>{link_text}</a>

  • attributes (dict[str, str]) – A dictionary of attributes for the link

Returns:

A correctly escaped formatted string with the translated message and the HTML link

Return type:

SafeString

User Utils

integreat_cms.cms.utils.user_utils.search_users(region: Region | None, query: str) QuerySet[User][source]

Searches for all users that match the given query. If region is None, all users are searched. :param region: The current region :param query: The query string used for filtering the regions :return: A query for all matching objects

Parameters:
Return type:

QuerySet[User]

Welcome Mail Utils

integreat_cms.cms.utils.welcome_mail_utils.send_welcome_mail(request: HttpRequest, user: User, activation: bool) None[source]

Sends welcome email to user with new account.

Making use of EmailMultiAlternatives and MIMEImage to send a multipart email with plain text and html version and also attach the integreat logo.

Parameters:
  • request (HttpRequest) – The current http request

  • user (User) – The user to whom the e-mail is to be sent

  • activation (bool) – Activation link should be generated

Return type:

None