Commit Graph

9573 Commits

Author SHA1 Message Date
Isaac Janzen 366ff0e76b
FIX: Don't display destroy reviewable button on client (#21226)
# Context

https://meta.discourse.org/t/missing-translate-in-review-page/262604

![image](https://user-images.githubusercontent.com/50783505/234089049-72332040-e7d5-4081-824a-b0b36e37187a.png)

An additional button was added as a result of dd495a0e19 which was intended to grant access to deleting reviewable from the API. 

We were being too flexible by only checking if the user was an admin

012aaf0ba3/lib/guardian.rb (L237)

where it should instead by scoped to check if the request was an API call.

# Fix

https://github.com/discourse/discourse/pull/21226/files#diff-0a2548be4b18bd4ef2dffb3ef8e44984d2fef7f037b53e98f67abea52ef75aa2R237

# Additions

Added a new guard of `is_api?`

https://github.com/discourse/discourse/pull/21226/files#diff-0a2548be4b18bd4ef2dffb3ef8e44984d2fef7f037b53e98f67abea52ef75aa2R657-R660

In `app/models/reviewable.rb` we check if the user has the permissions to the destroy action via the `Guardian`. To do this we were instantiating a new `Guardian` class which then caused us to lose the context of the request. The request is a necessary component in the guard of `is_api?` so we needed to pass the already defined Guardian from the `app/controllers/reviewables_controller.rb` to the `#perform` method to ensure the request is present.
2023-04-24 20:22:37 -05:00
David Taylor 6cb733d6c7
FIX: Ensure skip-module JS is transpiled correctly (#21224)
This regressed in 7e74dd0afe, and was causing issues with 2fa security keys on the email verification route
2023-04-24 17:39:02 +01:00
David Taylor 26b7f8a63b
DEV: Improve add_to_serializer include_* options (#21220)
- Move the old '`define_include_method`' arg to a `respect_plugin_enabled` kwarg

- Introduce an `include_condition` kwarg which can be passed a lambda with inclusion logic. Lambda will be run via `instance_exec` in the context of the serializer instance

This is backwards compatible - old-style invocations will trigger a deprecation message
2023-04-24 12:17:51 +01:00
Natalie Tay e1bc43aa31
Revert "DEV: Improve `add_to_serializer` `include_*` options (#21073)" (#21219)
This reverts commit 4895e76ef7.
2023-04-24 16:14:52 +08:00
David Taylor 4895e76ef7
DEV: Improve `add_to_serializer` `include_*` options (#21073)
- Move the old '`define_include_method`' arg to a `respect_plugin_enabled` kwarg
- Introduce an `include_condition` kwarg which can be passed a lambda with inclusion logic. Lambda will be run via `instance_exec` in the context of the serializer instance

This is backwards compatible - old-style invocations will trigger a deprecation message

Update chat and poll plugins to new pattern
2023-04-24 15:47:28 +10:00
David Taylor 56115977c0
DEV: Patch Sprockets::DirectiveProcessor to avoid extra newline (#21203)
By default, the Sprockets DirectiveProcessor introduces a newline between possible 'header' comments and the rest of the JS file. This causes sourcemaps to be offset by 1 line, and therefore breaks browser tooling. We know that Ember-Cli assets do not use Sprockets directives, so we can totally bypass the DirectiveProcessor for those files.

We're using v3 of Sprockets, which is no longer supported - upstreaming a fix will be difficult. Long term, we intend to move away from sprockets.
2023-04-21 19:35:00 +01:00
Daniel Waterworth a4d51810e2
DEV: Correct ambiguous name (#21189)
This file would do different things depending on whether
Migration::Migration existed beforehand.
2023-04-20 11:28:08 -05:00
Isaac Janzen 0d2f8c1a45
DEV: Use guards to make `can_delete_reviewable` guardian more readable (#21188) 2023-04-20 11:07:35 -05:00
Isaac Janzen dd495a0e19
FEATURE: Allow admins to delete reviewables via API (#21174)
This PR adds the ability to destroy reviewables for a passed user via the API. This was not possible before as this action was reserved for reviewables for you created only.

If a user is an admin and calls the `#destroy` action from the API they are able to destroy a reviewable for a passed user. A user can be targeted by passed either their:
- username
- external_id (for SSO) 

to the request.

In the case you attempt to destroy a non-personal reviewable and
- You are not an admin
- You do not access the `#destroy` action via the API

you will raise a `Discourse::InvalidAccess` (403) and will not succeed in destroying the reviewable.
2023-04-20 09:38:41 -05:00
Jarek Radosz 43e0025141
Revert "DEV: Merge package.json files (#21172)" (#21182)
This reverts commit 49a1e1cd0e.

Is causing issues in prod-adjacent environments (Jenkins)
2023-04-20 14:57:40 +02:00
Jarek Radosz 49a1e1cd0e
DEV: Merge package.json files (#21172)
This means: a single yarn.lock and removing one of the package.json files
2023-04-20 12:46:12 +02:00
Ted Johansson e002a24eca
FEATURE: Add new don't feed the trolls feature (#21001)
Responding to negative behaviour tends to solicit more of the same. Common wisdom states: "don't feed the trolls".

This change codifies that advice by introducing a new nudge when hitting the reply button on a flagged post. It will be shown if either the current user, or two other users (configurable via a site setting) have flagged the post.
2023-04-20 15:49:35 +08:00
Martin Brennan 6442bbf46c
DEV: Reintroduce chat rake dev generate tasks (#21164)
This is to help generate random channels and chat
messages for local dev. This was removed in 12a18d4d55
presumably because it was not worth refactoring at the
time.

I've only added these tasks:

- `rake chat:message:populate\[113,20\]` (channel_id, count)
  - Generates the count of messages for a channel ID provided,
    otherwise uses a random channel and 200 count.
- `rake chat:category_channel:populate`
  - Creates a chat channel for a random category.
- `rake chat🧵populate\[132,5\]` (channel_id, message_count)
  - Creates a thread with N messages in the specified channel,
    and enables threading in that channel if necessary
2023-04-20 10:53:10 +10:00
Gerhard Schlager 1ee87cbfa3 FEATURE: Detect current git "branch" even when a tag is checked out
It switches to a different command for detecting the current git branch because the old command always returned HEAD as branch when the git repository is on a detached head (e.g. tag). The new command doesn't return a branch when the repository is on a detached head, which allows us to fall back to the `version` variable that is stored in the git config since https://github.com/discourse/discourse_docker/pull/707. It contains the value of the `version` from `app.yml`.

It also includes a small change to specs, because our tests usually run on specific commits instead of a branch or tag, so Discourse.git_branch always returns "unknown". We can use the "unknown" branch for tests, so it makes sense to ignore it only in other envs.
2023-04-19 15:30:12 +02:00
Gerhard Schlager f523dcf9df REFACTOR: Simplify git command execution 2023-04-19 15:30:12 +02:00
Blake Erickson 76874b7098
FIX: 500 error when adding restricted category tags (#21147)
This fixes a 500 error that occurs when adding a tag to a category's
restricted tag list if the category's restricted tags already included a
synonym tag.
2023-04-18 11:01:11 -06:00
Ted Johansson ca82752976
Version bump to v3.1.0.beta4 (#21135) 2023-04-18 16:14:41 +08:00
Ted Johansson 437b73e322
SECURITY: Ensure site setting being updated is a configurable site setting (#21131) 2023-04-18 14:32:18 +08:00
Alan Guo Xiang Tan 1f0207ba06
DEV: Add support for more filters for `/filter` route (#21097)
* DEV: Support `likes-(min:max):<count>` on `/filter` route

This commit adds support for the following filters: 

1. `likes-min` 
2. `likes-max`
3. `views-min`
4. `views-max`
5. `likes-op-min`
6. `likes-op-max`

If the filter has an invalid value, i.e string that cannot be converted
into an integer, the filter will be ignored.

If either of each filter is specify multiple times, only the last
occurrence of each filter will be taken into consideration.
2023-04-14 10:21:04 +08:00
Alan Guo Xiang Tan 782b26d0eb
DEV: Support `posters-(min|max):<count>` on `/filter` route (#21095)
This commit adds support for the `posters-min:<count>` and
`posters-max:<count>` filters for the topics filtering query language.
`posters-min:1` will filter for topics with at least a one poster while
`posters-max:3` will filter for topics with a maximum of 3 posters.

If the filter has an invalid value, i.e string that cannot be converted
into an integer, the filter will be ignored.

If either of each filter is specify multiple times, only the last
occurence of each filter will be taken into consideration.
2023-04-14 07:48:38 +08:00
Alan Guo Xiang Tan bc4a9c50f2
DEV: Support `posts-min:<count>` and `posts-max:<count>` on `/filter` (#21090)
This commit adds support for the `posts-min:<count>` and
`posts-max:<count>` filters for the topics filtering query language.
`posts-min:1` will filter for topics with at least a one post while
`posts-max:3` will filter foor topics with a maximum of 3 posts.

If the filter has an invalid value, i.e string that cannot be converted
into an integer, the filter will be ignored.

If either of each filter is specify multiple times, only the last
occurence of each filter will be taken into consideration.
2023-04-14 06:05:55 +08:00
David Taylor e52f322cb5
UX: Use dominant color while loading onebox images (#21091)
When we "pull hotlinked images" on onebox images, they are added to the uploads table and their dominant color is calculated. This commit adds the data to the HTML so that it can be used by the client in the same way as non-onebox images. It also adds specific handling to the new `discourse-lazy-videos` plugin.
2023-04-13 12:04:46 +01:00
David Battersby 967010e545
FEATURE: Add an emoji deny list site setting (#20929)
This feature will allow sites to define which emoji are not allowed. Emoji in this list should be excluded from the set we show in the core emoji picker used in the composer for posts when emoji are enabled. And they should not be allowed to be chosen to be added to messages or as reactions in chat.

This feature prevents denied emoji from appearing in the following scenarios:
- topic title and page title
- private messages (topic title and body)
- inserting emojis into a chat
- reacting to chat messages
- using the emoji picker (composer, user status etc)
- using search within emoji picker

It also takes into account the various ways that emojis can be accessed, such as:
- emoji autocomplete suggestions
- emoji favourites (auto populates when adding to emoji deny list for example)
- emoji inline translations
- emoji skintones (ie. for certain hand gestures)
2023-04-13 15:38:54 +08:00
Alan Guo Xiang Tan 5b1306cb54
DEV: Refactor `TopicsFilter` (#21071)
Why this change?

Previously `TopicsFilter` was designed in such a way that we act on a
filter sequentially based on the order it was matched. However, this
made it hard to support filters composition where a similar filter may
be present further in the query string. Because of this limitation, I
previously introduced a private API `TopicsFilter.register_scope` which
allows us to act on a filter only after the entire query string has been
scanned. However, I felt that it made the code complicated and hard to
reason about.

In thie commit, I've changed it such that we scan through the entire
query string and group the values of each filter together. This allows
us to act on the values of a given filter in one go which I find easier
to reason about. This also opens up the possibility for us to ignore
certain filters when it has been specified multiple times.
2023-04-13 13:22:11 +08:00
David Taylor 121d5c6c6a
UX: Enable new notifications menu by default (#21060)
https://meta.discourse.org/t/260358
2023-04-12 09:45:29 +01:00
Alan Guo Xiang Tan a1524b84e2
DEV: Support `created-by:<username>` filter on `/filter` route (#21067)
This commit adds support for the `created-by:<username>` query filter
which will return topics created by the specified user. Multiple
usernames can be specified by comma seperating the usernames like so:
`created-by:username1,username2`. This will filter for topics created by
either of the specified users. Multiple `created-by:<username>` can also
be composed together. `created-by:username1 created-by:username2` is
equivalent to `created-by:username1,username2`.
2023-04-12 09:25:06 +08:00
Penar Musaraj 0ab3ba5f0d
SECURITY: strip `xlink:href` from uploaded SVGs (#21057)
This was inadvertently removed in 4c46c7e. In very specific scenarios,
this could be used execute arbitrary JavaScript.

Only affects instances where SVGs are allowed as uploads and CDN is not
configured.
2023-04-11 14:10:44 -04:00
David Taylor 9238767f7e
FEATURE: Persist password hashing algorithm/params in database (#20980)
Previously, Discourse's password hashing was hard-coded to a specific algorithm and parameters. Any changes to the algorithm or parameters would essentially invalidate all existing user passwords.

This commit introduces a new `password_algorithm` column on the `users` table. This persists the algorithm/parameters which were use to generate the hash for a given user. All existing rows in the users table are assumed to be using Discourse's current algorithm/parameters. With this data stored per-user in the database, we'll be able to keep existing passwords working while adjusting the algorithm/parameters for newly hashed passwords.

Passwords which were hashed with an old algorithm will be automatically re-hashed with the new algorithm when the user next logs in.

Values in the `password_algorithm` column are based on the PHC string format (https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md). Discourse's existing algorithm is described by the string `$pbkdf2-sha256$i=64000,l=32$`

To introduce a new algorithm and start using it, make sure it's implemented in the `PasswordHasher` library, then update `User::TARGET_PASSWORD_ALGORITHM`.
2023-04-11 10:16:28 +01:00
Alan Guo Xiang Tan 2809d7ba8e
DEV: Support `in:<notification level>` filter on `/filter` route (#21038)
This commit adds support for the `in:<topic notification level>` query
filter. As an example, `in:tracking` will filter for topics that the
user is watching. Filtering for multiple topic notification levels can
be done by comma separating the topic notification level keys. For
example, `in:muted,tracking` or `in:muted,tracking,watching`.
Alternatively, the user can also compose multiple filters with `in:muted
in:tracking` which translates to the same behaviour as
`in:muted,tracking`.
2023-04-11 08:48:07 +08:00
Daniel Waterworth c68497159f
FIX: Use string for postgres recently readonly DistributedCache (#21040)
Since DistributedCaches don't marshal timestamps
2023-04-10 13:54:55 -05:00
Sérgio Saquetim f8fb7ee9f3
DEV: Introduced topic_query_create_list_topics modifier (#21016)
Introduced a modifier on topic_query to change list while they're created

Co-authored-by: Jarek Radosz <jradosz@gmail.com>
2023-04-07 13:01:42 -03:00
Alan Guo Xiang Tan b2a951e4a5
DEV: Support `in:bookmarked` filter for the `/filter` route (#21000)
This filters the topics list to the topics that the current user has bookmarks in.
2023-04-06 12:55:28 +08:00
Alan Guo Xiang Tan ab54a616c1
DEV: Introduce `in:pinned` filter for experimental `/filter` route (#20974)
This commit adds support for the `in:pinned` filter to the topics filtering
query language. When the filter is present, it will filter for topics
where `Topic#pinned_until` is greater than `Topic#pinned_at`.
2023-04-06 10:13:02 +08:00
Alan Guo Xiang Tan 5bec894a8c
PERF: Fix N+1 queries problem when listing topics list (#20971)
This performance regression was introduced in
7c6a8f1c74 where the preloading of tags in
`TopicQuery` was accidentally removed.
2023-04-06 06:58:35 +08:00
Mark VanLandingham 65f35e1ef2
FEATURE: SiteSetting for creation of small action on tag change (#20812)
This adds a SiteSetting, which when enabled, creates a small_action post for tag/category changes to the topic. It uses `topic.add_moderator_post, and passes raw text in, to describe the change.
2023-04-05 13:31:31 -05:00
David Taylor d3e5251704
PERF: Use `OpenSSL::KDF` for Pbkdf2 implementation (#20982)
This was introduced to the standard library in Ruby 2.4. In my testing, it produces the same result, and is around 8x faster than our pure-ruby implementation
2023-04-05 17:00:05 +01:00
David Taylor df849e51b7
DEV: Add plugin hook for transforming site setting defaults (#20941) 2023-04-05 12:28:16 +01:00
Alan Guo Xiang Tan 62696b9ee7
DEV: Properly support composing multiple category filters on `/filter` (#20953)
Before this commit, composing multiple category filters with a query such as category:category1 and category:category2 would not return any results. This is because we were filtering for topics that belonged to both category1 and category2, which is impossible since a topic can only belong to a single category.

With this commit, specifying a query like category:category1 category:category2 will now translate to filtering for topics that belong to either the category1 or category2 category.
2023-04-05 07:16:37 +08:00
Bianca Nenciu 9ff105973f
FEATURE: Allow invite only and Discourse connect (#20961)
Invite only and Discourse connect could not be enabled at the same time
because of some legacy reason. This is a follow up commit to ce04db8,
355d51a and 40f6ceb.
2023-04-04 19:52:11 +03:00
Jarek Radosz 29e2e3ff3b
DEV: Fix random typos (#20937) 2023-04-03 19:27:32 +02:00
Roman Rizzi ecac62dd6f
DEV: Make search results blurb non-pg headlines setting dependent (#20939)
Followup to #20915. If we're grouping search results that don't rely on core's search, we won't have access to pg headlines. This is now configurable via the constructor, defaulting to `SiteSetting.use_pg_headlines_for_excerpt`
2023-04-03 11:09:36 -03:00
David Taylor f3402be262
DEV: Introduce `Migration::Helpers` for new-site detection (#20934)
We use schema_migration_details to determine the age of a site in multiple migrations. This commit moves the logic into a dedicated `Migration::Helpers` module so that it doesn't need to be re-implemented every time.
2023-04-03 11:46:39 +01:00
Alan Guo Xiang Tan fd34032db2
DEV: Support filter for topics in specific subcategories on /filter (#20927)
This commit adds support for filtering for topics in specific
subcategories via the categories filter query language.

For example: `category:documentation:admins` will filter for topics and
subcategory topics in
the category with slug "admins" whose parent category has the slug
"documentation".

The `=` prefix can also be used such that
`=category:documentation:admins` will exclude subcategory topics of the
category with slug "admins" whose parent category has the slug
"documentation".
2023-04-03 18:36:59 +08:00
Alan Guo Xiang Tan 0162f0ccb0
DEV: Update experimental `/filter` route with categories support (#20911)
On the `/filter` route, the categories filtering query language is now
supported in the input per the example provided below:

```
category:bug => topics in the bug category AND all subcategories
=category:bug => topics in the bug category excluding subcategories
category:bug,feature => allow for categories either in bug or feature
=category:bug,feature => allow for exact categories match excluding sub cats
categories: => alias for category
```

Currently composing multiple category filters is not supported as we
have yet to determine what behaviour it should result in. For example,
`category:bug category:feature` would now return topics that are in both
the `bug` and `feature` category but it is not possible for a topic to
belong to two categories.
2023-03-31 14:32:12 +08:00
Sam 347681dd20
DEV: add topic_query_suggested_options modifier (#20893)
Add a modifier that will allow us to tune the results returned by suggested.

At the moment the modifier allows us to toggle including random results.
This was created for the discourse-ai module. It needs to switch off random
results when it returns related topics.

Longer term we can use it to toggle unread/new and other aspects.

This also demonstrates how to test the contract when adding modifiers.
2023-03-31 09:03:15 +11:00
Daniel Waterworth 2df0eca39a
DEV: Make postgres_readonly cache work like other caches (#20879)
We didn't have an authoritative source for this data previously, so now
it's stored in redis.
2023-03-30 09:14:59 -05:00
Renato Atilio 7afcb664fb
FIX: pretty-text shims - getURL's baseUri (#20822) 2023-03-30 08:35:06 -04:00
Alan Guo Xiang Tan a154d7207d
DEV: Improve test coverage for `/filters` route (#20890) 2023-03-30 12:57:23 +08:00
Martin Brennan e6feb3f136
DEV: Remove currentUser lookup in pretty-text (#20894)
This was added in d3f02a1270
for hashtags but later removed usage in
b2acc416e7. It was removed because
serializing the user does not include things like their
secure_categories.

It is not used by any other plugins or themes, and can cause
issues where it will error when operating on a null user. Better
to just pass in the user_id and use it to look up a user
directly in a PrettyText::Helper
2023-03-30 14:50:36 +10:00
Martin Brennan eea74e0e32
DEV: Add auto _map extension for simple/compact list SiteSettings (#20888)
Similar to the _map added for group_list SiteSettings in
e62e93f83a, this commit adds
the same extension for simple and compact `list` type SiteSettings,
so developers do not have to do the `.to_s.split("|")` dance
themselves all the time.

For example:

```
SiteSetting.markdown_linkify_tlds

=> "com|net|org|io|onion|co|tv|ru|cn|us|uk|me|de|fr|fi|gov|ddd"

SiteSetting.markdown_linkify_tlds_map

=> ["com", "net", "org", "io", "onion", "co", "tv", "ru", "cn", "us", "uk", "me", "de", "fr", "fi", "gov"]
```
2023-03-30 14:08:19 +10:00
Martin Brennan 84ff96bd07
FIX: Do not validate email in TL promotion (#20892)
There is no need to validate the user's emails when
promoting/demoting their trust level, this can cause
issues in things like Jobs::Tl3Promotions, we don't
need to fail in that case when all we are doing is changing
trust level.
2023-03-30 13:52:10 +10:00
Sam 795e6d72a4
FEATURE: modifier API for plugins (#20887)
Introduces a new API for plugin data modification without class-based extension overhead.

This commit introduces a new API that allows plugins to modify data in cases where they return different data rather than additional data, as is common with filtered_registers in DiscoursePluginRegistry. This API removes the need for defining class-based extension points.

When a plugin registers a modifier, it will automatically be called if the plugin is enabled. The core will then modify the parameter sent to it using the block registered by the plugin:
 
```ruby
DiscoursePluginRegistry.register_modifier(plugin_instance, :magic_sum_modifier) { |a, b| a + b }
sum = DiscoursePluginRegistry.apply_modifier(:magic_sum_filter, 1, 2)
expect(sum).to eq(3)
```

Key features of these modifiers:

- Operate in a stack (first registered, first called)
- Automatically disabled when the plugin is disabled
- Pass the cumulative result of all block invocations to the caller
2023-03-30 14:39:55 +11:00
Alan Guo Xiang Tan 4e11014693
DEV: Support `status:public` in topics filtering query language (#20889)
This commit adds support for the `status:public` filter which only
return topics that belong to public categories.
2023-03-30 10:57:26 +08:00
Alan Guo Xiang Tan 49e7e639cc
DEV: Update experimental `/filter` route with tags support (#20874)
The following are the changes being introduced in this commit:

1. Instead of mapping the query language to various query params on the
client side, we've decided that the benefits of having a more robust
query language far outweighs the benefits of having a more human readable query params in the URL.
As such, the `/filter` route will just accept a single `q` query param
and the query string will be parsed on the server side.

1. On the `/filter` route, the tags filtering query language is now
   supported in the input per the example provided below:

   ```
   tags:bug+feature tagged both bug and feature
   tags:bug,feature tagged either bug or feature
   -tags:bug+feature excluding topics tagged bug and feature
   -tags:bug,feature excluding topics tagged bug or feature
   ```

   The `tags` filter can also be specified multiple
times in the query string like so `tags:bug tags:feature` which will
filter topics that contain both the `bug` tag and `feature` tag. More
complex query like `tags:bug+feature -tags:experimental` will also work.
2023-03-30 09:00:42 +08:00
Jan Cernik afe3e36363
DEV: Remove lazy-yt and replace with lazy-videos (#20722)
- Refactors the old plugin to remove jquery usage
- Adds support for Vimeo videos (default on) and Tiktok (experimental and default off)
2023-03-29 11:54:25 -04:00
Sam ddec7bf6a3
DEV: allow API for list_suggested_for to exclude random (#20857)
This is needed so plugins can potentially create lists without random topics
2023-03-28 15:52:17 +11:00
Daniel Waterworth 9d34b73a5e
DEV: Make csp cache work like other caches (#20818) 2023-03-27 09:22:38 -05:00
Alan Guo Xiang Tan 4624cca00f
DEV: Fix `TopcisFilter#filter_tags` not working for a single tag (#20840)
Follow-up to dd88fdeabc
2023-03-27 16:58:40 +08:00
Alan Guo Xiang Tan dd88fdeabc
DEV: Introduce `TopicsFilter#filter_tags` method (#20839)
This change sets the ground work for allowing us to filter topics list
by tags in the following ways:

1. Filter for topics that matches all tags in a given set of tags
2. Filter for topics that matches any tags in a given set of tags
3. Exclude topics that matches all tags in a given set of tags
4. Exclude topics that matches any tags in a given set of tags
2023-03-27 14:16:53 +08:00
Krzysztof Kotlarek 4047073292
FIX: display validation under custom sidebar fields (#20772)
Before, incorrectly filled fields were marked with red border. Now, additional information under the field is displayed to notify the user what is incorrect.

/t/93696
2023-03-27 13:03:16 +11:00
Alan Guo Xiang Tan 56fbdde0e5
FIX: Broken `?status=(listed|unlisted)` query param support (#20834)
In 66c5054, the support for filtering a
topics list based on the visible attribute of a topic via the status query param
was accidentally removed.
2023-03-27 07:30:19 +08:00
Vinoth Kannan ed6f7b1e6d
FIX: use correct validation method name for `default_categories_normal`. (#20801)
When we renamed the `default_categories_regular` to `default_categories_normal` we missed a site setting validation method. It allowed the duplicate category ids in `default_categories_normal` site setting and caused the problem in user registration process.

5176c689e9
2023-03-24 11:40:37 +05:30
Alan Guo Xiang Tan 7c6a8f1c74
DEV: Refactor `TopicQuery#default_results` to improve readability (#20800)
This commit breaks down the code in TopicQuery#default_results into
smaller private methods to improve readability.
2023-03-24 11:17:55 +08:00
Martin Brennan 97f8f88cfe
FIX: ACL for OptimizedImage was using wrong path on multisite (#20784)
When setting the ACL for optimized images after setting the
ACL for the linked upload (e.g. via the SyncACLForUploads job),
we were using the optimized image path as the S3 key. This worked
for single sites, however it would fail silently for multisite
sites since the path would be incorrect, because the Discourse.store.upload_path
was not included.

For example, something like this:

somecluster1/optimized/2X/1/3478534853498753984_2_1380x300.png

Instead of:

somecluster1/uploads/somesite1/2X/1/3478534853498753984_2_1380x300.png

The silent failure is still intentional, since we don't want to
break other things because of ACL updates, but now we will update
the ACL correctly for optimized images on multisite sites.
2023-03-24 10:16:53 +10:00
David Taylor b81767c1b1
SECURITY: Limit URL length for theme remote (#20787) 2023-03-23 12:01:04 +00:00
Sam d87e78616d
FEATURE: allow site owners to disable impersonation (#20783)
Site owners can now disable impersonation using the global setting
`allow_impersonation` (Eg: DISCOURSE_ALLOW_IMPERSONATION: false)

see:

https://meta.discourse.org/t/thoughts-about-impersonate-user/258795
2023-03-23 15:16:05 +11:00
Jarek Radosz 627f69738f
DEV: Capture output in hashtags spec (#20773) 2023-03-23 11:47:14 +10:00
Bianca Nenciu fb3c610f09
PERF: Optimize topic query for many categories (#20743)
Sites with many categories and many of them in muted by default (see
`default_categories_muted`) reported bad performance when requesting
the homepage as an anonymous user. This was the case because of the
long query that iterated over topics and categories trying to remove
those from the muted categories.
2023-03-22 23:31:33 +02:00
Bianca Nenciu f12e77d500
FIX: Do not allow anonymous users to be anonymized (#20776) 2023-03-22 20:51:42 +02:00
David Taylor 7070f81596
DEV: Allow `DROP NOT NULL` in pre-deploy migrations (#20775)
Our SafeMigrate system is designed to prevent tables/columns being dropped in pre-deploy migrations. Its regex-based detection was triggering incorrectly on `ALTER COLUMN DROP NOT NULL`.
2023-03-22 14:43:32 +00:00
Alan Guo Xiang Tan b06e31f8e7
DEV: Remove experimental support for query string on `/filter` route (#20632) 2023-03-22 10:04:57 +08:00
Martin Brennan 520d4f504b
FEATURE: Auto-remove users without permission from channel (#20344)
There are many situations that may cause users to lose permission to
send messages in a chat channel. Until now we have relied on security
checks in `Chat::ChatChannelFetcher` to remove channels which the
user may have a `UserChatChannelMembership` record for but which
they do not have access to.

This commit takes a more proactive approach. Now any of these following
`DiscourseEvent` triggers may cause `UserChatChannelMembership`
records to be deleted:

* `category_updated` - Permissions of the category changed
   (i.e. CategoryGroup records changed)
* `user_removed_from_group` - Means the user may not be able to access the
   channel based on `GroupUser` or also `chat_allowed_groups`
* `site_setting_changed` - The `chat_allowed_groups` was updated, some
   users may no longer be in groups that can access chat.
* `group_destroyed` - Means the user may not be able to access the
   channel based on `GroupUser` or also `chat_allowed_groups`

All of these are handled in a distinct service run in a background
job. Users removed are logged via `StaffActionLog` and then we
publish messages on a per-channel basis to users who had their
memberships deleted.

When the user has a channel they are kicked from open, we show
a dialog saying "You no longer have access to this channel".

When they click OK we redirect them either:

* To their first other public channel, if they have any followed
* The chat browse page if they don't

This is to save on tons of requests from kicked out users getting messages
from other channels.

When the user does not have the kicked channel open, we can just
silently yoink it out of their sidebar and turn off subscriptions.
2023-03-22 10:19:59 +10:00
Kris 147941a5d7
UX: update chat icon to d-chat (#20744) 2023-03-21 10:40:42 -04:00
Isaac Janzen ca4b73d20c
FIX: Support tag query param on `/tag/{name}` routes (#20742) 2023-03-20 13:51:39 -05:00
Daniel Waterworth da0d20d4a9
DEV: Refactor svg sprite parsing (#20727)
There was a lot of duplication in the svg parsing and coercion code. This reduces that duplication and causes svg sprite parsing to happen earlier so that more computation is cached.
2023-03-20 11:41:23 -05:00
Joffrey JAFFEUX 133ea4cfec
DEV: handles presence channel configured with everyone group (#20741)
This commit will allow any connected user to access a presence channel configured with the automatic group "everyone"
2023-03-20 16:56:43 +01:00
Sam 0364ef5efe
FIX: MaxMindDB download failures caused a crash on rebuild (#20737)
We did not properly define the "name" variable leading to the error handling
to crash.

This quick fix ensures it can gracefully fail.
2023-03-20 18:23:54 +11:00
Daniel Waterworth 293cb7bde2
FIX: An ember build is required to run the system tests (#20725) 2023-03-17 13:20:49 -05:00
Blake Erickson 6b5743ba3c
Version bump to v3.1.0.beta3 (#20712) 2023-03-16 17:51:54 -06:00
Ted Johansson 39c2f63b35 SECURITY: Add FinalDestination::FastImage that's SSRF safe 2023-03-16 15:27:09 -06:00
Alan Guo Xiang Tan fd16eade7f SECURITY: SSRF protection bypass with IPv4-mapped IPv6 addresses
As part of this commit, we've also expanded our list of private IP
ranges based on
https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
and https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
2023-03-16 15:27:09 -06:00
Alan Guo Xiang Tan 52ef44f43b SECURITY: Monkey-patch web-push gem to use safer HTTP client
`FinalDestination::HTTP` is our patch of `Net::HTTP` which defend us
against SSRF and DNS rebinding attacks.
2023-03-16 15:27:09 -06:00
Loïc Guitaut 0bd64788d2 SECURITY: Rate limit the creation of backups 2023-03-16 16:09:22 +01:00
Daniel Waterworth 164b60cd07 DEV: Optionally, run system tests in docker:test 2023-03-15 16:46:48 -05:00
Daniel Waterworth 84f590ab83
DEV: Store theme sprites in the DB (#20501)
Let's avoid fetching sprites from the CDN during page rendering.
2023-03-14 13:11:45 -05:00
David Taylor 964f37476d
FIX: TopicQuery for NULL `category.topic_id` (#20664)
Our schema allows `category.topic_id` to be NULL. Null values shouldn't actually happen in production, but it is very common in tests because `Fabricate(:category)` skips creating the definition topic to improve performance. Before this commit, a NULL category.topic_id would cause all subcategory topics to be excluded from a TopicQuery result. This is because, in postgres, `NULL <> anything` is falsy. Instead, we can use `IS DISTINCT FROM`, which will return true when NULL is compared to a non-NULL value.
2023-03-13 19:33:26 +00:00
Rafael dos Santos Silva 0a5b078ac7
FEATURE: Hook for suggested topic customization (#20618) 2023-03-13 15:37:49 -03:00
Alan Guo Xiang Tan e4b11e7643
FEATURE: Only list watching group messages in messages notifications panel (#20630)
Why is this change required?

Prior to this change, we would list all group messages that a user
has access to in the user menu messages notifications panel dropdown.
However, this did not respect the topic's notification level setting and
group messages which the user has set to 'normal' notification level were
being displayed

What does this commit do?

With this commit, we no longer display all group messages that a user
has access to. Instead, we only display group messages that a user is
watching in the user menu messages notifications panel dropdown.

Internal Ref: /t/94392
2023-03-13 08:09:38 +08:00
Alan Guo Xiang Tan 0d9efa938b
DEV: Avoid logging routing errors (#20622)
The logs are usually caused by the client and is of no use to us.
2023-03-10 17:17:59 +08:00
Jay Pfaffman 4350a903ec
clear security keys in disable_2fa rake task (#20586) 2023-03-09 15:38:59 -05:00
Martin Brennan 5ea89d1fcb
FIX: UploadReference order by tiebreaker for UploadSecurity (#20602)
Follow up to 4d2a95ffe6. Sometimes
due to the original UploadReference migration or other issues,
multiple UploadReference records can have the exact same
created_at date and time. To tiebreak and correct the SQL order
when this happens, we can add a secondary `id ASC` ordering
when we check for the first upload reference.
2023-03-09 11:52:26 +10:00
Martin Brennan 6feb436303
DEV: Change external upload rate limit maximums to settings (#20577)
Way back when this was introduced way back in b96c10a903
I didn't have any frame of reference for what these max rate
limit numbers should be, so 10 seemed like a reasonable limit
until a real world case where this did not make sense came
along.

The time has come.

Moving these into site settings, which are hidden since in most
cases there is no need to change these.
2023-03-08 15:27:17 +10:00
Alan Guo Xiang Tan cf0a0945e4
Revert "DEV: Allow webmock to intercept `FinalDestination::HTTP` requests (#20575)" (#20576) 2023-03-08 11:26:32 +08:00
Alan Guo Xiang Tan 500d0f6daf
DEV: Allow webmock to intercept `FinalDestination::HTTP` requests (#20575) 2023-03-08 10:40:01 +08:00
Sam 3f5fa4eb09
DEV: avoid mocking FinalDestination (#20570) 2023-03-08 09:09:18 +08:00
Martin Brennan 360d0dde65
DEV: Change Bookmarkable registration to DiscoursePluginRegistry (#20556)
Similar spirit to e195e6f614,
this moves the Bookmarkable registration to DiscoursePluginRegistry
so plugins which are not enabled do not register additional
bookmarkable classes.
2023-03-08 10:39:12 +10:00
Osama Sayegh 3f908c047d
FIX: Use the default value correctly for theme settings of type uploads (#20541)
When a theme setting of type `upload` has a default upload, it should return the URL of the specified default upload until a custom upload is used for the setting. However, currently this isn't the case and we get null instead of the default upload URL.

The reason for this is because the `super` method of `#value` already returns the default upload URL (if there's one), so we can't pass that to `cdn_url` which expects an upload ID:

c961dcc757/lib/theme_settings_manager.rb (L212)

This commit fixes the bug by skipping the call to `cdn_url` when we fallback to the default upload for the setting value.
2023-03-06 11:41:47 +03:00
Alan Guo Xiang Tan 66c50547b4
DEV: Experimental /filter route to filter through topics (#20494)
This commit introduces an experimental `/filter` route which allows a
user to input a query string to filter through topics.

Internal Ref: /t/92833
2023-03-03 09:46:21 +08:00
Leonardo Mosquera e204c61bd8
FIX: #present -> #presence typo in TopicRetriever (#20509) 2023-03-02 13:05:45 -03:00
chapoi e52bbc1230
UX/DEV: Review queue redesign fixes (#20239)
* UX: add type tag and design update

* UX: clarify status copy in reviewQ

* DEV: switch to selectKit

* UX: color approve/reject buttons in RQ

* DEV: regroup actions

* UX: add type tag and design update

* UX: clarify status copy in reviewQ

* Join questions for flagged post with "or" with new I18n function
* Move ReviewableScores component out of context
* Add CSS classes to reviewable-item based on human type

* UX: add table header for scoring

* UX: don't display % score

* UX: prefix modifier class with dash

* UX: reviewQ flag table styling

* UX: consistent use of ignore icon

* DEV: only show context question on pending status

* UX: only show table headers on pending status

* DEV: reviewQ regroup actions for hidden posts

* UX: reviewQ > approve/reject buttons

* UX: reviewQ add fadeout

* UX: reviewQ styling

* DEV: move scores back into component

* UX: reviewQ mobile styling

* UX: score table on mobile

* UX: reviewQ > move meta info outside table

* UX: reviewQ > score layout fixes

* DEV: readd `agree_and_keep` and fix the spec tests.

* Fix the spec tests

* fix the quint test

* DEV: readd deleting replies

* UX: reviewQ copy tweaks

* DEV: readd test for ignore + delete replies

* Remove old

* FIX: Add perform_ignore back in for backwards compat

* DEV: add an action alias `ignore` for `ignore_and_do_nothing`.

---------

Co-authored-by: Martin Brennan <martin@discourse.org>
Co-authored-by: Vinoth Kannan <svkn.87@gmail.com>
2023-03-02 16:40:53 +01:00
Martin Brennan e195e6f614
DEV: Move about_stat_groups to DiscoursePluginRegistry (#20496)
Follow up to 098ab29d41. Since
we just used a `cattr_reader` on `About` this was not safe
for multisite, since some sites could have the chat plugin
enabled and some may not. Using `DiscoursePluginRegistry` gets
around this issue, and makes it so the chat stats only show
for a site if `chat_enabled` is true.
2023-03-02 08:10:16 +10:00
Keegan George 666b4a7e6b
DEV: Define form template field inputs (#20430) 2023-03-01 11:07:13 -08:00
Loïc Guitaut 8b67a534a0 FIX: Allow floats for zoom level in Google Maps onebox
Sometimes we get Maps URL containing a zoom level as a float (17.5z and
not 17z) but this doesn’t work with our current onebox implementation.

While Google accepts those float zoom levels, it removes automatically
the floating part in the URL (thus when visiting a Maps URL containing
17.5z, the URL will be rewritten shortly after as 17z). When putting a
float zoom level in an embedded URL, this actually breaks (Maps API
returns a 400 error).

This patch addresses the issue by allowing the onebox engine to match on
a zoom level expressed as a float but we only keep the integer part thus
rendering properly maps.
2023-03-01 12:45:33 +01:00
Jarek Radosz ddbe6cf3b5
DEV: Remove site setting "diags" (#20481)
Added almost exactly 10 years ago (in a2cca2540e), I don't think they're useful anymore 😅
2023-03-01 11:31:57 +01:00
Sam 71be74ffd3
FIX: recalculating trust levels was not working (#20492)
The recalculate code was never firing cause TrustLevel.calculate unconditionally
returned a trust level. (albeit a wrong one)

New code ensures we only bypass promotion checks for cases where trust level
is locked.

see: https://meta.discourse.org/t/user-trust-level-resets-to-zero-when-unlocked/255444
2023-03-01 15:35:21 +11:00
Constanza c051992098
FIX: mark posted as true for post authors in the TopicUser table during ensure_consistency task (#20473)
The ensure_consistency rake task was not marking posted as true for post authors in the TopicUser table, post migration. Create another step to set posted='t'.
2023-02-28 20:45:32 -04:00
Sam 654959faa4
DEV: reduce amount of errors logged when notifying on flags (#20472)
Forcing distributed muted to raise when a notify reviewable job is running
leads to excessive errors in the logs under many conditions.

The new pattern

1. Optimises the counting of reviewables so it is a lot faster
2. Holds the distributed lock for 2 minutes (max)


The downside is the job queue can get blocked up when tons of notify
reviewables are running at the same time. However this should be very
rare in the real world, as we only notify when stuff is flagged which
is fairly infrequent.

This also give a fair bit more time for the notifications which may be
a little slow on large sites with tons of mods.
2023-03-01 08:58:32 +11:00
Bianca Nenciu ccb345bd88
FEATURE: Update topic/comment embedding parameters (#20181)
This commit implements many changes to topic and comments embedding. It
deprecates the class_name field from EmbeddableHost and suggests using
the className parameter. discourse_username parameter has been
deprecated and it will fetch it from embedded site from the author or
discourse-username meta.

See the updated code sample from Admin > Customize > Embedding page.

* FEATURE: Add className parameter for Discourse embed

* DEV: Hide class_name from EmbeddableHost

* DEV: Deprecate class_name field of EmbeddableHost

* FEATURE: Use either author or discourse-username meta tag

* DEV: Deprecate discourse_username parameter

* DEV: Improve embed code sample
2023-02-28 14:31:59 +02:00
Jarek Radosz 116781c748
DEV: Update ember-cli-htmlbars to 6.2.0 (#20467)
* Build(deps): Bump ember-cli-htmlbars in /app/assets/javascripts

Bumps [ember-cli-htmlbars](https://github.com/ember-cli/ember-cli-htmlbars) from 6.1.1 to 6.2.0.
- [Release notes](https://github.com/ember-cli/ember-cli-htmlbars/releases)
- [Changelog](https://github.com/ember-cli/ember-cli-htmlbars/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ember-cli/ember-cli-htmlbars/compare/v6.1.1...v6.2.0)

---
updated-dependencies:
- dependency-name: ember-cli-htmlbars
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* Load additional files

* Update code

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-27 18:43:28 +01:00
Jarek Radosz f63d18d6ca
DEV: Update syntax_tree to 6.0.1 (#20466) 2023-02-27 17:20:00 +01:00
Osama Sayegh a509441148
DEV: Include unread topics in New topic lists and link to it in sidebar (#20432)
This commit introduces a few experimental changes to the New topics list and "Everything" link in the sidebar:

1. Make the New topics list include unread topics
2. Make the Everything section in the sidebar link to the New topics list (`/new`)
3. Remove "unread" or "new" text next to the count and keep the count
4. The count is a sum of new and unread topics counts

All of these of changes are behind an off-by-default feature flag. I've not written extensive tests for these changes because they're highly experimental.

Internal topic: t/77234.
2023-02-27 15:11:01 +03:00
Ted Johansson b50b63808c
DEV: Make Guardian#can_see? default to false for unwatched objects (#20412)
When invoking e.g. `can_see?(Foo.new)`, the guardian checks if there's a method `#can_see_foo?` defined and if so uses that to determine whether the user can see it or not.

When such a method is not defined, the guardian currently returns `true`, but it is probably a better call (pun intended) to make it "safe by default" and return `false` instead. I.e. if you can't explicitly see it, you can't see it at all.

This change makes the change to `Guardian#can_see?` to fall back to `false` if no visibility check method is defined.

For `#can_see_user?` and `#can_see_tag?` we don't have any particular logic that prevents viewing. We previously relied on the implicit `true` value, but since that's now change to `false`, I have explicitly implemented these two methods in `UserGuardian` and `TagGuardian` modules. If in the future we want to add some logic for it, this would be the place.

To be clear, **the behaviour remains the same**, but the `true` value is now explicit rather than implicit.
2023-02-24 15:57:01 +08:00
Penar Musaraj c052df412a
DEV: Add support for aliases in HighlightJS languages (#20380)
We were only supporting the main name of each HighlightJS language. So, by default, you could not use `js` or `jsx` to highlight Javascript, given they are aliases for `javascript`.

This PR adds a list of aliases as a constant to core (built via a rake task), and then checks against the `highlighted_languages` site settings plus the list of aliases when processing a code block.
2023-02-23 15:06:06 -05:00
Loïc Guitaut a9f2c6db64 SECURITY: Show only visible tags in metadata
Currently, the topic metadata show both public and private
tags whereas only visible ones should be exposed.
2023-02-23 17:22:20 +01:00
Martin Brennan 4ab1f76499
DEV: Fix bin/turbo_rspec runtime recording (#20407)
This commit 57caf08e13 broke
`bin/turbo_rspec` timing recording via `TurboTests::Runner`,
because we changed to using all `spec/*` folders except
`spec/system` as default for the runner, rather than
the old `['spec']` array, which is what `TurboTests::Runner`
was relying on to determine whether to record test run
time with `ParallelTests::RSpec::RuntimeLogger`.

Instead, we can just pass a new `use_runtime_info` boolean to the
runner class and use it when running against the default set of
spec files using `bin/turbo_rspec` and the turbo rspec rake task.
2023-02-23 07:47:11 +10:00
Krzysztof Kotlarek b9d037770c
DEV: configurable public sidebar sections (#20303)
Extension of https://github.com/discourse/discourse/pull/20057

Admin can create a public session visible to everyone. An additional checkbox is displayed for staff members.
2023-02-22 08:55:44 +11:00
Loïc Guitaut f7c57fbc19 DEV: Enable `unless` cops
We discussed the use of `unless` internally and decided to enforce
available rules from rubocop to restrict its most problematic uses.
2023-02-21 10:30:48 +01:00
Leonardo Mosquera 509fee0f5a
FIX: allow changing default DNS query timeout of 2s via GlobalSetting (#20383)
The current default timeout is hardcoded to 2 seconds which is proving
too low for certain cases, and resulting in sporadic timeouts due to slow DNS queries.
2023-02-21 09:54:29 +11:00
Osama Sayegh f91631b625
DEV: Update javascript:update_constants rake task following template colocation (#20365)
As of ba3f62f576, handlebars templates are colocated with js files so the path to hbs templates referenced by this rake task is no longer valid. This commit fixes the path to hbs templates and updates a couple of files that are generated by the rake task.
2023-02-20 06:20:47 +03:00
Martin Brennan 7ad92b7ab9
FIX: Do not enqueue update_post_uploads_secure_status unnecessarily (#20366)
We call `post.update_uploads_secure_status` in both
`PostCreator` and `PostRevisor`. Only the former was checking
if `SiteSetting.secure_uploads?` was enabled, but the latter
was not. There is no need to enqueue the job
`UpdatePostUploadsSecureStatus` if secure_uploads is not
enabled for the site.
2023-02-20 11:21:54 +10:00
Sam cd247d5322
FEATURE: Roll out new search optimisations (#20364)
- Reduce duplication of terms in post index from unlimited to 6. This will
result in reduced index size and reduced weighting for posts containing
a huge amount of duplicate terms. (Eg: a post containing "sam sam sam sam
sam sam sam sam", will index as "sam sam sam sam sam sam", only including
the word up to 6 times.) This corrects a flaw where title weighting could
be ignored.

- Prioritize exact matches of words in titles. Our search always performs
a prefix match. However we want to give special weight to exact title matches
meaning that a search for "sum" will find topics such as "the sum of us" vs
"summer in spring".

- Pick up fixes to our search algorithm which are missing from old indexes.
Specifically pick up the fix that indexes URLs properly. (`https://happy.com`
was stemmed to `happi` in keywords and then was not searchable)

see also:

https://meta.discourse.org/t/refinements-to-search-being-tested-on-meta/254158

Indexing will take a while and work in batches, in the background.
2023-02-20 11:53:35 +11:00
Leonardo Mosquera 6fa9a8990d
Add username template variables to Welcome User email template (#20352)
* Add username and name_or_username variables to SystemMessage defaults

* Allow username and name variables on welcome_user email template overrides

* Satisfy linting

* Add test
2023-02-17 18:38:21 -03:00
Osama Sayegh 75ae70c27c
DEV: rtlcss_wrapper renamed to rtlcss (#20331)
The `rtlcss_wrapper` gem has been renamed to `rtlcss` per bd89847a39.
2023-02-16 18:15:56 +03:00
Osama Sayegh 5423e7c5b7
DEV: Add backend support for unread and new topics list (#20293)
This commit adds backend support for a new topics list that combines both the current unread and new topics lists. We're going to experiment with this new list (name TBD) internally and decide if this feature is something that we want to fully build.

Internal topic: t/77234.
2023-02-16 16:02:09 +03:00
Selase Krakani 5a6e5a4012
FIX: Unsubscribing via key associated with deleted topic (#20275)
Currently, clicking on the unsubscribe link with a `key` associated with a
deleted topic results in an HTTP 500 response.

This change fixes that by skipping any attempt to run topic related flow if topic
isn't present.
2023-02-16 10:47:01 +00:00
natiz 9c30ae93b3
DEV: Add `after_email_send` app event (#20178) 2023-02-15 11:23:45 -05:00
Sam e636abeb0d
FIX: do not notify admins on suppressed categories (#20238)
* FIX: do not notify admins on suppressed categories

Avoid notifying admins on categories where they are not explicitly members
in cases where SiteSetting.suppress_secured_categories_from_admin is
enabled.

This helps keep notification stream clean and avoids admins mistakenly
being invited to discussions that should be suppressed
2023-02-14 16:45:06 +11:00
Martin Brennan cf5fa23cd3
DEV: Remove old secure_media setting (#20259)
This has been renamed to secure_uploads since
8ebd5edd1e
2023-02-14 09:41:18 +10:00
Martin Brennan 60ad836313
DEV: Chat service object initial implementation (#19814)
This is a combined work of Martin Brennan, Loïc Guitaut, and Joffrey Jaffeux.

---

This commit implements a base service object when working in chat. The documentation is available at https://discourse.github.io/discourse/chat/backend/Chat/Service.html

Generating documentation has been made as part of this commit with a bigger goal in mind of generally making it easier to dive into the chat project.

Working with services generally involves 3 parts:

- The service object itself, which is a series of steps where few of them are specialized (model, transaction, policy)

```ruby
class UpdateAge
  include Chat::Service::Base

  model :user, :fetch_user
  policy :can_see_user
  contract
  step :update_age

  class Contract
    attribute :age, :integer
  end

  def fetch_user(user_id:, **)
    User.find_by(id: user_id)
  end

  def can_see_user(guardian:, **)
    guardian.can_see_user(user)
  end

  def update_age(age:, **)
    user.update!(age: age)
  end
end
```

- The `with_service` controller helper, handling success and failure of the service within a service and making easy to return proper response to it from the controller

```ruby
def update
  with_service(UpdateAge) do
    on_success { render_serialized(result.user, BasicUserSerializer, root: "user") }
  end
end
```

- Rspec matchers and steps inspector, improving the dev experience while creating specs for a service

```ruby
RSpec.describe(UpdateAge) do
  subject(:result) do
    described_class.call(guardian: guardian, user_id: user.id, age: age)
  end

  fab!(:user) { Fabricate(:user) }
  fab!(:current_user) { Fabricate(:admin) }

  let(:guardian) { Guardian.new(current_user) }
  let(:age) { 1 }

   it { expect(user.reload.age).to eq(age) }
end
```

Note in case of unexpected failure in your spec, the output will give all the relevant information:

```
  1) UpdateAge when no channel_id is given is expected to fail to find a model named 'user'
     Failure/Error: it { is_expected.to fail_to_find_a_model(:user) }

       Expected model 'foo' (key: 'result.model.user') was not found in the result object.

       [1/4] [model] 'user' 
       [2/4] [policy] 'can_see_user'
       [3/4] [contract] 'default'
       [4/4] [step] 'update_age'

       /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/update_age.rb:32:in `fetch_user': missing keyword: :user_id (ArgumentError)
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:202:in `instance_exec'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:202:in `call'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:219:in `call'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:417:in `block in run!'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:417:in `each'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:417:in `run!'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:411:in `run'
       	from <internal:kernel>:90:in `tap'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/app/services/base.rb:302:in `call'
       	from /Users/joffreyjaffeux/Code/pr-discourse/plugins/chat/spec/services/update_age_spec.rb:15:in `block (3 levels) in <main>'
```
2023-02-13 13:09:57 +01:00
Ted Johansson 25a226279a
DEV: Replace #pluck_first freedom patch with AR #pick in core (#19893)
The #pluck_first freedom patch, first introduced by @danielwaterworth has served us well, and is used widely throughout both core and plugins. It seems to have been a common enough use case that Rails 6 introduced it's own method #pick with the exact same implementation. This allows us to retire the freedom patch and switch over to the built-in ActiveRecord method.

There is no replacement for #pluck_first!, but a quick search shows we are using this in a very limited capacity, and in some cases incorrectly (by assuming a nil return rather than an exception), which can quite easily be replaced with #pick plus some extra handling.
2023-02-13 12:39:45 +08:00
Krzysztof Kotlarek 010370f8b1
FIX: error anonymous when tl4_delete_posts_and_topics setting (#20257)
Bug introduced in this PR: https://github.com/discourse/discourse/pull/19946

When the setting is enabled, an error is triggered for anonymous users.
2023-02-13 15:34:04 +11:00
Krzysztof Kotlarek 85fbe3f628
FIX: IconPicker option to display only available icons (#20235)
Not all icons are shipped by default. Sidebar section icon picker should only display available icons.
2023-02-13 09:24:47 +11:00
David Taylor 25fabccd59
DEV: Enable parallel babel processing in ember-cli (#20215)
Ember CLI will automatically run babel transformations in parallel when the config is 'serializable', and can therefore be applied in multiple processes automatically. If any plugin is defined in an unserializable way, parallelisation will be disabled.

Our discourse-widget-hbs transformer was causing parallelisation to be disabled. This commit fixes that, and also enables the throwUnlessParallelizable flag so that we catch this kind of issue more easily in future.

This commit also refactors our deprecation silencing system into its own file, and uses a fake babel plugin to ensure deprecations are silenced in babel worker processes.

In our GitHub CI jobs, this doubles the speed of ember builds (1m30s -> 45s). It should also improve production deploy times, and cold-start dev builds.
2023-02-09 16:24:24 +00:00
Gerhard Schlager 58875b818b
FEATURE: Create SQL-only backup if there are no uploads (#20221)
It doesn't make sense to double-compress the backup when there are no uploads even when the admin requested a backup with uploads.
2023-02-08 21:40:15 +01:00
Keegan George 871607a420
DEV: Create form templates (#20189) 2023-02-08 11:21:39 -08:00
Keegan George b677bb6f24
DEV: Add `yaml` support to `<AceEditor />` (#20198) 2023-02-07 12:49:12 -08:00
Rafael dos Santos Silva 6e522e4aad
DEV: Move to Sass compilation to dart-sass (#19910)
This PR is a major change to Sass compilation in Discourse.

The new version of sass-ruby moves to dart-sass putting we back on the supported version of Sass. It does so while keeping compatibility with the existing method signatures, so minimal change is needed in Discourse for this change.

This moves us

From:
  - sassc 2.0.1 (Feb 2019)
  - libsass 3.5.2 (May 2018)

To:
  - dart-sass 1.58

This update applies the following breaking changes:

> 
> These breaking changes are coming soon or have recently been released:
> 
>  [Functions are stricter about which units they allow](https://sass-lang.com/documentation/breaking-changes/function-units) beginning in Dart Sass 1.32.0.
> 
>  [Selectors with invalid combinators are invalid](https://sass-lang.com/documentation/breaking-changes/bogus-combinators) beginning in Dart Sass 1.54.0.
> 
>  [/ is changing from a division operation to a list separator](https://sass-lang.com/documentation/breaking-changes/slash-div) beginning in Dart Sass 1.33.0.
> 
>  [Parsing the special syntax of @-moz-document will be invalid](https://sass-lang.com/documentation/breaking-changes/moz-document) beginning in Dart Sass 1.7.2.
> 
>  [Compound selectors could not be extended](https://sass-lang.com/documentation/breaking-changes/extend-compound) in Dart Sass 1.0.0 and Ruby Sass 4.0.0.


SCSS files have been migrated automatically using `sass-migrator division app/assets/stylesheets/**/*.scss`
2023-02-07 12:24:57 -03:00
Krzysztof Kotlarek 84a87a703c
DEV: configurable custom sidebar sections (#20057)
Allows users to configure their own custom sidebar sections with links withing Discourse instance. Links can be passed as relative path, for example "/tags" or full URL.

Only path is saved in DB, so when Discourse domain is changed, links will be still valid.

Feature is hidden behind SiteSetting.enable_custom_sidebar_sections. This hidden setting determines the group which members have access to this new feature.
2023-02-03 14:44:40 +11:00
Sam 5d28cb709a
FIX: de-prioritize archived topics (#20161)
Previously due to an error archived topics were more prominent in search
than closed topics.

This amends our internal logic to ensure archived topics are bumped down
the list.
2023-02-03 13:23:27 +11:00
Gerhard Schlager 7fd63b34b1
DEV: Make it obvious that `joined` translation is used by onebox (#20158)
This also moves the date as interpolation key into the string which makes translation easier.
2023-02-03 10:02:14 +08:00
Sam 1dba1aca27
FIX: add support for PG 14 and up (#20137)
Previously to_tsquery would split terms and join with &

In PG 14 terms are split and use <-> which means followed directly by.

In PG 13:

discourse_test=# SELECT to_tsquery('english', '''hello world''');
     to_tsquery
---------------------
 'hello' & 'world'
(1 row)

In PG 14:

discourse_test=# SELECT to_tsquery('english', '''hello world''');
     to_tsquery
---------------------
 'hello' <-> 'world'
(1 row)


Change is very unobtrosive, we simply amend our to_tsquery to behave like
it used to behave and make no use of the `<->` operator


More detail at: https://akorotkov.github.io/blog/2021/05/22/pg-14-query-parsing/

Note that plainto_tsquery used elsewhere in Discourse keeps the exact
same function.

This also corrects a faulty test that was passing by a fluke on older
version of PG
2023-02-03 08:11:25 +11:00
David Taylor 54f165beae DEV: Correct syntax_tree violations 2023-02-02 13:03:11 +00:00
Osama Sayegh f94951147e
FIX: Replace R2 gem with rtlcss for generating RTL CSS (#19636)
We've had a couple of problems with the R2 gem where it generated a broken RTL CSS bundle that caused a badly broken layout when Discourse is used in an RTL language, see a3ce93b and 5926386. For this reason, we're replacing R2 with `rtlcss` that can handle modern CSS features better than R2 does.

`rltcss` is written in JS and available as an npm package. Calling the `rltcss` from rubyland is done via the `rtlcss_wrapper` gem which contains a distributable copy of the `rtlcss` package and loads/calls it with Mini Racer. See https://github.com/discourse/rtlcss_wrapper for more details.

Internal topic: t/76263.
2023-02-01 14:21:15 +03:00
David Taylor 66256c15bd
UX: Calculate missing hover/selected colors from existing colors (#20105)
`--d-hover` is calculated to be equivalent to primary-100 in light mode, or primary-low in dark mode

`--d-selected` is calculated to be equivalent to primary-low in light mode, or primary-100 in dark mode

`lib/color_math` is introduced to provide some utilities for making these calculations.
2023-02-01 09:55:21 +00:00
Alan Guo Xiang Tan f1ea2a2509
DEV: Add validator for search_ranking_weights site setting (#20088)
Follow-up to 6934edd97c
2023-02-01 06:43:41 +08:00
Gerhard Schlager f4ce402dc4
DEV: `i18n:check` rake task was broken on Ruby 3.1 (#20103)
`server.en.yml` contains aliases and Ruby 3.1 made changes to `YAML.load_file`.
see https://www.ctrl.blog/entry/ruby-psych4.html
2023-01-31 16:53:24 +01:00
Ghassan Maslamani 96a6bb69b5
FIX: vimeo iframe url when data-original-href is missing (#18894) 2023-01-31 12:00:27 +01:00
Sam c5345d0e54
FEATURE: prioritize_exact_search_title_match hidden setting (#20089)
The new `prioritize_exact_search_match` can be used to force the search
algorithm to prioritize exact term matches in title when ranking results.

This is scoped narrowly to titles for cases such as a topic titled:

"organisation chart" and a search of "org chart".

If we scoped this wider, all discussion about "org chart" would float to
the top and leave a very common title de-prioritized.

This is a hidden site setting and it has some performance impact due
to double ranking.

That said, performance impact is somewhat mitigated cause ranking on
title alone is a very cheap operation.
2023-01-31 16:34:01 +11:00
Alan Guo Xiang Tan 6934edd97c
DEV: Add hidden site setting to configure search ranking weights (#20086)
This site setting is mostly experimental at this point.
2023-01-31 08:57:13 +08:00
Sam 5d669d8aa2
Revert "FEATURE: hidden site setting to disable search prefix matching (#20058)" (#20073)
This reverts commit 64f7b97d08.

Too many side effects for this setting, we have decided to remove it
2023-01-31 07:39:23 +08:00
Jan Cernik aecd8b1eff
FIX: Add support for multiple TikTok aspect ratios (#20064) 2023-01-30 18:12:01 -03:00
Sam 64f7b97d08
FEATURE: hidden site setting to disable search prefix matching (#20058)
Many users seems surprised by prefix matching in search leading to
unexpected results.

Over the years we always would return results starting with a search term
and not expect exact matches.

Meaning a search for `abra` would find `abracadabra`

This introduces the Site Setting `enable_search_prefix_matching` which
defaults to true. (behavior unchanged)

We plan to experiment on select sites with exact matches to see if the
results are less surprising
2023-01-30 12:44:40 +08:00
Bianca Nenciu 8fc11215e1
FIX: Ensure soft-deleted topics can be deleted (#19802)
* FIX: Ensure soft-deleted topics can be deleted

The topic was not found during the deletion process because it was
deleted and `@post.topic` was nil.

* DEV: Use @topic instead of finding the topic every time
2023-01-27 16:15:33 +02:00
Ethan da0b401fa5
FIX: Fixed getting badges from inviting youself (#19778)
Update invite badge query to exclude self
2023-01-27 12:28:47 +08:00
David Taylor 798b4bb604
FIX: Ensure anon-cached values are never returned for API requests (#20021)
Under some situations, we would inadvertently return a public (unauthenticated) result to an authenticated API request. This commit adds the `Api-Key` header to our anonymous cache bypass logic.
2023-01-26 13:26:29 +00:00
jbrw f8863b0f98
DEV: Limit concurrency of NotifyReviewables job (#19968)
Under scenarios of extremely high load where large numbers of `Reviewable*` items are being created, it has been observed that multiple instances of the `NotifyReviewable` job may run simultaneously.

These jobs will work satisfactorily if the concurrency is limited to 1, and the different types of jobs (items reviewable by admins, vs moderators, vs particular groups, etc.) are run eventually.

This change introduces a new option to `DistributedMutex` which allows the `max_get_lock_attempts` to be specified. If the number is exceeded an error will be raised, which will cause Sidekiq to requeue the job. Sidekiq has existing logic to back-off on retry times for jobs that have failed multiple times.
2023-01-25 15:19:11 -05:00
Bianca Nenciu e6a41150e2
Version bump to v3.1.0.beta2 (#19999) 2023-01-25 13:47:16 -05:00
Bianca Nenciu c186a46910
SECURITY: Prevent XSS in local oneboxes (#20008)
Co-authored-by: OsamaSayegh <asooomaasoooma90@gmail.com>
2023-01-25 19:17:21 +02:00
Bianca Nenciu f55e0fe791
SECURITY: Update to exclude tag topic filter (#20006)
Ignores tags specified in exclude_tag topics param that a user does not
have access to.

Co-authored-by: Blake Erickson <o.blakeerickson@gmail.com>
2023-01-25 18:56:22 +02:00
Bianca Nenciu 6d92c3cbda
SECURITY: Prevent ReDoS in user agent parsing (#20002)
Co-authored-by: Penar Musaraj <pmusaraj@gmail.com>
2023-01-25 18:55:33 +02:00
Bianca Nenciu b32db6f2a3
SECURITY: Prevent ReDOS by making the SSH url regex unambiguous (#20000)
Co-authored-by: Daniel Waterworth <me@danielwaterworth.com>
2023-01-25 18:55:01 +02:00
David Taylor e2db764cdd
DEV: Remove older ruby version logic (#19971)
Discourse no longer boots on anything less than 3.1, so these code paths will never be used
2023-01-24 10:42:56 +00:00
Martin Brennan 63fdb6dd65
FIX: Do not add empty use/svg tags in ExcerptParser (#19969)
There was an issue where if hashtag-cooked HTML was sent
to the ExcerptParser without the keep_svg option, we would
end up with empty </use> and </svg> tags on the parts of the
excerpt where the hashtag was, in this case when a post
push notification was sent.

Fixed this, and also added a way to only display a plaintext
version of the hashtag for cases like this via PrettyText#excerpt.
2023-01-24 14:40:24 +10:00
Vinoth Kannan 799202d50b
FIX: skip email if blank while syncing SSO attributes. (#19939)
Also, return email blank error in `EmailValidator`  when the email is blank.
2023-01-24 09:10:24 +05:30
Martin Brennan 110c96e6d7
FIX: Do not count deleted post for upload ref security (#19949)
When checking whether an existing upload should be secure
based on upload references, do not count deleted posts, since
there is still a reference attached to them. This can lead to
issues where e.g. an upload is used for a post then later on
a custom emoji.
2023-01-24 10:01:48 +10:00
Jan Cernik d0c820e816
FEATURE: Add better TikTok onebox support (#19934) 2023-01-23 09:49:02 -03:00
Krzysztof Kotlarek ae20ce8654
FIX: TL4 user can see deleted topics (#19946)
New feature that TL4 users can delete/recover topics and post was introduced https://github.com/discourse/discourse/pull/19766

One guardian was missed to ensure that can see deleted topics
2023-01-23 12:02:47 +11:00
Daniel Waterworth 666536cbd1
DEV: Prefer \A and \z over ^ and $ in regexes (#19936) 2023-01-20 12:52:49 -06:00
Krzysztof Kotlarek 019ec74076
FEATURE: setting which allows TL4 users to deleted posts (#19766)
New setting which allows TL4 users to delete/view/recover posts and topics
2023-01-20 13:31:51 +11:00
Alan Guo Xiang Tan f122f24b35
SECURITY: Default tags to show count of topics in unrestricted categories (#19916)
Currently, `Tag#topic_count` is a count of all regular topics regardless of whether the topic is in a read restricted category or not. As a result, any users can technically poll a sensitive tag to determine if a new topic is created in a category which the user has not excess to. We classify this as a minor leak in sensitive information.

The following changes are introduced in this commit:

1. Introduce `Tag#public_topic_count` which only count topics which have been tagged with a given tag in public categories.
2. Rename `Tag#topic_count` to `Tag#staff_topic_count` which counts the same way as `Tag#topic_count`. In other words, it counts all topics tagged with a given tag regardless of the category the topic is in. The rename is also done so that we indicate that this column contains sensitive information. 
3. Change all previous spots which relied on `Topic#topic_count` to rely on `Tag.topic_column_count(guardian)` which will return the right "topic count" column to use based on the current scope. 
4. Introduce `SiteSetting.include_secure_categories_in_tag_counts` site setting to allow site administrators to always display the tag topics count using `Tag#staff_topic_count` instead.
2023-01-20 09:50:24 +08:00
Martin Brennan 4d2a95ffe6
FIX: Query UploadReference in UploadSecurity for existing uploads (#19917)
This fixes a longstanding issue for sites with the
secure_uploads setting enabled. What would happen is a scenario
like this, since we did not check all places an upload could be
linked to whenever we used UploadSecurity to check whether an
upload should be secure:

* Upload is created and used for site setting, set to secure: false
  since site setting uploads should not be secure. Let's say favicon
* Favicon for the site is used inside a post in a private category,
  e.g. via a Onebox
* We changed the secure status for the upload to true, since it's been
  used in a private category and we don't check if it's originator
  was a public place
* The site favicon breaks :'(

This was a source of constant consternation. Now, when an upload is _not_
being created, and we are checking if an existing upload should be
secure, we now check to see what the first record in the UploadReference
table is for that upload. If it's something public like a site setting,
then we will never change the upload to `secure`.
2023-01-20 10:24:52 +10:00
Alan Guo Xiang Tan b00e160dae
PERF: Don't parse posts for mentions when user status is disabled (#19915)
Prior to this change, we were parsing `Post#cooked` every time we
serialize a post to extract the usernames of mentioned users in the
post. However, the only reason we have to do this is to support
displaying a user's status beside each mention in a post on the client side when
the `enable_user_status` site setting is enabled. When
`enable_user_status` is disabled, we should avoid having to parse
`Post#cooked` since there is no point in doing so.
2023-01-20 07:58:00 +08:00
Isaac Janzen 292d3677e9
FEATURE: Allow admins to permanently delete revisions (#19913)
# Context
This PR introduces the ability to permanently delete revisions from a post while maintaining the changes implemented by the revisions.
Additional Context: /t/90301

# Functionality
In the case a staff member wants to _remove the visual cue_ that a post has been edited eg.

<img width="86" alt="Screenshot 2023-01-18 at 2 59 12 PM" src="https://user-images.githubusercontent.com/50783505/213293333-9c881229-ab18-4591-b39b-e3419a67907d.png">

while maintaining the changes made in the edits, they can enable the (hidden) site setting of `can_permanently_delete`.
When this is enabled, after _hiding_ the revisions

<img width="149" alt="Screenshot 2023-01-19 at 1 53 35 PM" src="https://user-images.githubusercontent.com/50783505/213546080-2a9e9c55-b3ef-428e-a93d-1b6ba287dfae.png">

there will be an additional button in the history modal to <kbd>Delete revisions</kbd> on a post.

<img width="997" alt="Screenshot 2023-01-19 at 1 49 51 PM" src="https://user-images.githubusercontent.com/50783505/213546333-49042558-50ab-4724-9da7-08bacc68d38d.png">

Since this action is permanent, we display a confirmation dialog prior to triggering the destroy call

<img width="722" alt="Screenshot 2023-01-19 at 1 55 59 PM" src="https://user-images.githubusercontent.com/50783505/213546487-96ea6e89-ac49-4892-b4b0-28996e3c867f.png">

Once confirmed the history modal will close and the post will `rebake` to display an _unedited_ post.

<img width="868" alt="Screenshot 2023-01-19 at 1 56 35 PM" src="https://user-images.githubusercontent.com/50783505/213546608-d6436717-8484-4132-a1a8-b7a348d92728.png">
 
see that there is not a visual que for _revision have been made on this post_ for a post that **HAS** been edited. In addition to this, a user history log for `purge_post_revisions` will be added for each action completed.

# Limits
- Admins are rate limited to 20 posts per minute
2023-01-19 15:09:01 -06:00
David Taylor 5406e24acb
FEATURE: Introduce pg_force_readonly_mode GlobalSetting (#19612)
This allows the entire cluster to be forced into pg readonly mode. Equivalent to running `Discourse.enable_pg_force_readonly_mode` on the console.
2023-01-19 13:59:11 +00:00
Martin Brennan 56a93f7532
FEATURE: Add rake task to mark old hashtag format for rebake (#19876)
Since the new hashtag format has been added, we want site
admins to be able to rebake old posts with the old hashtag
format. This can now be done with `rake hashtags:mark_old_format_for_rebake`
which goes and marks posts with the old cooked version of hashtags
in this format for rebake:

```
<a class=\"hashtag\" href=\"/c/ux/14\">#<span>ux</span></a>
```

c.f. https://meta.discourse.org/t/what-rebake-is-required-for-the-new-autocomplete-styling/249642/12
2023-01-18 10:16:05 +10:00
Martin Brennan 115dfccf3b
FIX: Enqueue notify_mailing_list_subscribers when post is recovered (#19888)
This commit fixes the following issue:

* User creates a post
* Akismet or some other thing like requiring posts to be approved puts
  the post in the review queue, deleting it
* Admin approves the post
* Email is never sent to mailing list mode subscribers

We intentionally do not enqueue this for every single post when
recovering a topic (i.e. recovering the first post) since the topics
could have a lot of posts with emails already sent, and we don't want
to clog sidekiq with thousands of notify jobs.
2023-01-18 09:13:45 +10:00
Ted Johansson 9cdeb93375
FEATURE: Allow TL4 users to see unlisted topics (#19890)
TL4 users can already list and unlist topics, but they can't see
the unlisted topics. This change brings this to par by allowing
TL4 users to also see unlisted topics.
2023-01-17 16:50:15 +08:00
Sérgio Saquetim 0feb9ad341
DEV: Added callback to change the query used to filter groups in search (#19884)
Added plugin registry that will allow adding callbacks that can change the query that is used
to filter groups while running a search.
2023-01-16 15:48:00 -03:00
David Taylor 41f3bb8b50
FIX: Restore class-property babel transform for themes (#19883)
This seems to be required for decorators to work on class properties. Followup to 624f4a7de9
2023-01-16 18:06:46 +00:00
David Taylor 624f4a7de9
Drop support for iOS < 15.7 (#19847)
https://meta.discourse.org/t/224747
2023-01-16 17:28:59 +00:00
Bianca Nenciu 0fea826f42
FIX: Validate tags parameter of TopicQuery (#19830)
Recently, we have seen some errors related to invalid tags value being
passed to TopicQuery.
2023-01-16 19:20:19 +02:00
Régis Hanol b704e338ef
DEV: extract anniversary badge query (#19716)
So it can easily be overwritten in a plugin for example.

### Added more tests to provide better coverage

We previously only had `u.silenced_till IS NULL` but I made it consistent with pretty much every other places where we check for "active" users.

These two new lines do change the query a tiny bit though. 

**Before** 

- You could not get the badge if you were currently silenced (no matter what period is being checked)
- You could get the badge if you were suspended 😬 

**After**

- You can't get the badge if you were silenced during the past year
- You can't get the badge if you were suspended during the past year


### Improved the performance of the query by using `NOT EXISTS` instead of `LEFT JOIN / COUNT() = 0`

There is no difference in behaviour between 

```sql
LEFT JOIN user_badges AS ub ON ub.user_id = u.id AND ...
[...]
HAVING COUNT(ub.*) = 0
```

and

```sql
NOT EXISTS (SELECT 1 FROM user_badges AS ub WHERE ub.user_id = u.id AND ...)
```

The only difference is performance-wise. The `NOT EXISTS` is 10-30% faster on very large databases (aka. posts and users in X millions). I checked on 3 of the largest datasets I could find.
2023-01-16 11:55:00 +01:00
David Taylor 29f7ec7090
DEV: Prevent defer stats exception when thread aborted (#19863)
When the thread is aborted, an exception is raised before the `start` of a job is set, and therefore raises an exception in the `ensure` block. This commit checks that `start` exists, and also adds `abort_on_exception=true` so that this issue would have caused test failures.
2023-01-16 09:08:44 +11:00
Alan Guo Xiang Tan f72875c729
DEV: Introduce `enable_new_notifications_menu` site setting (#19860)
The `enable_new_notifications_menu` site setting allows sites that have
`navigation_menu` set to `legacy` to use the redesigned notifications
menu before switching to the new sidebar navigation menu.
2023-01-16 06:04:53 +08:00
Selase Krakani 73ec80893d
FEATURE: Extend topic update API scope to allow status updates (#19654)
Allow an API key created with topic:update API scope to make updates to
topic status. This change also introduces an optional category_id scope
param.
2023-01-13 01:21:04 +00:00
Ted Johansson 5dcb245eac
FIX: Ruby 2 backward compatible plugin logout redirect (#19845)
This is a very subtle one. Setting the redirect URL is done by passing
a hash through a Discourse event. This is broken on Ruby 2 since the
support for keyword arguments in events was added.

In Ruby 2 the last argument is cast to keyword arguments if it is a
hash. The key point here is that creates a new copy of the hash, so
what the plugin is modifying is not the hash that was passed.
2023-01-12 19:12:20 +08:00
Loïc Guitaut 4093fc6074 Revert "DEV: Migrate existing cookies to Rails 7 format"
This reverts commit 66e8fe9cc6 as it
unexpectedly caused some users to be logged out. We are investigating
the problem.
2023-01-12 12:07:49 +01:00
Loïc Guitaut 66e8fe9cc6 DEV: Migrate existing cookies to Rails 7 format
This patch introduces a cookies rotator as indicated in the Rails
upgrade guide. This allows to migrate from the old SHA1 digest to the
new SHA256 digest.
2023-01-12 11:09:07 +01:00
Martin Brennan 1f59a8299d
DEV: Address TODOs for email Message-ID generation (#19842)
Remove some old deprecated methods and update docs. Will leave
the backwards-compatible Message-ID formats a little while longer
just to be sure.
2023-01-12 13:54:15 +10:00
Sam 7b63c42304
FEATURE: add basic instrumentation to defer queue (#19824)
This will give us some aggregate stats on the defer queue performance.

It is limited to 100 entries (for safety) which is stored in an LRU cache.

Scheduler::Defer.stats can then be used to get an array that denotes:

- number of runs and completions (queued, finished)
- error count (errors)
- total duration (duration)

We can look later at exposing these metrics to gain visibility on the reason
the defer queue is clogged.
2023-01-12 12:29:50 +11:00
Martin Brennan 387693e889
FIX: Improve error reporting and failure modes for channel archiving (#19791)
There was an issue with channel archiving, where at times the topic
creation could fail which left the archive in a bad state, as read-only
instead of archived. This commit does several things:

* Changes the ChatChannelArchiveService to validate the topic being
  created first and if it is not valid report the topic creation errors
  in the PM we send to the user
* Changes the UI message in the channel with the archive status to reflect
  that topic creation failed
* Validate the new topic when starting the archive process from the UI,
  and show the validation errors to the user straight away instead of
  creating the archive record and starting the process

This also fixes another issue in the discourse_dev config which was
failing because YAML parsing does not enable all classes by default now,
which was making the seeding rake task for chat fail.
2023-01-12 10:04:46 +10:00
Martin Brennan 21a95b000e
DEV: Remove defunct TODOs (#19825)
* Firefox now finally returns PerformanceMeasure from performance.measure
* Some TODOs were really more NOTE or FIXME material or no longer relevant
* retain_hours is not needed in ExternalUploadsManager,  it doesn't seem like anywhere in the UI sends this as a param for uploads
* https://github.com/discourse/discourse/pull/18413 was merged so we can remove JS test workaround for settings
2023-01-12 09:41:39 +10:00
Loïc Guitaut 14d97f9cf1 FEATURE: Show more context in Discourse topic oneboxes
Currently when generating a onebox for Discourse topics, some important
context is missing such as categories and tags.

This patch addresses this issue by introducing a new onebox engine
dedicated to display this information when available. Indeed to get this
new information, categories and tags are exposed in the topic metadata
as opengraph tags.
2023-01-11 14:22:53 +01:00
Osama Sayegh 17daf077e2
Version bump to v3.1.0.beta1 (#19822) 2023-01-11 08:39:15 +03:00
Justin René Back aad7a14b36
FIX: Make DBHelper.find build valid query (#19408) 2023-01-10 22:38:52 +02:00
Daniel Waterworth dfc449a32e
FIX: Continue if checking themes if updating one fails (#19665) 2023-01-09 11:56:43 -06:00
Bianca Nenciu fb780c50fd
FIX: Replace all quote-like unicodes with quotes (#19714)
If unaccent is called with quote-like Unicode characters then it can
generate invalid queries because some of the transformed quotes by
unaccent are not escaped and to_tsquery fails because of bad input.

This commits replaces more quote-like Unicode characters before
unaccent is called.
2023-01-09 19:19:51 +02:00
David Taylor 6417173082
DEV: Apply syntax_tree formatting to `lib/*` 2023-01-09 12:10:19 +00:00
Jarek Radosz ff508d1ae5
FIX: Correctly support DiscourseEvent kwargs (#19788)
Fixes the support for kwargs in `DiscourseEvent.trigger()` on Ruby 3, e.g.

```rb
DiscourseEvent.trigger(:before_system_message_sent, message_type: type, recipient: @recipient, post_creator_args: post_creator_args, params: method_params)
```

Fixes https://github.com/discourse/discourse-local-site-contacts
2023-01-09 11:26:39 +01:00
Martin Brennan 56eaf91589
FIX: Do not error when anon user looks at secure upload for deleted post (#19792)
If a secure upload's access_control_post was trashed, and an anon user
tried to look at that upload, they would get a 500 error rather than
the correct 403 because of an error inside the PostGuardian logic.
2023-01-09 16:12:10 +10:00
David Taylor 66e8a35b4d
DEV: Include message-bus request type in HTTP request data (#19762) 2023-01-06 11:26:18 +00:00
Martin Brennan c4ea158656
FIX: Improve tags in email subjects and add filter headers (#19760)
This commit does a couple of things:

1. Changes the limit of tags to include a subject for a
   notification email to the `max_tags_per_topic` setting
   instead of the arbitrary 3 limit
2. Adds both an X-Discourse-Tags and X-Discourse-Category
   custom header to outbound emails containing the tags
   and category from the subject, so people on mail clients
   that allow advanced filtering (i.e. not Gmail) can filter
   mail by tags and category, which is useful for mailing
   list mode users

c.f. https://meta.discourse.org/t/headers-for-email-notifications-so-that-gmail-users-can-filter-on-tags/249982/17
2023-01-06 10:03:02 +10:00
Alan Guo Xiang Tan 6543dec7cb
Version bump to v3.0.0.beta16 (#19751) 2023-01-05 09:45:40 +08:00
Martin Brennan 16b9165630
FIX: Bookmark auto delete preference usage and default value (#19707)
This commit fixes an issue where the chat message bookmarks
did not respect the user's `bookmark_auto_delete_preference`
which they select in their user preference page.

Also, it changes the default for that value to "keep bookmark and clear reminder"
rather than "never", which ends up leaving a lot of expired bookmark
reminders around which are a pain to clean up.
2023-01-05 08:43:58 +10:00
Alan Guo Xiang Tan 918dd4d635
SECURITY: use rstrip instead of regex gsub to prevent ReDOS (#19737)
`rstrip` implementation is much more performant than regex

Co-authored-by: Krzysztof Kotlarek <kotlarek.krzysztof@gmail.com>
2023-01-05 06:09:17 +08:00
Alan Guo Xiang Tan bf6b08670a
SECURITY: Check the length of raw post body (#19733)
Co-authored-by: Jarek Radosz <jradosz@gmail.com>
2023-01-05 06:08:43 +08:00
Alan Guo Xiang Tan ab3a032b4b
SECURITY: BCC active user emails from group SMTP (#19725)
When sending emails out via group SMTP, if we
are sending them to non-staged users we want
to mask those emails with BCC, just so we don't
expose them to anyone we shouldn't. Staged users
are ones that have likely only interacted with
support via email, and will likely include other
people who were CC'd on the original email to the
group.

Co-authored-by: Martin Brennan <martin@discourse.org>
2023-01-05 06:07:50 +08:00
Osama Sayegh bbcdf74c58
DEV: Flip primary_email_verified? default to false (#19703)
This commit changes the default return value of `Auth::ManagedAuthenticator#primary_email_verified?` to false. We're changing the default to force developers to think about email verification when building a new authentication method. All existing authenticators (in core and official plugins) have been updated to explicitly define the `primary_email_verified?` method in their subclass of `Auth::ManagedAuthenticator` (example commit 65f57a4d05).

Internal topic: t/82084.
2023-01-04 10:51:10 +03:00
Roman Rizzi c2e18c41a3
FIX: Check that the node has a src attr when getting size (#19696) 2023-01-03 15:27:05 -03:00
Alan Guo Xiang Tan f04e454628
Version bump to v3.0.0.beta15 (#19685) 2023-01-03 14:29:26 +08:00
Alan Guo Xiang Tan af76f291e6
PERF: Avoid running redundant bookmarks query for anon viewing topic (#19659)
The `TopicView#bookmarks` method is called by `TopicViewSerializer` and `PostSerializer`
so we want to avoid running a meaningless query when user is not
present.
2023-01-03 10:00:36 +08:00
Alan Guo Xiang Tan 24db6fbb73
PERF: Memoize topic level checks in PostGuardian (#19647)
When loading posts in a topic, the topic level guardian
checks are run multiple times even though all the posts belong to the
same topic. Profiling in production revealed that this accounted for a
significant amount of request time for a user that is not staff or anon.
Therefore, we're optimizing this by adding memoizing the topic level
calls in `PostGuardian`. Speficifally, the result of
`TopicGuardian#can_see_topic?` and `PostGuardian#can_create_post?`
method calls are memoized per topic.

Locally profiling shows a significant improvement for normal users
loading a topic with 100 posts.

Benchmark script command: `ruby script/bench.rb --unicorn --skip-bundle-assets --iterations 100`

Before:

```
topic user:
  50: 114
  75: 117
  90: 122
  99: 209
topic.json user:
  50: 67
  75: 69
  90: 72
  99: 162
```

After:

```
topic user:
  50: 101
  75: 104
  90: 107
  99: 184
topic.json user:
  50: 53
  75: 53
  90: 56
  99: 138
```
2023-01-03 09:00:42 +08:00
Alan Guo Xiang Tan be1ae9411b
PERF: Remove redundant DB queries from `TopicView` (#19658)
This commit removes 3 redundant DB queries when loading posts.

1. `@posts` will eventually have to be loaded so we can avoid two
additional queries.

2. No need to preload topic association of posts as we're already
dealing with a fixed topic in `TopicView`.
2023-01-03 08:17:52 +08:00
David Taylor eebe2f256c
DEV: Skip s3 asset deletion when in readonly mode (#19611)
In some situations (e.g. disaster recovery), it may make sense to spin up a temporary readonly version of a cluster. In that situation, the s3 `expire_missing_assets` job would delete assets which are still in use by the canonical read-write version of the cluster.

To avoid that, this commit will skip deletion if the site is currently in readonly mode.
2022-12-30 11:35:40 +00:00
Alan Guo Xiang Tan 0da79561c3
DEV: Improve/Fix script/bench.rb (#19646)
1. Fix bug where we were not waiting for all unicorn workers to start up
before running benchmarks.

2. Fix a bug where headers were not used when benchmarking. Admin
benchmarks were basically running as anon user.

3. Disable rate limits when in profile env. We're pretty much going to
hit the rate limit every time as a normal user.

4. Benchmark against topic with a fixed posts count of 100. Previously profiling script was just randomly creating posts
and we would benchmark against a topic with a fixed posts count of 30.
Sometimes, the script fails because no topics with a posts count of 30
exists.

5. Benchmarks are not run against a normal user on top of anon and
admin.

6. Add script option to select tests that should be run.
2022-12-30 07:25:11 +08:00
Isaac Janzen e5349e43af
DEV: Update group moderator behavior to better mimic staff (#19618)
# Context
When a topic is reviewable by a group we give those group moderators some admin abilities including the ability to delete a topic.

# Problem
There are two main problems:

1. Currently when a group moderator deletes a topic they are redirected to root (not the same for staff)
2. Viewing the categories deleted topics (`c/foo/1/?status=deleted`) does not display the deleted topic to the group moderator (not the same for staff).

# Fix
If the `deleted_by` user is part a group that matches the `reviewable_by_group` on a topic then don't redirect. This is the default interaction for staff to give them the ability to do things like restore the topic in case it was accidentally deleted.

To render the deleted topics as expected for the group moderator I am utilizing [the guardian scope of `guardian.can_see_deleted_topics?` for said category](https://github.com/discourse/discourse/pull/19618/files#diff-288e61b8bacdb29d9c2e05b42da6837b0036dcf1867332d977ca7c5e74a44297R802-R803)
2022-12-29 10:07:03 -06:00
David Taylor 104a16610a DEV: Configure prettier for hbs templates 2022-12-28 13:11:12 +00:00
David Taylor d4d9d60a5f
DEV: Print system test logs with other test metadata (#19637)
Previously, browser logs would be printed to STDOUT halfway through the test run. This commit changes the behaviour so that the logs are included in the failure summary along with other rspec failure information.
2022-12-28 10:47:57 +00:00
Ted Johansson 06db264f24
FIX: Gracefully handle DNS issued from SSRF lookup when inline oneboxing (#19631)
There is an issue where chat message processing breaks due to
unhandles `SocketError` exceptions originating in the SSRF check,
specifically in `FinalDestination::Resolver`.

This change gives `FinalDestination::SSRFDetector` a new error class
to wrap the `SocketError` in, and haves the `RetrieveTitle` class
handle that error gracefully.
2022-12-28 10:30:20 +08:00
Alan Guo Xiang Tan 1fd0e82da7
PERF: Fix N+1 queries problem on topic view page (#19629)
`User#flair_group` was not preloaded leading to the N+1 queries problem
when multiple users have flair groups.
2022-12-27 09:05:37 +08:00
Osama Sayegh d8b39810d2
DEV: Stop leaking state in dashboard controller specs (#19608)
A few specs in `dashboard_controller_spec.rb` set some state in redis but don't clean it up afterwards which causes other specs to fail when they're ran after `dashboard_controller_spec.rb`.

Related commit: 18467d4.
2022-12-23 15:41:30 +03:00
Alan Guo Xiang Tan a8ee56ebee
PERF: Remove unnecessary query from `TopicQuery.remove_muted_tags` (#19586)
When `default_tags_muted` site settings has not been set, there is no
need to execute the query.
2022-12-23 04:29:17 +08:00
Penar Musaraj 8546c2084a
DEV: Load SVG sprites during system spec runs (#19497)
Co-authored-by: David Taylor <david@taylorhq.com>
2022-12-22 08:13:43 -05:00
Alan Guo Xiang Tan 4eee1320b0
PERF: Fix N+1 queries when serializing topic posters (#19545)
At the time of writing, this is how the `TopicPosterSerializer` looks
like:

```
class TopicPosterSerializer < ApplicationSerializer
  attributes :extras, :description

  has_one :user, serializer: PosterSerializer
  has_one :primary_group, serializer: PrimaryGroupSerializer
  has_one :flair_group, serializer: FlairGroupSerializer
end
```

Within `PosterSerializer`, the `primary_group` and `flair_group`
association is requested on the `user` object. However, the associations
have not been loaded on the `user` object at this point leading to the
N+1 queries problem. One may wonder
why the associations have not been loaded when the `TopicPosterSerializer`
has `has_one :primary_group` and `has_one :flair_group`. It turns out that `TopicPoster`
is just a struct containing the  `user`, `primary_group` and
`flair_group` objects. The `primary_group` and `flair_group`
ActiveRecord objects are loaded seperately in `UserLookup` and not preloaded when querying for
the users. This is done for performance reason so that we are able to
load the `primary_group` and `flair_group` records in a single query
without duplication.
2022-12-22 05:30:29 +08:00
Bianca Nenciu 58479fe10b
DEV: Pass kwargs to defined method (#19552) 2022-12-21 19:02:40 +02:00
David Taylor f1ec8c869a
DEV: Fix FinalDestination::Resolver race condition (#19558)
We were adding to the resolver's work queue before setting up the `@lookup` and `@parent` information. That could lead to the lookup being performed on the wrong (or `nil`) hostname. This also lead to some flakiness in specs.
2022-12-21 16:02:24 +00:00
David Taylor a6af981e1b
DEV: Add retry logic to `plugin:install_all_official` (#19551)
This task sometimes fails in CI due to temporary network issues. Retrying twice should help resolve those situations without needing to manually restart the job.
2022-12-21 15:31:03 +00:00
Jarek Radosz dc13e8ecfd
DEV: Fix TurboTests::Runner fail_fast condition (#19540)
It fast-failed after the first failure regardless of the param…
2022-12-21 02:33:52 +01:00
Martin Brennan 94b258deda
FIX: TL0 could not message group with everyone messageable_level (#19525)
The commits e62e93f83a and
d6bd4ad7ee caused a regression
to the behaviour added for
https://meta.discourse.org/t/allow-tl0-to-write-messages-to-staff-group-not-to-other-members-or-non-staff/124335,
which allowed a user to message a group with the messageable_level
set to Everyone even if they were TL0 (or otherwise did not reach
the appropriate trust level). This commit fixes the issue and adjusts
the spec to reflect the real scenario.

c.f. https://meta.discourse.org/t/tl0-cant-message-groups-with-messageable-level-everyone-recession/249205
2022-12-20 13:11:14 +10:00
Blake Erickson ae2153b330
UX: Wizard Step Enhancements (#19487)
* UX: Wizard Step Enhancements

- Remove illustrations
- Add Emoji graphic to top of steps
- Add description below step title
- Move point of contact to last step

* Move step count to header, plus some button navigation tweaks

* add remaining emoji to step headers

* fix button logic on steps

* Update Point of Contact

* remove automated messages field

* adjust styling for counter, title, and emoji

* Update wording for logos

* Fix tests

* fix prettier

* fix specs

* set same with for steps except for styling screen

* use sentence case; remove duplicate copy under your organization fields

* fix missing buttons on small screens

* add spacing to buttons; adjust font weight to labels

* adjust styling for community logo step; use sentence case for button

* update copy for point of contact text helper

* use sentence case for field labels

* fix ui tests

* use btn-back class to fix ui tests

* reduce bottom margin for toggle fields

* clean up

Co-authored-by: Ella <ella.estigoy@gmail.com>
2022-12-19 17:24:09 -07:00
Martin Brennan 6b9c0ee554
DEV: Change HashtagAutocompleteService to use DiscoursePluginRegistry (#19491)
Follow up to a review in #18937, this commit changes the HashtagAutocompleteService to no longer use class variables to register hashtag data sources or types in context priority order. This is to address multisite concerns, where one site could e.g. have chat disabled and another might not. The filtered plugin registers I added will not be included if the plugin is disabled.
2022-12-19 13:46:17 +10:00
Martin Brennan baf78d3d91
FIX: Add missing user_id args for ChatMessage.cook (#19508)
In both ChatMessage#rebake! and in ChatMessageProcessor
when we were calling ChatMessage.cook we were missing the
user_id to cook with, which causes missed hashtag cooks
because of missing permissions.
2022-12-19 11:05:37 +10:00
Krzysztof Kotlarek 09d15d4c7f
FIX: access to category chat only when user can create post (#19488)
Previously, restricted category chat channel was available for all groups - even `readonly`. From now on, only user who belong to group with `create_post` or `full` permissions can access that chat channel.
2022-12-19 11:35:28 +11:00
Rafael dos Santos Silva b8c1289c7a
DEV: Fix YAML load in new Ruby (#19500) 2022-12-16 17:07:18 -03:00
Bianca Nenciu b80765f1f4
DEV: Remove enable_whispers site setting (#19196)
* DEV: Remove enable_whispers site setting

Whispers are enabled as long as there is at least one group allowed to
whisper, see whispers_allowed_groups site setting.

* DEV: Always enable whispers for admins if at least one group is allowed.
2022-12-16 18:42:51 +02:00
Ryan Vandersmith e6439e89cf
FEATURE: Onebox for Embed Motoko (#19293) 2022-12-16 09:59:40 -05:00
Martin Brennan 624b1b3820
FIX: Remove user_option saving for bookmark auto delete pref (#19476)
We were changing the user's user_option.bookmark_auto_delete_preference
to whatever they changed it to in the bookmark modal to use as default
for future bookmarks. However this was leading to a lot of confusion
since if you wanted to set it for one bookmark you had to remember to
change it back on the next one.

This commit removes that automatic functionality, and instead moves
the bookmark auto delete preference to User Preferences > Interface
in an explicit dropdown.
2022-12-16 08:50:31 +10:00
Osama Sayegh 1c03d6f9b9
FEATURE: Send notifications to admins when new features are released (#19460)
This commit adds a new notification that gets sent to admins when the site gets new features after an upgrade/deploy. Clicking on the notification takes the admin to the admin dashboard at `/admin` where they can see the new features under the "New Features" section.

Internal topic: t/87166.
2022-12-15 20:12:53 +03:00
Martin Brennan ec9ec1e04e
FEATURE: Sort hashtags starting with term higher priority (#19463)
This introduces another "section" of queries to the
hashtag autocomplete search, which returns results for
each type that start with the search term. So now results
will be in this order, and within these sections ordered
by the types in priority order:

1. Exact matches sorted by type
2. "starts with" sorted by type
3. Everything else sorted by type then name within type
2022-12-15 13:01:44 +10:00
Gerhard Schlager 4e42759caa
FIX: Use correct plural rules for Russian (#19467)
Previously this didn't work because Transifex didn't support "many".
2022-12-14 18:56:46 +01:00
Blake Erickson 492f68c462
FIX: Unable to change homepage style via wizard (#19462)
Depending on the current state of things, sometimes the homepage style
wouldn't update because we were incorrectly blocking updates the
`desktop_category_page_style` site setting if the first item in the top
menu was 'categories'.

Added a test case to handle this situation.

See https://meta.discourse.org/t/248354
2022-12-13 17:52:59 -07:00
Michael Brown 618fb5b34d FIX: properly count DistributedMutex locking attempts
When originally introduced, `attempts` was only used in the read-only check
context.

With the introduction of the exponential backoff in cda370db, `attempts` was
also used to count loop iterations, but was left inside the if block instead of
being incremented every loop, meaning the exponential backoff was only
happening when the site was recently readonly.

Co-authored-by: jbrw <jamie.wilson@discourse.org>
2022-12-13 17:27:13 -05:00
Blake Erickson de53cf7657
FEATURE: Add chat and sidebar toggles to the setup wizard (#19347)
* FEATURE: Add chat and sidebar toggles to the setup wizard

- Fix css alighnment
- Add Enable Chat Toggle
- Add Enable Sidebar Toggle

* Check for the chat plugin

* Account for new sidebar step

* update chat and sidebar description

* UI: add checkmark as a visual indicator that it is enabled

* use new navigation_memu site setting for enabling the sidebar

* fix tests

* Add tests

* Update lib/wizard/step_updater.rb

Use HEADER_DROPDOWN instead of LEGACY

Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>

* Fix spec. Use HEADER_DROPDOWN instead of LEGACY

Co-authored-by: Ella <ella.estigoy@gmail.com>
Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
2022-12-12 14:30:21 -07:00
Bianca Nenciu 17b7ab0d7b
FIX: Make sure generated tsqueries are valid (#19368)
The tsquery used for searching is generated using both functions from
Ruby and Postgresql (for example, unaccent function). Depending on the
term used, it generated an invalid tsquery. For example "can’t"
generated "''can''t''" instead of "''can''''t''".
2022-12-12 17:57:20 +02:00
jbrw 1a48ea767e
DEV: Allow additional TopicList preloaded associations (#18891)
This provides a means to allow additional associations to be preloaded when generating a TopicList.
2022-12-12 09:08:13 -05:00
Martin Brennan b2acc416e7
FIX: Server-side hashtag lookups of secure categories for a user (#19377)
* FIX: Use Category.secured(guardian) for hashtag datasource

Follow up to comments in #19219, changing the category
hashtag datasource to use Category.secured(guardian) instead
of Site.new(guardian).categories here since the latter does
more work for not much benefit, and the query time is the
same. Also eliminates some Hash -> Model back and forth
busywork. Add some more specs too.

* FIX: Server-side hashtag lookup cooking user loading

When we were using the PrettyText.options.currentUser
and parsing back and forth with JSON for the hashtag
lookups server-side, we had a bug where the user's
secure categories were not loaded since we never actually
loaded a User model from the database, only parsed it
from JSON.

This commit fixes the issue by instead using the
PretyText.options.userId and looking up the user directly
from the database when calling hashtag_lookup via the
PrettyText::Helpers code when cooking server-side. Added
the missing spec to check for this as well.
2022-12-09 10:34:25 +10:00
David Taylor 03fadf91f0
FEATURE: Optionally allow a separate `s3_asset_cdn_url` to be specified (#19284)
If configured, this will be used for static JS assets which are stored on S3. This can be useful if you want to use different CDN providers/configuration for Uploads and JS
2022-12-08 10:36:20 +00:00
Martin Brennan 3fdb8ffb57
FEATURE: Allow showing hashtag autocomplete results without term (#19219)
This commit allows us to type # in the UI and present autocomplete
results immediately with the following logic for the topic composer,
and reversed for the chat composer:

* Categories the user can access and has not muted sorted by `topic_count`
* Tags the user can access and has not muted sorted by `topic_count`
* Chat channels the user is a member of sorted by `messages_count`

So in effect, we allow searching for hashtags without a search term.
To do this we add a new `search_without_term` to each data source so
each one can define how it wants to handle this logic.
2022-12-08 13:47:59 +10:00
Alan Guo Xiang Tan fde9e6bc25
DEV: Migrate sidebar site settings (#19336)
This new site setting replaces the
`enable_experimental_sidebar_hamburger` and `enable_sidebar` site
settings as the sidebar feature exits the experimental phase.

Note that we're replacing this without depreciation since the previous
site setting was considered experimental.

Internal Ref: /t/86563
2022-12-08 09:44:29 +08:00
Alan Guo Xiang Tan 773cf045b2
DEV: Update redis gem to 4.8.0 (#19350) 2022-12-08 06:48:44 +08:00
jbrw 64b781dacf
PERF: Perform only one category update when creating a new topic (#19361)
When under extremely high load, it has been observed that updating the categories table when creating a new topic can become a bottleneck.

This change will reduce the two updates to one when a new topic is created within a category, and therefore should help with performance when under extremely high load.
2022-12-07 14:35:13 -05:00
David Taylor 566793208e
DEV: Support colocation under `/admin` namespace in themes/plugins (#19353) 2022-12-07 14:24:03 +00:00
Andrei Prigorshnev a76d864c51
FEATURE: Show live user status on inline mentions on posts (#18683)
Note that we don't have a database table and a model for post mentions yet, and I decided to implement it without adding one to avoid heavy data migrations. Still, we may want to add such a model later, that would be convenient, we have such a model for mentions in chat.

Note that status appears on all mentions on all posts in a topic except of the case when you just posted a new post, and it appeared on the bottom of the topic. On such posts, status won't be shown immediately for now (you'll need to reload the page to see the status). I'll take care of it in one of the following PRs.
2022-12-06 19:10:36 +04:00
Rafael dos Santos Silva d247e5d37c
FEATURE: Youtube Short onebox support (#19335)
* FEATURE: Youtube Shorts onebox support

Co-authored-by: Canapin <canapin@gmail.com>
2022-12-06 11:56:48 -03:00
Daniel Waterworth 3a4ac3a7c0
FIX: Don't update url in GitImporter (#19273)
Since it's fetched and used elsewhere and expected to stay the same.
2022-12-01 10:50:06 -06:00
Selase Krakani 0ce38bd7bc
SECURITY: Restrict unlisted topic creation (#19259) 2022-12-01 10:26:35 +00:00
Martin Brennan 9513e7be6d
FIX: Email hashtag-cooked text replacement error (#19278)
In some cases (e.g. user notification emails) we
are passing an excerpted/stripped version of the
post HTML to Email::Styles, at which point the
<span> elements surrounding the hashtag text have
been stripped. This caused an error when trying to
remove that element to replace the text.

Instead we can just remove all elements inside
a.hashtag-cooked and replace with the raw #hashtag
text which will work in more cases.
2022-12-01 19:48:24 +10:00
Martin Brennan d516c575fd
FIX: Handle null svg class for excerpt parsing (#19276)
Follow-up to 9d50790530

In certain cases the svg may not a class, so we just
need safe navigation to avoid an error here.
2022-12-01 10:56:16 +10:00
Daniel Waterworth d9364a272e
FIX: When following redirects before cloning, use the first git request (#19269)
This is closer to git's redirect following behaviour. We prevented git
following redirects when we clone in order to prevent SSRF attacks.

Follow-up-to: 291bbc4fb9
2022-11-30 14:21:09 -06:00
Martin Brennan 9d50790530
FIX: Allow svg in oneboxer in certain cases (#19253)
When doing local oneboxes we sometimes want to allow
SVGs in the final preview HTML. The main case currently
is for the new cooked hashtags, which include an SVG
icon.

SVGs will be included in local oneboxes via `ExcerptParser` _only_
if they have the d-icon class, and if the caller for `post.excerpt`
specifies the `keep_svg: true` option.
2022-11-30 12:42:15 +10:00
Roman Rizzi 88a0384d43
FIX: Don't notify of post deletion when agreeing with automatic flags. (#19241) 2022-11-29 14:18:07 -03:00
Daniel Waterworth aab4ea1849
Version bump to v2.9.0.beta14 (#19242) 2022-11-29 10:59:53 -06:00
Bianca Nenciu 3048d3d07d
FEATURE: Track API and user API requests (#19186)
Adds stats for API and user API requests similar to regular page views.
This comes with a new report to visualize API requests per day like the
consolidated page views one.
2022-11-29 13:07:42 +02:00
Roman Rizzi 07a9163ea8
FEATURE: Deleting a user with their posts also deletes chat messages. (#19194)
This commit introduce a new API for registering callbacks, which we'll execute when a user gets destroyed, and the `delete_posts` opt is true. The chat plugin registers one callback and queues a job to destroy every message from that user in batches.
2022-11-28 13:32:57 -03:00
Martin Brennan f8d1b794cd
Version bump to v2.9.0.beta13 (#19212) 2022-11-28 10:58:43 +10:00
Martin Brennan 73803cf8f7
Revert "Version bump to v2.9.0.beta13 (#19210)" (#19211)
This reverts commit a71f6cf09b.

The github UI had an error I didn't notice which resulted
in a security commit being merged _after_ the bump, now
I have to redo the bump.
2022-11-28 10:57:06 +10:00
Martin Brennan a71f6cf09b
Version bump to v2.9.0.beta13 (#19210) 2022-11-28 10:44:25 +10:00
Rafael dos Santos Silva 90411540c7
FIX: Use correct Regexp flag to ignore case (#19184)
Ruby 3.2 started enforcing valid string flags in Regexp constructor.
2022-11-25 10:56:59 -03:00
Sam 755ca0fcbb
PERF: stop downloading images from post processor and lean on uploads
Previously we would unconditionally fetch all images via HTTP to grab
original sizing from cooked post processor in 2 different spots.

This was wasteful as we already calculate and cache this info in upload records.

This also simplifies some specs and reduces use of mocks.
2022-11-25 12:40:31 +11:00
David Taylor abe2813789
DEV: Add useful error message for hbs register_asset (#19185)
This hasn't been necessary for many years, and is no longer supported following 84bec1cb. Only extremely old plugins might be trying to do this. All the affected open-source plugins I can find have already been updated.
2022-11-24 19:03:06 +00:00
David Taylor 84bec1cbae
DEV: Cleanup legacy asset compilation gems and code (#19177)
We now use Ember CLI (core/plugins) and DiscourseJSProcessor (themes) for all Ember and template compilation. This commit removes the remnants of the legacy Sprockets-based Ember compilation system.

Sprockets, and its DiscourseJSProcess-based Babel transformations, is still in use for a few assets. Ideally that will be removed/replaced in the near future.
2022-11-24 12:13:59 +00:00
David Taylor 174a8b431b
DEV: Support passing relative URLs CSP builder (#19176)
Raw paths like `/test/path` are not supported natively in the CSP. This commit prepends the site's base URL to these paths. This allows plugins to add 'local' assets to the CSP without needing to hardcode the site's hostname.
2022-11-24 11:27:47 +00:00
Osama Sayegh 65f57a4d05
DEV: Explicitly define primary_email_verified? method for managed authenticators (#19127)
We're going to change the default return value of the `primary_email_verified?` method of `Auth::ManagedAuthenticator` to false, so we need to explicitly define the method on authenticators to return true where it makes sense to do so.

Internal topic: t/82084.
2022-11-24 06:46:06 +03:00
Gerhard Schlager 62be87d5f3
FIX: Filtering rows of S3 inventory files was too strict (#19153)
In some setups the keys start with "original/" and "optimized/" and in some setups the key is something like "foo/original/", so lets make the filter less strict.
2022-11-22 21:41:22 +01:00
Gerhard Schlager c75b6cd999
UX: Update "education.dominating_topic" and raise default percentage (#19154)
See /t/82396
2022-11-22 21:11:53 +01:00
Daniel Waterworth f895f27b02
FIX: When filtering tags for visibility, respect tag group permissions (#19152) 2022-11-22 12:55:57 -06:00
Rafael dos Santos Silva e901403621
FEATURE: API to customize server side composer errors handling in the client side (#19107)
This will be used by plugins to handle the client side of their custom
post validations without having to overwrite the whole composer save
action as it was done in other plugins.

Co-authored-by: Penar Musaraj <pmusaraj@gmail.com>
2022-11-21 13:11:29 -03:00
Martin Brennan d3f02a1270
FEATURE: Generic hashtag autocomplete lookup and markdown cooking (#18937)
This commit fleshes out and adds functionality for the new `#hashtag` search and
lookup system, still hidden behind the `enable_experimental_hashtag_autocomplete`
feature flag.

**Serverside**

We have two plugin API registration methods that are used to define data sources
(`register_hashtag_data_source`) and hashtag result type priorities depending on
the context (`register_hashtag_type_in_context`). Reading the comments in plugin.rb
should make it clear what these are doing. Reading the `HashtagAutocompleteService`
in full will likely help a lot as well.

Each data source is responsible for providing its own **lookup** and **search**
method that returns hashtag results based on the arguments provided. For example,
the category hashtag data source has to take into account parent categories and
how they relate, and each data source has to define their own icon to use for the
hashtag, and so on.

The `Site` serializer has two new attributes that source data from `HashtagAutocompleteService`.
There is `hashtag_icons` that is just a simple array of all the different icons that
can be used for allowlisting in our markdown pipeline, and there is `hashtag_context_configurations`
that is used to store the type priority orders for each registered context.

When sending emails, we cannot render the SVG icons for hashtags, so
we need to change the HTML hashtags to the normal `#hashtag` text.

**Markdown**

The `hashtag-autocomplete.js` file is where I have added the new `hashtag-autocomplete`
markdown rule, and like all of our rules this is used to cook the raw text on both the clientside
and on the serverside using MiniRacer. Only on the server side do we actually reach out to
the database with the `hashtagLookup` function, on the clientside we just render a plainer
version of the hashtag HTML. Only in the composer preview do we do further lookups based
on this.

This rule is the first one (that I can find) that uses the `currentUser` based on a passed
in `user_id` for guardian checks in markdown rendering code. This is the `last_editor_id`
for both the post and chat message. In some cases we need to cook without a user present,
so the `Discourse.system_user` is used in this case.

**Chat Channels**

This also contains the changes required for chat so that chat channels can be used
as a data source for hashtag searches and lookups. This data source will only be
used when `enable_experimental_hashtag_autocomplete` is `true`, so we don't have
to worry about channel results suddenly turning up.

------

**Known Rough Edges**

- Onebox excerpts will not render the icon svg/use tags, I plan to address that in a follow up PR
- Selecting a hashtag + pressing the Quote button will result in weird behaviour, I plan to address that in a follow up PR
- Mixed hashtag contexts for hashtags without a type suffix will not work correctly, e.g. #ux which is both a category and a channel slug will resolve to a category when used inside a post or within a [chat] transcript in that post. Users can get around this manually by adding the correct suffix, for example ::channel. We may get to this at some point in future
- Icons will not show for the hashtags in emails since SVG support is so terrible in email (this is not likely to be resolved, but still noting for posterity)
- Additional refinements and review fixes wil
2022-11-21 08:37:06 +10:00
Gerhard Schlager a597ef7131
PERF: Speed up S3 inventory updates (#19110)
The UPDATE statement could lock the `uploads` table for a very long time
when the `verification_status` of lots of uploads changed. Splitting up
and simplifying the UPDATE solves that problem.

Also, this change ensures that only the needed data from the inventory
gets inserted into the `TEMP TABLE`. For example, there's no need to
have records for optimized images in that table when the `uploads` table
gets updated.
2022-11-20 21:52:30 +01:00
Sam 4f63bc8ed2
FEATURE: hidden site setting to suppress unsecured categories from admins (#19098)
The hidden site setting `suppress_secured_categories_from_admin` will
suppress visibility of categories without explicit access from admins
in a few key areas (category drop downs and topic lists)

It is not intended to be a security wall since admins can amend any site
setting. Instead it is feature that allows hiding the categories from the
UI.

Admins will still be able to see topics in categories without explicit
access using direct URLs or flags.

Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
2022-11-18 14:37:36 +11:00
Blake Erickson 7f63e72a50
UX: Mark pre-populated dropdowns as not required (#19064)
These two dropdown fields in the setup wizard are pre-populated, and
there is no way to de-select a value, you can only change it. So we can
remove the required attribute so that an asterisk doesn't show up in the
UI.
2022-11-16 14:53:45 -07:00
Du Jiajun 41e6b516e5
FIX: Support unicode in search filter @username (#18804) 2022-11-16 10:42:37 +01:00
David Taylor ca72d8d030
PERF: Adjust node memory threshold for assets:precompile (#19040)
Previously we were forcing node's max-old-space-size to be 2GB. This override was added in a01b1dd6 to avoid issues caused by a lower default node heap_size_limit on machines with less memory.

This commit makes that `max-old-space-size` override more specific so that it only applies to machines with less memory. Other machines will go use Node's defaults.

The override is also lowered to 1GB. This is still high enough for the build to complete, while reducing memory usage.

https://meta.discourse.org/t/245547
2022-11-15 22:02:13 +00:00
Daniel Waterworth 47709c6d49
DEV: Reinstate --single-branch when cloning themes (#19026) 2022-11-15 13:23:57 -06:00
Blake Erickson 7be53b1588
FEATURE: Default Composer Category Site Setting (#18967)
* FEATURE: Default Composer Category Site Setting

- Create the default_composer_category site setting
- Replace general_category_id logic for auto selecting the composer
  category
- Prevent Uncategorized from being selected if not allowed
- Add default_composer_category option to seeded categories
- Create a migration to populate the default_composer_category site
  setting if there is a general_category_id populated
- Added some tests

* Add missing translation for the new site setting

* fix some js tests

* Just check that the header value is null
2022-11-14 11:09:57 -07:00
Martin Brennan 4306522a4e
Version bump to v2.9.0.beta12 (#19006) 2022-11-14 13:07:16 +10:00
Jarek Radosz e54a3d5ea9
DEV: Add `START_ID` to `uploads:downsize` task (#18992) 2022-11-11 22:51:48 +01:00
Jarek Radosz dc8a7e74f4
FIX: Allow attr updates of over-size-limit uploads (#18986) 2022-11-11 17:56:11 +01:00
Jarek Radosz bc22fe4fdf
DEV: Convert the downsizing script to a rake task (#18976)
…to make it testable!
2022-11-11 13:00:44 +01:00
Selase Krakani 0b367216ae
FIX: Ensure moderators_manage_categories_and_groups is respected (#18884)
Currently, moderators are able to set primary group for users
irrespective of the of the `moderators_manage_categories_and_groups` site
setting value.

This change updates Guardian implementation to honour it.
2022-11-11 11:06:05 +00:00
Jarek Radosz 3e0196cbbf
FIX: Shrinking images where smaller image upload exists (#18965) 2022-11-10 12:43:56 +01:00
Martin Brennan f8f55cef67
DEV: TODO followups (#18936)
* Remove old bookmark column ignores to follow up b22450c7a8
* Change some group site setting checks to use the _map helper
* Remove old secure_media helper stub for chat
* Change attr_accessor to attr_reader for preloaded_custom_fields to follow up 70af45055a
2022-11-09 07:48:05 +10:00
David Taylor 8700c5ee6b
PERF: Make stylesheet hashes consistent between deploys (#18909)
Previously the stylesheet cachebusting hash was based on the maximum mtime of files. This works well in development and during in-container updates (e.g. via docker_manager). However, when a fresh docker image is created for each deploy, the file mtimes will change even if the contents has not.

This commit changes the production logic to calculate the cachebuster from the filenames and contents of the relevant assets. This should be consistent across deploys, thereby improving cache hits and improving page load times.
2022-11-07 16:13:35 +00:00
David Taylor f30f9ec5d9
PERF: Update `s3:expire_missing_assets` to delete in batches (#18908)
Some sites may have thousands of stale assets - deleting them one-by-one is very slow.

Followup to e8570b5cc9
2022-11-07 12:53:14 +00:00
David Taylor e8570b5cc9
Fix and improve `s3:expire_missing_assets` task (#18863)
- Ensure it works with prefixed S3 buckets
- Perform a sanity check that all current assets are present on S3 before starting deletion
- Remove the lifecycle rule configuration and delete expired assets immediately. This task should be run post-deploy anyway, so adding a 10-day window is not required
2022-11-07 10:44:45 +00:00
Martin Brennan d6bd4ad7ee
FIX: Make can_send_private_messages not reliant on system user (#18812)
Since the system user is a regular user, it can have its
`allow_private_messages` user option turned off, which
with our current `can_send_private_message?(Discourse.system_user)`
check inside the CurrentUserSerializer, will prevent any
user from sending messages in the UI if the system user is not
accepting PMs.

This commit adds a new `can_send_private_messages?` method to
the Guardian, which can be used in serializers and not depend
on the system user. When the user actually sends a message
we still rely on the old `can_send_private_message?(target)`
call to see if they are allowed to send the message to the target.
The new method is just to say they can "generally" send
private messages.
2022-11-07 09:11:18 +10:00
Vinoth Kannan dea44ec923
FEATURE: new site setting to hide user profiles by default. (#18864)
Previously, we didn't have a site-wide setting to set the default behavior for user profile visibility and user presence features. But we already have a user preference for that.
2022-11-06 16:44:17 +05:30
Daniel Waterworth 6f48502dd2
DEV: Add rake task to install a theme from an archive (#18890) 2022-11-04 16:42:07 -05:00
David Taylor b18ebc9648
PERF: Correct should_skip? logic in `s3:upload` (#18862)
This task is supposed to skip uploading if the asset is already present in S3. However, when a bucket 'folder path' was configured, this logic was broken and so the assets would be re-uploaded every time.

This commit fixes that logic to include the bucket 'folder path' in the check
2022-11-04 17:50:46 +00:00
Joffrey JAFFEUX 11f3618b80
DEV: initial system tests for chat and plugins (#18881)
This is a very basic to ensure it's working and open future possible work
2022-11-04 15:06:24 +01:00