This commit introduces the `behaviorTransformer` API to safely override behaviors defined in Discourse.
Two new plugin APIs are introduced:
- `addBehaviorTransformerName` which allows plugins and theme-components to add a new valid transformer name if they want to provide overridable behaviors;
- `registerBehaviorTransformer` to register a transformer to override behaviors.
It also introduces the function `applyBehaviorTransformer` which can be imported from `discourse/lib/transformer`. This is used to mark a callback containing the desired behavior as overridable and applies the transformer logic.
How does it work?
## Marking a behavior as overridable:
To mark a behavior as overridable, in Discourse core, first the transformer name must be added to `app/assets/javascripts/discourse/app/lib/transformer/registry.js`. For plugins and theme-components, use the plugin API `addBehaviorTransformerName` instead.
Then, in your component or class, use the function `applyBehaviorTransformer` to mark the Behavior as overridable and handle the logic:
- example:
```js
...
@action
loadMore() {
applyBehaviorTransformer(
"discovery-topic-list-load-more",
() => {
this.documentTitle.updateContextCount(0);
return this.model
.loadMore()
.then(({ moreTopicsUrl, newTopics } = {}) => {
if (
newTopics &&
newTopics.length &&
this.bulkSelectHelper?.bulkSelectEnabled
) {
this.bulkSelectHelper.addTopics(newTopics);
}
if (moreTopicsUrl && $(window).height() >= $(document).height()) {
this.send("loadMore");
}
});
},
{ model: this.model }
);
},
...
```
## Overriding a behavior in plugins or themes
To override a behavior in plugins, themes, or TCs use the plugin API `registerBehaviorTransformer`:
- Example:
```js
withPluginApi("1.35.0", (api) => {
api.registerBehaviorTransformer("example-transformer", ({ context, next }) => {
console.log('we can introduce new behavior here instead', context);
next(); // call next to execute the expected behavior
});
});
```
Ember's legacy mixin system does not support native-class syntax, so we have to use the non-decorator syntaxes for `action()` and `computed()`.
Eventually, we will need to refactor things to remove these mixins... but today is not that day.
When creating a shared draft, we're recording topic view stats on the draft and then pass those on when the draft is published, conflating the actual view count.
This fixes that by not registering topic views if the topic is a shared draft.
When `SiteSetting.review_every_post` is true and the category `require_topic_approval` system creates two reviewable items.
1. Firstly, because the category needs approval, the `ReviewableQueuePost` record` is created - at this stage, no topic is created.
2. Admin is approving the review. The topic and first post are created.
3. Because `review_every_post` is true `queue_for_review_if_possible` callback is evaluated and `ReviewablePost` is created.
4. Then `ReviewableQueuePost` is linked to the newly generated topic and post.
At the beginning, we were thinking about hooking to those guards:
```
def self.queue_for_review_if_possible(post, created_or_edited_by)
return unless SiteSetting.review_every_post
return if post.post_type != Post.types[:regular] || post.topic.private_message?
return if Reviewable.pending.where(target: post).exists?
...
```
And add something like
```
return if Reviewable.approved.where(target: post).exists?
```
However, because the callback happens in point 3. before the `ReviewableQueuePost` is linked to the `Topic`, it was not possible.
Therefore, when `ReviewableQueuePost` is creating a `Topic`, a new option called `:reviewed_queued_post` is passed to `PostCreator` to avoid creating a second `Reviewable`.
Currently, descriptions for flag types aren’t interpolated, returning
`%{base_path}` in their string, for example. This breaks the navigation
on the sites.
The behavior changed probably because of an upgrade of Ruby, as two
hashes were passed to `I18n.t` (`vars` and `default`) without using the
splat operator.
Similar to https://github.com/discourse/discourse/pull/28061, merging topics with many posts can exceed the 30 seconds timeout that Unicorn workers are limited to, so we should move the operation into a background thread to get around this limit.
Internal topic: t/133710.
* SECURITY: Update default allowed iframes list
Change the default iframe url list to all include 3 slashes.
* SECURITY: limit group tag's name length
Limit the size of a group tag's name to 100 characters.
Internal ref - t/130059
* SECURITY: Improve sanitization of SVGs in Onebox
---------
Co-authored-by: Blake Erickson <o.blakeerickson@gmail.com>
Co-authored-by: Régis Hanol <regis@hanol.fr>
Co-authored-by: David Taylor <david@taylorhq.com>
Followup 4aea12fdcb
In certain config areas (like About) we want to be able
to fetch specific site settings by name. In this case,
sometimes we need to be able to fetch hidden settings,
in cases where a config area is still experimental.
Splitting out a different endpoint for this purpose
allows us to be stricter with what we return for config
areas without affecting the main site settings UI, revealing
hidden settings before they are ready.
`addCommunitySectionLink` API function accepts secondary argument to determine if the link should be added to the primary or secondary (more) section. There was a bug and all links were mounted in the secondary section.
We have a dedicated admin page (`/admin/customize/email_templates`) that lets admins customize all emails that Discourse sends to users. The way this page works is that it lists all translations strings that are used for emails, and the list of translation strings is currently hardcoded and hasn't been updated in years. We've had a number of new emails that Discourse sends, so we should add those templates to the list to let admins easily customize those templates.
Meta topic: https://meta.discourse.org/t/3-2-x-still-ignores-some-custom-email-templates/308203.
In this case, there is no 'nearPost' param in the URL. Instead, the server preloads a post-stream with whichever page of posts is requested. We can check for that situation using `postStream.firstPostPresent`.
Also updates the widget-header version to fetch a value from the service on initial render, instead of relying on the observer triggering.
Followup to bdec564d14
Currently, if MF definitions are missing (typically because there’s a
compilation error), `I18n.messageFormat` will try to access
`I18n._mfMessages.hasMessage` resulting in a crash that will in turn
crash Ember.
This patch addresses the issue by using the optional chaining operator
making the `I18n.messageFormat` method return a "Missing Key" message.
MF strings won’t be rendered properly, but the site will stay usable.
* FIX: Ensure JsLocaleHelper to obly outputs up-to-date translations
The old implementation forgot to filter out deprecated
translations, causing these translations to incorrectly override the new
locale in the frontend.
This commit fills in the forgotten where clause, filtering only the
up-to-date part.
Related meta topic: https://meta.discourse.org/t/outdated-translation-replacement-causing-missing-translation/314352
By default, the swc minifier seems to unwrap 'unneeded' IIFE. That means it was undoing the 'bugfix' transformation we have for class fields in Safari 15. Disabling the 'inline' and 'reduce_funcs' options seems to stop this behavior.
Currently, when adding translation overrides, values aren’t validated
for MF strings. This results in being able to add invalid plural keys or
even strings containing invalid syntax.
This patch addresses this issue by compiling the string when saving an
override if the key is detected as an MF one.
If there’s an error from the compiler, it’s added to the model errors,
which in turn is displayed to the user in the admin UI, helping them to
understand what went wrong.
When we show user tips, we immediately send an AJAX request to mark the
tiup as seen. This is done in the background. However, when system tests
are run, sometimes that request is not completed before the test ends.
This causes the test to be flakey.
One way to fix this is to force the system test run to wait for the AJAX
request to complete. However, this is not ideal because it makes the
test suite slower on each run.
Instead, this commit removes the flakey assertion and adds an alternative
assertion in the frontend tests that ensures the background request is
sent when the user tip is shown.
Form Kit is our new form library/framework for unifying the way forms look across Discourse. The admin config area for the /about page is a new form that isn't currently used, so it makes sense for it to be one of the first forms to be migrated to Form Kit to test the library.
Co-authored-by: Joffrey JAFFEUX <j.jaffeux@gmail.com>
* `@ember/owner` instead of `@ember/application`
* `discourse-i18n` instead of `I18n`
* `{ service } from "@ember/service"` instead of `inject as service`
In an attempt to improve build performance, 9db5eafb mistakenly removed minimization for some of our JS assets, leading to a significant increase in the size of some files.
This commit restores minimization to those files. To avoid regressing on the build time improvements, this commit switches to using the `webpack-terser-plugin`'s "swcMinify" option. On an entry-level 1CPU/1GB-ram/2GB-swap DO droplet, this commit increases build time from ~16 minutes to ~18 minutes.
Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
Performing a bulk action on many topics can exceed the 30 seconds timeout that Unicorn workers have which results in the request failing and the operation getting aborted. To get around this 30 seconds timeout, we can push the operation into a background thread using the rack `hijack` API.
Internal topic: t/133779.
In development, classes are lazy loaded so `Jobs::Onceoff.onceoff_job_klasses`
may not have been set. This is not a problem in production cause stuff
is eager loaded.
Follow-up to f4d06f195d
* FIX: Add post id to the anchor to prevent two identical anchors
We generate anchors for headings in posts. This works fine if there is
only one post in a topic with anchors. The problem comes when you have
two or more posts with the same heading. PrettyText generates anchors
based on the heading text using the raw context of each post, so it is
entirely possible to generate the same anchor for two posts in the same
topic, especially for topics with template replies
Post1:
# heading
context
Post2:
# heading
context
When both posts are on the page at the same time, the anchor will only
work for the first post, according to the [HTML specification](https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier).
> If there is an a element in the document tree whose root is document
> that has a name attribute whose value is equal to fragment, then
> return the *first* such element in tree order.
This bug is particularly serious in forums with non-Latin languages,
such as Chinese. We do not generate slugs for Chinese, which results in
the heading anchors being completely dependent on their order.
```ruby
[2] pry(main)> PrettyText.cook("# 中文")
=> "<h1><a name=\"h-1\" class=\"anchor\" href=\"#h-1\"></a>中文</h1>"
```
Therefore, the anchors in the two posts must be in exactly the same by
order, causing almost all of the anchors in the second post to be
invalid.
This commit solves this problem by adding the `post_id` to the anchor.
The new anchor generation method will add `p-{post_id}` as a prefix when
post_id is available:
```ruby
[3] pry(main)> PrettyText.cook("# 中文", post_id: 1234)
=> "<h1><a name=\"p-1234-h-1\" class=\"anchor\" href=\"#p-1234-h-1\"></a>中文</h1>"
```
This way we can ensure that each anchor name only appears once on the
same topic. Using post id also prevents the potential possibility of the
same anchor name when splitting/merging topics.
We are investigating a memory leak in Sidekiq and saw the following line
when comparing heap dumps over time.
`Allocated IMEMO 14775 objects of size 591000/7389528 (in bytes) at:
/var/www/discourse/app/jobs/onceoff/onceoff.rb:36`
That line in question was doing a `.select { |klass| klass < self }` on
`ObjectSpace.each_object(Class)`. This for some reason is allocating a
whole bunch of `IMEMO` objects which are instruction sequence objects.
Instead of diving deeper into why this might be leaking, we can just
save our time by switching to an implementation that is more efficient
and does not require looping through a ton of objects.
Disabling webpack minimize is a bug we are working to resolve but we
have to consider self-hosters that deploy on low cost hardware
and reenabling this for them drastically increases the build time.
For now, add a `DISCOURSE_WEBPACK_MINIMIZE` env to allow sites to opt
back in.
Previously in these 2 PRs, we introduced a new site setting `SiteSetting.enforce_second_factor_on_external_auth`.
https://github.com/discourse/discourse/pull/27547https://github.com/discourse/discourse/pull/27674
When disabled, it should enforce 2FA for local login with username and password and skip the requirement when authenticating with oauth2.
We stored information about the login method in a secure session but it is not reliable. Therefore, information about the login method is moved to the database.
This commit also attempts to promote more declarative patterns. The route history logic has been replaced by using the history-store service.
---------
Co-authored-by: Jarek Radosz <jarek@cvx.dev>
Co-authored-by: David Taylor <david@taylorhq.com>
This commit changes the group SMTP settings form (at
`/g/:name/manage/email`) to use
FormKit, our magical new form component system ✨
---------
Co-authored-by: Joffrey JAFFEUX <j.jaffeux@gmail.com>
- Ensure main title is set as 'not visible' when removed from DOM
- `deactivate` -> `willTransition` to ensure proper behavior when navigating between multiple topics
Followup to bdec564d14
- Move topic-title on-screen detection to intersection-observer (via new modifier), and add a boolean to header service which indicates whether it's on-screen
- Move scroll-direction from Mixin to dedicated service. Teach it to pause scroll monitoring while transitions are in progress, to avoid reporting false changes in scroll direction. Also resets to a 'neutral' state after each navigation, which indicates the the user has not yet scrolled
- When entering a topic view, notify the header service which post is being targeted. It can then make an educated guess about whether the topic title is likely to be in-view
- Update header service `topicInfoVisible` to be a declarative getter, based on the three refactored sources of truth mentioned above
- Update legacy widget header to use the header service for topic info
All of these changes mean that the header no longer 'flickers' when navigating into topics on mobile. As well as the improved UX, this should also improve our Cumulative Layout Shift (CLS) web vital metrics.
Fixed using next instead. It was causing this kind of errors:
```
Job exception: unexpected return
/var/www/discourse/app/controllers/topics_controller.rb:1304:in `block in defer_topic_view'
/var/www/discourse/lib/scheduler/defer.rb:115:in `block in do_work'
rails_multisite-6.0.0/lib/rails_multisite/connection_management/null_instance.rb:49:in `with_connection'
rails_multisite-6.0.0/lib/rails_multisite/connection_management.rb:21:in `with_connection'
/var/www/discourse/lib/scheduler/defer.rb:109:in `do_work'
/var/www/discourse/lib/scheduler/defer.rb:97:in `block (2 levels) in start_thread'
```
* FEATURE: Clean up previously logged information after permanently deleting posts
When soft deleteing a topic or post, we will log some details in the
staff log, including the raw content of the post. Before this commit, we
will not clear the information in these records. Therefore, after
permanently deleting the post, `UserHistory` still retains copy of the
permanently deleted post. This is an unexpected behaviour and may raise
some potential legal issues.
This commit adds a behavior that when a post is permanently deleted, the
details column of the `UserHistory` associated with the post will be
overwritten to "(permanently deleted)". At the same time, for permanent
deletion, a new `action_id` is introduced to distinguish it from soft
deletion.
Related meta topic: https://meta.discourse.org/t/introduce-a-way-to-also-permanently-delete-the-sensitive-info-from-the-staff-logs/292546
Followup dd30463276
We missed the explicit `return` when we changed to
async/await, so the model ends up being null on admin
backups.
This means we also have no tests for the backup UI, that
will be fixed in a subsequent PR.
There is a bug with chat type flags - "An error occurred: Applies to is not included in the list"
Flag.valid_applies_to_types is a set of core types and types registered by plugins `Set.new(DEFAULT_VALID_APPLIES_TO | DiscoursePluginRegistry.flag_applies_to_types)`
Using lamba should ensure that valid values are calculated dynamically.
This commit promotes the new topic bulk action
menu introduced in 89883b2f51
to the main method of bulk selecting and performing
actions on topics. The site setting flag gating this
feature is deleted, and the old bulk select code is
deleted as well.
The new modal shows a loading spinner while operations
are taking place, allows selecting the action from a dropdown
instead of having a 2-step modal flow,
and also supports additional options for some operations, e.g.
allowing Close silently.
Replaces the existing topic map with the experimental-topic-map made by @awesomerobot.
---------
Co-authored-by: awesomerobot <kris.aubuchon@discourse.org>
This commit introduces the foundation for a new design for the /about page that we're currently working on. The current version will remain available and still be the default until we finish the new version and are ready to roll out. To opt into the new version right now, add one or more group to the `experimental_redesigned_about_page_groups` site setting and members in those groups will get the new version.
Internal topic: t/128545.
* FEATURE: Add logging for CustomEmoji
We didn't provide any logs for CustomEmoji before, nor did we record the
person who added any emoji in the database. As a result, the staff had
no way to trace back who added a certain emoji.
This commit adds a new column `user_id` to `custom_emojis` to record the
creator of an emoji. At the same time, a log is added for staff logs to
record who added or deleted a custom emoji.
If a user has a required action, e.g. adding a 2FA method or filling in new required fields, we disable client-side routing except to allowed pages.
This led to a situation where a user might navigate away from e.g. the profile page to look at the new ToS, and then being "stuck" due to not knowing how to get back to accept the new terms.
This PR makes it so that if you click any restricted link, instead of doing nothing we transition the user back to the page where they can take the required action.
User actions can trigger functions that render changes to the screen within the same cycle (e.g. pressing the reply button will cause the login modal to pop up), potentially impacting performance and causing some jank on slower devices.
This change inserts runAfterFramePaint where certain actions are triggered. Below are some screenshots indicating an improved INP for some of the buttons affected on controls with the highest INPs. The two places where this is added help with several actions, e.g. user + group cards, generic button action usage.
Usage:
```
@validation="integer"
```
This commit also adds a default for rules. By default a rule will now be `ruleName: {}`, this avoids all the boilerplate in validation-parser.js.
We'd implemented the deprecation by overriding `get parentView`, and storing the real value on `_parentView`. Unfortunately that meant people could access `_parentView` directly, thereby bypassing the deprecation message.
This commit moves the internal storage to a private field, which cannot be accessed from outside the class. A deprecated getter for `_parentView` is introduced to avoid immediate breakage for any code using this workaround.