Class: Category
Constant Summary
collapse
- RESERVED_SLUGS =
["none"]
- SLUG_REF_SEPARATOR =
":"
- @@subcategory_ids =
DistributedCache.new("subcategory_ids")
- @@url_cache =
DistributedCache.new("category_url")
HasCustomFields::CUSTOM_FIELDS_MAX_ITEMS, HasCustomFields::CUSTOM_FIELDS_MAX_VALUE_LENGTH
Constants included
from Searchable
Searchable::PRIORITIES
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
#enqueue_destroyed_web_hook
#clear_custom_fields, #create_singular, #custom_field_preloaded?, #custom_fields, #custom_fields=, #custom_fields_clean?, #custom_fields_preloaded?, #reload, #save_custom_fields, #set_preloaded_custom_fields, #upsert_custom_fields
#move_to
Instance Attribute Details
#displayable_topics ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def displayable_topics
@displayable_topics
end
|
#has_children ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def has_children
@has_children
end
|
#notification_level ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def notification_level
@notification_level
end
|
#permission ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def permission
@permission
end
|
#skip_category_definition ⇒ Object
Allows us to skip creating the category definition topic in tests.
206
207
208
|
# File 'app/models/category.rb', line 206
def skip_category_definition
@skip_category_definition
end
|
#subcategory_ids ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def subcategory_ids
@subcategory_ids
end
|
#subcategory_list ⇒ Object
permission is just used by serialization we may consider wrapping this in another spot
198
199
200
|
# File 'app/models/category.rb', line 198
def subcategory_list
@subcategory_list
end
|
Class Method Details
.auto_bump_topic! ⇒ Object
683
684
685
686
687
688
689
|
# File 'app/models/category.rb', line 683
def self.auto_bump_topic!
Category
.joins(:category_setting)
.where("category_settings.num_auto_bump_daily > 0")
.shuffle
.any?(&:auto_bump_topic!)
end
|
.clear_subcategory_ids ⇒ Object
291
292
293
|
# File 'app/models/category.rb', line 291
def self.clear_subcategory_ids
@@subcategory_ids.clear
end
|
.ensure_consistency! ⇒ Object
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
|
# File 'app/models/category.rb', line 997
def self.ensure_consistency!
sql = <<~SQL
SELECT t.id FROM topics t
JOIN categories c ON c.topic_id = t.id
LEFT JOIN posts p ON p.topic_id = t.id AND p.post_number = 1
WHERE p.id IS NULL
SQL
DB.query_single(sql).each { |id| Topic.with_deleted.find_by(id: id).destroy! }
sql = <<~SQL
UPDATE categories c
SET topic_id = NULL
WHERE c.id IN (
SELECT c2.id FROM categories c2
LEFT JOIN topics t ON t.id = c2.topic_id AND t.deleted_at IS NULL
WHERE t.id IS NULL AND c2.topic_id IS NOT NULL
)
SQL
DB.exec(sql)
Category
.joins("LEFT JOIN topics ON categories.topic_id = topics.id AND topics.deleted_at IS NULL")
.where("categories.id <> ?", SiteSetting.uncategorized_category_id)
.where(topics: { id: nil })
.find_each { |category| category.create_category_definition }
end
|
.find_by_email(email) ⇒ Object
836
837
838
|
# File 'app/models/category.rb', line 836
def self.find_by_email(email)
self.where("string_to_array(email_in, '|') @> ARRAY[?]", Email.downcase(email)).first
end
|
.find_by_slug(category_slug, parent_category_slug = nil) ⇒ Object
953
954
955
956
957
|
# File 'app/models/category.rb', line 953
def self.find_by_slug(category_slug, parent_category_slug = nil)
return nil if category_slug.nil?
find_by_slug_path([parent_category_slug, category_slug].compact)
end
|
.find_by_slug_path(slug_path) ⇒ Object
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
|
# File 'app/models/category.rb', line 922
def self.find_by_slug_path(slug_path)
return nil if slug_path.empty?
return nil if slug_path.size > SiteSetting.max_category_nesting
slug_path.map! { |slug| CGI.escape(slug.downcase) }
query =
slug_path.inject(nil) do |parent_id, slug|
category = Category.where(slug: slug, parent_category_id: parent_id)
if match_id = /\A(\d+)-category/.match(slug).presence
category = category.or(Category.where(id: match_id[1], parent_category_id: parent_id))
end
category.select(:id)
end
Category.find_by_id(query)
end
|
.find_by_slug_path_with_id(slug_path_with_id) ⇒ Object
942
943
944
945
946
947
948
949
950
951
|
# File 'app/models/category.rb', line 942
def self.find_by_slug_path_with_id(slug_path_with_id)
slug_path = slug_path_with_id.split("/")
if slug_path.last =~ /\A\d+\Z/
id = slug_path.pop.to_i
Category.find_by_id(id)
else
Category.find_by_slug_path(slug_path)
end
end
|
.ids_from_slugs(slugs) ⇒ Object
Accepts an array of slugs with each item in the array Returns the category ids of the last slug in the array. The slugs array has to follow the proper category nesting hierarchy. If any of the slug in the array is invalid or if the slugs array does not follow the proper category nesting hierarchy, nil is returned.
When only a single slug is provided, the category id of all the categories with that slug is returned.
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
|
# File 'app/models/category.rb', line 230
def self.ids_from_slugs(slugs)
return [] if slugs.blank?
params = {}
params_index = 0
sqls =
slugs.map do |slug|
category_slugs =
slug.split(":").first(SiteSetting.max_category_nesting).map { Slug.for(_1, "") }
sql = ""
if category_slugs.length == 1
params[:"slug_#{params_index}"] = category_slugs.first
sql = "SELECT id FROM categories WHERE slug = :slug_#{params_index}"
params_index += 1
else
category_slugs.each_with_index do |category_slug, index|
params[:"slug_#{params_index}"] = category_slug
sql =
if index == 0
"SELECT id FROM categories WHERE slug = :slug_#{params_index} AND parent_category_id IS NULL"
else
"SELECT id FROM categories WHERE parent_category_id = (#{sql}) AND slug = :slug_#{params_index}"
end
params_index += 1
end
end
sql
end
DB.query_single(sqls.join("\nUNION ALL\n"), params)
end
|
.post_template ⇒ Object
Internal: Generate the text of post prompting to enter category description.
396
397
398
|
# File 'app/models/category.rb', line 396
def self.post_template
I18n.t("category.post_template", replace_paragraph: I18n.t("category.replace_paragraph"))
end
|
.query_category(slug_or_id, parent_category_id) ⇒ Object
828
829
830
831
832
833
834
|
# File 'app/models/category.rb', line 828
def self.query_category(slug_or_id, parent_category_id)
encoded_slug_or_id = CGI.escape(slug_or_id) if SiteSetting.slug_generation_method == "encoded"
self.where(
slug: (encoded_slug_or_id || slug_or_id),
parent_category_id: parent_category_id,
).first || self.where(id: slug_or_id.to_i, parent_category_id: parent_category_id).first
end
|
.query_parent_category(parent_slug) ⇒ Object
822
823
824
825
826
|
# File 'app/models/category.rb', line 822
def self.query_parent_category(parent_slug)
encoded_parent_slug = CGI.escape(parent_slug) if SiteSetting.slug_generation_method == "encoded"
self.where(slug: (encoded_parent_slug || parent_slug), parent_category_id: nil).pick(:id) ||
self.where(id: parent_slug.to_i).pick(:id)
end
|
.reset_topic_ids_cache ⇒ Object
216
217
218
|
# File 'app/models/category.rb', line 216
def self.reset_topic_ids_cache
topic_id_cache.clear
end
|
.resolve_permissions(permissions) ⇒ Object
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
|
# File 'app/models/category.rb', line 651
def self.resolve_permissions(permissions)
read_restricted = true
everyone = Group::AUTO_GROUPS[:everyone]
full = CategoryGroup.permission_types[:full]
mapped =
permissions.map do |group, permission|
group_id = Group.group_id_from_param(group)
permission = CategoryGroup.permission_types[permission] unless permission.is_a?(Integer)
[group_id, permission]
end
mapped.each do |group, permission|
return false, [] if group == everyone && permission == full
read_restricted = false if group == everyone
end
[read_restricted, mapped]
end
|
.scoped_to_permissions(guardian, permission_types) ⇒ Object
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
# File 'app/models/category.rb', line 303
def self.scoped_to_permissions(guardian, permission_types)
if guardian.try(:is_admin?)
all
elsif !guardian || guardian.anonymous?
if permission_types.include?(:readonly)
where("NOT categories.read_restricted")
else
where("1 = 0")
end
else
permissions = permission_types.map { |p| CategoryGroup.permission_types[p] }
where(
"(:staged AND LENGTH(COALESCE(email_in, '')) > 0 AND email_in_allow_strangers)
OR categories.id NOT IN (SELECT category_id FROM category_groups)
OR categories.id IN (
SELECT category_id
FROM category_groups
WHERE permission_type IN (:permissions)
AND (group_id = :everyone OR group_id IN (SELECT group_id FROM group_users WHERE user_id = :user_id))
)",
staged: guardian.is_staged?,
permissions: permissions,
user_id: guardian.user.id,
everyone: Group::AUTO_GROUPS[:everyone],
)
end
end
|
.subcategory_ids(category_id) ⇒ Object
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
|
# File 'app/models/category.rb', line 270
def self.subcategory_ids(category_id)
@@subcategory_ids.defer_get_set(category_id.to_s) do
sql = <<~SQL
WITH RECURSIVE subcategories AS (
SELECT :category_id id, 1 depth
UNION
SELECT categories.id, (subcategories.depth + 1) depth
FROM categories
JOIN subcategories ON subcategories.id = categories.parent_category_id
WHERE subcategories.depth < :max_category_nesting
)
SELECT id FROM subcategories
SQL
DB.query_single(
sql,
category_id: category_id,
max_category_nesting: SiteSetting.max_category_nesting,
)
end
end
|
.topic_id_cache ⇒ Object
208
209
210
|
# File 'app/models/category.rb', line 208
def self.topic_id_cache
@topic_id_cache ||= DistributedCache.new("category_topic_ids")
end
|
.topic_ids ⇒ Object
212
213
214
|
# File 'app/models/category.rb', line 212
def self.topic_ids
topic_id_cache.defer_get_set("ids") { Set.new(Category.pluck(:topic_id).compact) }
end
|
.update_stats ⇒ Object
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
|
# File 'app/models/category.rb', line 331
def self.update_stats
topics_with_post_count =
Topic
.select("topics.category_id, COUNT(*) topic_count, SUM(topics.posts_count) post_count")
.where(
"topics.id NOT IN (select cc.topic_id from categories cc WHERE topic_id IS NOT NULL)",
)
.group("topics.category_id")
.visible
.to_sql
DB.exec <<~SQL
UPDATE categories c
SET topic_count = COALESCE(x.topic_count, 0),
post_count = COALESCE(x.post_count, 0)
FROM (
SELECT ccc.id as category_id, stats.topic_count, stats.post_count
FROM categories ccc
LEFT JOIN (#{topics_with_post_count}) stats
ON stats.category_id = ccc.id
) x
WHERE x.category_id = c.id
AND (c.topic_count <> COALESCE(x.topic_count, 0) OR c.post_count <> COALESCE(x.post_count, 0))
SQL
Category.all.each do |c|
topics = c.topics.visible
topics = topics.where(["topics.id <> ?", c.topic_id]) if c.topic_id
c.topics_year = topics.created_since(1.year.ago).count
c.topics_month = topics.created_since(1.month.ago).count
c.topics_week = topics.created_since(1.week.ago).count
c.topics_day = topics.created_since(1.day.ago).count
posts = c.visible_posts
c.posts_year = posts.created_since(1.year.ago).count
c.posts_month = posts.created_since(1.month.ago).count
c.posts_week = posts.created_since(1.week.ago).count
c.posts_day = posts.created_since(1.day.ago).count
c.save if c.changed?
end
end
|
Instance Method Details
#access_category_via_group ⇒ Object
457
458
459
460
461
462
463
464
|
# File 'app/models/category.rb', line 457
def access_category_via_group
Group
.joins(:category_groups)
.where("category_groups.category_id = ?", self.id)
.where("groups.public_admission OR groups.allow_membership_requests")
.order(:allow_membership_requests)
.first
end
|
#allowed_tag_groups=(group_names) ⇒ Object
732
733
734
|
# File 'app/models/category.rb', line 732
def allowed_tag_groups=(group_names)
self.tag_groups = TagGroup.where(name: group_names).all.to_a
end
|
#apply_permissions ⇒ Object
641
642
643
644
645
646
647
648
649
|
# File 'app/models/category.rb', line 641
def apply_permissions
if @permissions
category_groups.destroy_all
@permissions.each do |group_id, permission_type|
category_groups.build(group_id: group_id, permission_type: permission_type)
end
@permissions = nil
end
end
|
#auto_bump_limiter ⇒ Object
674
675
676
677
|
# File 'app/models/category.rb', line 674
def auto_bump_limiter
return nil if num_auto_bump_daily.to_i == 0
RateLimiter.new(nil, "auto_bump_limit_#{self.id}", 1, 86_400 / num_auto_bump_daily.to_i)
end
|
#auto_bump_topic! ⇒ Object
will automatically bump a single topic if number of automatically bumped topics is smaller than threshold
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
|
# File 'app/models/category.rb', line 693
def auto_bump_topic!
return false if num_auto_bump_daily.to_i == 0
limiter = auto_bump_limiter
return false if !limiter.can_perform?
filters = []
DiscourseEvent.trigger(:filter_auto_bump_topics, self, filters)
relation = Topic
filters.each { |filter| relation = filter.call(relation) } if filters.length > 0
topic =
relation
.visible
.listable_topics
.exclude_scheduled_bump_topics
.where(category_id: self.id)
.where("id <> ?", self.topic_id)
.where("bumped_at < ?", (self.auto_bump_cooldown_days || 1).days.ago)
.where("pinned_at IS NULL AND NOT closed AND NOT archived")
.order("bumped_at ASC")
.limit(1)
.first
if topic
topic.add_small_action(Discourse.system_user, "autobumped", nil, bump: true)
limiter.performed!
true
else
false
end
end
|
#cannot_delete_reason ⇒ Object
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
|
# File 'app/models/category.rb', line 1050
def cannot_delete_reason
return I18n.t("category.cannot_delete.uncategorized") if self.uncategorized?
return I18n.t("category.cannot_delete.has_subcategories") if self.has_children?
if self.topic_count != 0
oldest_topic = self.topics.where.not(id: self.topic_id).order("created_at ASC").limit(1).first
if oldest_topic
I18n.t(
"category.cannot_delete.topic_exists",
count: self.topic_count,
topic_link: "<a href=\"#{oldest_topic.url}\">#{CGI.escapeHTML(oldest_topic.title)}</a>",
)
else
I18n.t("category.cannot_delete.topic_exists_no_oldest", count: self.topic_count)
end
end
end
|
#clear_auto_bump_cache! ⇒ Object
679
680
681
|
# File 'app/models/category.rb', line 679
def clear_auto_bump_cache!
auto_bump_limiter&.clear!
end
|
428
429
430
|
# File 'app/models/category.rb', line 428
def clear_related_site_settings
SiteSetting.general_category_id = -1 if self.id == SiteSetting.general_category_id
end
|
#clear_subcategory_ids ⇒ Object
#clear_url_cache ⇒ Object
865
866
867
|
# File 'app/models/category.rb', line 865
def clear_url_cache
@@url_cache.clear
end
|
#create_category_definition ⇒ Object
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
# File 'app/models/category.rb', line 400
def create_category_definition
return if skip_category_definition
Topic.transaction do
t =
Topic.new(
title: I18n.t("category.topic_prefix", category: name),
user: user,
pinned_at: Time.now,
category_id: id,
)
t.skip_callbacks = true
t.ignore_category_auto_close = true
t.delete_topic_timer(TopicTimer.types[:close])
t.save!(validate: false)
update_column(:topic_id, t.id)
post = t.posts.build(raw: description || post_template, user: user)
post.save!(validate: false)
update_column(:description, post.cooked) if description.present?
t
end
end
|
#create_category_permalink ⇒ Object
884
885
886
887
888
889
890
891
892
893
894
895
896
897
|
# File 'app/models/category.rb', line 884
def create_category_permalink
old_slug = saved_changes.transform_values(&:first)["slug"]
url = +"#{Discourse.base_path}/c"
url << "/#{parent_category.slug_path.join("/")}" if parent_category_id
url << "/#{old_slug}/#{id}"
url = Permalink.normalize_url(url)
if Permalink.where(url: url).exists?
Permalink.where(url: url).update_all(category_id: id)
else
Permalink.create(url: url, category_id: id)
end
end
|
#delete_category_permalink ⇒ Object
899
900
901
902
|
# File 'app/models/category.rb', line 899
def delete_category_permalink
permalink = Permalink.find_by_url("c/#{slug_path.join("/")}")
permalink.destroy if permalink
end
|
#depth_of_descendants(max_depth = SiteSetting.max_category_nesting) ⇒ Object
This is used in a validation so has to produce accurate results before the record has been saved
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
|
# File 'app/models/category.rb', line 563
def depth_of_descendants(max_depth = SiteSetting.max_category_nesting)
parent_id = self.parent_category_id
return max_depth if parent_id == id
DB.query(<<~SQL, id: id, parent_id: parent_id, max_depth: max_depth)[0].max
WITH RECURSIVE descendants(id, depth) AS (
SELECT :id :: integer, 0
UNION ALL
SELECT
categories.id,
CASE
WHEN categories.id = :parent_id THEN :max_depth
ELSE descendants.depth + 1
END
FROM categories, descendants
WHERE categories.parent_category_id = descendants.id
AND descendants.depth < :max_depth
)
SELECT max(depth) FROM descendants
SQL
end
|
#description_excerpt ⇒ Object
450
451
452
453
454
455
|
# File 'app/models/category.rb', line 450
def description_excerpt
return nil unless self.description
@@cache_excerpt ||= LruRedux::ThreadSafeCache.new(1000)
@@cache_excerpt.getset(self.description) { PrettyText.excerpt(description, 300) }
end
|
#description_text ⇒ Object
440
441
442
443
444
445
446
447
448
|
# File 'app/models/category.rb', line 440
def description_text
return nil unless self.description
@@cache_text ||= LruRedux::ThreadSafeCache.new(1000)
@@cache_text.getset(self.description) do
text = Nokogiri::HTML5.fragment(self.description).text.strip
ERB::Util.html_escape(text).html_safe
end
end
|
#downcase_email ⇒ Object
753
754
755
|
# File 'app/models/category.rb', line 753
def downcase_email
self.email_in = (email_in || "").strip.downcase.presence
end
|
#downcase_name ⇒ Object
787
788
789
|
# File 'app/models/category.rb', line 787
def downcase_name
self.name_lower = name.downcase if self.name
end
|
#duplicate_slug? ⇒ Boolean
466
467
468
|
# File 'app/models/category.rb', line 466
def duplicate_slug?
Category.where(slug: self.slug, parent_category_id: parent_category_id).where.not(id: id).any?
end
|
#email_in_validator ⇒ Object
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
|
# File 'app/models/category.rb', line 757
def email_in_validator
return if self.email_in.blank?
email_in
.split("|")
.each do |email|
escaped = Rack::Utils.escape_html(email)
if !Email.is_valid?(email)
self.errors.add(:base, I18n.t("category.errors.invalid_email_in", email: escaped))
elsif group = Group.find_by_email(email)
self.errors.add(
:base,
I18n.t(
"category.errors.email_already_used_in_group",
email: escaped,
group_name: Rack::Utils.escape_html(group.name),
),
)
elsif category = Category.where.not(id: self.id).find_by_email(email)
self.errors.add(
:base,
I18n.t(
"category.errors.email_already_used_in_category",
email: escaped,
category_name: Rack::Utils.escape_html(category.name),
),
)
end
end
end
|
#ensure_slug ⇒ Object
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
# File 'app/models/category.rb', line 470
def ensure_slug
return unless name.present?
self.name.strip!
if slug.present?
slug = SiteSetting.slug_generation_method == "encoded" ? CGI.unescape(self.slug) : self.slug
self.slug = Slug.for(slug, "", method: :encoded)
if self.slug.blank?
errors.add(:slug, :invalid)
elsif SiteSetting.slug_generation_method == "ascii" && !CGI.unescape(self.slug).ascii_only?
errors.add(:slug, I18n.t("category.errors.slug_contains_non_ascii_chars"))
elsif duplicate_slug?
errors.add(:slug, I18n.t("category.errors.is_already_in_use"))
end
else
self.slug = Slug.for(name, "")
self.slug = "" if duplicate_slug?
end
match_id = /\A(\d+)-category/.match(self.slug)
if match_id.present?
errors.add(:slug, :invalid) if new_record? || (match_id[1] != self.id.to_s)
end
end
|
#full_slug(separator = "-") ⇒ Object
858
859
860
861
|
# File 'app/models/category.rb', line 858
def full_slug(separator = "-")
start_idx = "#{Discourse.base_path}/c/".size
url[start_idx..-1].gsub("/", separator)
end
|
#group_names=(names) ⇒ Object
602
603
604
605
606
607
|
# File 'app/models/category.rb', line 602
def group_names=(names)
category_groups.destroy_all unless new_record?
ids = Group.where(name: names.split(",")).pluck(:id)
ids.each { |id| category_groups.build(group_id: id) }
end
|
#has_children? ⇒ Boolean
840
841
842
843
|
# File 'app/models/category.rb', line 840
def has_children?
@has_children ||= (id && Category.where(parent_category_id: id).exists?) ? :true : :false
@has_children == :true
end
|
1069
1070
1071
|
# File 'app/models/category.rb', line 1069
def has_restricted_tags?
tags.count > 0 || tag_groups.count > 0
end
|
#height_of_ancestors(max_height = SiteSetting.max_category_nesting) ⇒ Object
This is used in a validation so has to produce accurate results before the record has been saved
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
|
# File 'app/models/category.rb', line 535
def height_of_ancestors(max_height = SiteSetting.max_category_nesting)
parent_id = self.parent_category_id
return max_height if parent_id == id
DB.query(<<~SQL, id: id, parent_id: parent_id, max_height: max_height)[0].max
WITH RECURSIVE ancestors(parent_category_id, height) AS (
SELECT :parent_id :: integer, 0
UNION ALL
SELECT
categories.parent_category_id,
CASE
WHEN categories.parent_category_id = :id THEN :max_height
ELSE ancestors.height + 1
END
FROM categories, ancestors
WHERE categories.id = ancestors.parent_category_id
AND ancestors.height < :max_height
)
SELECT max(height) FROM ancestors
SQL
end
|
#index_search ⇒ Object
908
909
910
911
912
913
914
|
# File 'app/models/category.rb', line 908
def index_search
Jobs.enqueue(
:index_category_for_search,
category_id: self.id,
force: saved_change_to_attribute?(:name),
)
end
|
#parent_category_validator ⇒ Object
589
590
591
592
593
594
595
596
597
598
599
600
|
# File 'app/models/category.rb', line 589
def parent_category_validator
if parent_category_id
errors.add(:base, I18n.t("category.errors.uncategorized_parent")) if uncategorized?
errors.add(:base, I18n.t("category.errors.self_parent")) if parent_category_id == id
total_depth = height_of_ancestors + 1 + depth_of_descendants
if total_depth > SiteSetting.max_category_nesting
errors.add(:base, I18n.t("category.errors.depth"))
end
end
end
|
#permissions=(permissions) ⇒ Object
625
626
627
|
# File 'app/models/category.rb', line 625
def permissions=(permissions)
set_permissions(permissions)
end
|
#permissions_compatibility_validator ⇒ Object
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
|
# File 'app/models/category.rb', line 970
def permissions_compatibility_validator
if @permissions && parent_category_id.present?
return if parent_category.category_groups.empty?
parent_permissions = parent_category.category_groups.pluck(:group_id, :permission_type)
child_permissions =
(
if @permissions.empty?
[[Group[:everyone].id, CategoryGroup.permission_types[:full]]]
else
@permissions
end
)
check_permissions_compatibility(parent_permissions, child_permissions)
elsif @permissions && subcategories.present?
return if @permissions.empty?
parent_permissions = @permissions
child_permissions = subcategories_permissions.uniq
check_permissions_compatibility(parent_permissions, child_permissions)
end
end
|
#permissions_params ⇒ Object
629
630
631
632
633
634
635
636
637
638
639
|
# File 'app/models/category.rb', line 629
def permissions_params
hash = {}
category_groups
.includes(:group)
.each do |category_group|
if category_group.group.present?
hash[category_group.group_name] = category_group.permission_type
end
end
hash
end
|
#publish_category ⇒ Object
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
|
# File 'app/models/category.rb', line 504
def publish_category
if self.read_restricted
group_ids = self.groups.pluck(:id)
if group_ids.present?
MessageBus.publish(
"/categories",
{ categories: ActiveModel::ArraySerializer.new([self]).as_json },
group_ids: group_ids,
)
end
else
MessageBus.publish(
"/categories",
{ categories: ActiveModel::ArraySerializer.new([self]).as_json },
)
end
end
|
#publish_category_deletion ⇒ Object
529
530
531
|
# File 'app/models/category.rb', line 529
def publish_category_deletion
MessageBus.publish("/categories", deleted_categories: [self.id])
end
|
#publish_discourse_stylesheet ⇒ Object
904
905
906
|
# File 'app/models/category.rb', line 904
def publish_discourse_stylesheet
Stylesheet::Manager.cache.clear
end
|
#remove_site_settings ⇒ Object
523
524
525
526
527
|
# File 'app/models/category.rb', line 523
def remove_site_settings
SiteSetting.all_settings.each do |s|
SiteSetting.set(s[:setting], "") if s[:type] == "category" && s[:value].to_i == self.id
end
end
|
#rename_category_definition ⇒ Object
If the name changes, try and update the category definition topic too if it’s an exact match
876
877
878
879
880
881
882
|
# File 'app/models/category.rb', line 876
def rename_category_definition
return unless topic.present?
old_name = saved_changes.transform_values(&:first)["name"]
if topic.title == I18n.t("category.topic_prefix", category: old_name)
topic.update_attribute(:title, I18n.t("category.topic_prefix", category: name))
end
end
|
#required_tag_groups=(required_groups) ⇒ Object
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
|
# File 'app/models/category.rb', line 736
def required_tag_groups=(required_groups)
map =
Array(required_groups)
.map
.with_index { |rg, i| [rg["name"], { min_count: rg["min_count"].to_i, order: i }] }
.to_h
tag_groups = TagGroup.where(name: map.keys)
self.category_required_tag_groups =
tag_groups
.map do |tag_group|
attrs = map[tag_group.name]
CategoryRequiredTagGroup.new(tag_group: tag_group, **attrs)
end
.sort_by(&:order)
end
|
#reset_topic_ids_cache ⇒ Object
#secure_group_ids ⇒ Object
795
796
797
|
# File 'app/models/category.rb', line 795
def secure_group_ids
groups.pluck("groups.id") if self.read_restricted?
end
|
#seeded? ⇒ Boolean
849
850
851
852
853
854
855
856
|
# File 'app/models/category.rb', line 849
def seeded?
[
SiteSetting.general_category_id,
SiteSetting.meta_category_id,
SiteSetting.staff_category_id,
SiteSetting.uncategorized_category_id,
].include? id
end
|
#set_permissions(permissions) ⇒ Object
will reset permission on a topic to a particular set.
Available permissions are, :full, :create_post, :readonly
hash can be:
:everyone => :full - everyone has everything :everyone => :readonly, :staff => :full 7 => 1 # you can pass a group_id and permission id
618
619
620
621
622
623
|
# File 'app/models/category.rb', line 618
def set_permissions(permissions)
self.read_restricted, @permissions = Category.resolve_permissions(permissions)
end
|
#slug_for_url ⇒ Object
500
501
502
|
# File 'app/models/category.rb', line 500
def slug_for_url
slug.present? ? self.slug : "#{self.id}-category"
end
|
#slug_path ⇒ Object
1026
1027
1028
1029
1030
1031
1032
1033
1034
|
# File 'app/models/category.rb', line 1026
def slug_path
if self.parent_category_id.present?
slug_path = self.parent_category.slug_path
slug_path.push(self.slug_for_url)
slug_path
else
[self.slug_for_url]
end
end
|
#slug_ref(depth: 1) ⇒ Object
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
|
# File 'app/models/category.rb', line 1036
def slug_ref(depth: 1)
if self.parent_category_id.present?
built_ref = [self.slug]
parent = self.parent_category
while parent.present? && (built_ref.length < depth + 1)
built_ref << parent.slug
parent = parent.parent_category
end
built_ref.reverse.join(Category::SLUG_REF_SEPARATOR)
else
self.slug
end
end
|
#subcategory_list_includes_topics? ⇒ Boolean
959
960
961
|
# File 'app/models/category.rb', line 959
def subcategory_list_includes_topics?
subcategory_list_style.end_with?("with_featured_topics")
end
|
#top_level? ⇒ Boolean
299
300
301
|
# File 'app/models/category.rb', line 299
def top_level?
self.parent_category_id.nil?
end
|
#topic_url ⇒ Object
432
433
434
435
436
437
438
|
# File 'app/models/category.rb', line 432
def topic_url
if has_attribute?("topic_slug")
Topic.relative_url(topic_id, read_attribute(:topic_slug))
else
topic_only_relative_url.try(:relative_url)
end
end
|
#trash_category_definition ⇒ Object
424
425
426
|
# File 'app/models/category.rb', line 424
def trash_category_definition
self.topic&.trash!
end
|
#uncategorized? ⇒ Boolean
845
846
847
|
# File 'app/models/category.rb', line 845
def uncategorized?
id == SiteSetting.uncategorized_category_id
end
|
#update_latest ⇒ Object
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
|
# File 'app/models/category.rb', line 799
def update_latest
latest_post_id =
Post
.order("posts.created_at desc")
.where("NOT hidden")
.joins("join topics on topics.id = topic_id")
.where("topics.category_id = :id", id: self.id)
.limit(1)
.pluck("posts.id")
.first
latest_topic_id =
Topic
.order("topics.created_at desc")
.where("visible")
.where("topics.category_id = :id", id: self.id)
.limit(1)
.pluck("topics.id")
.first
self.update(latest_topic_id: latest_topic_id, latest_post_id: latest_post_id)
end
|
#update_reviewables ⇒ Object
916
917
918
919
920
|
# File 'app/models/category.rb', line 916
def update_reviewables
if should_update_reviewables?
Reviewable.where(category_id: id).update_all(reviewable_by_group_id: reviewable_by_group_id)
end
end
|
#url ⇒ Object
869
870
871
872
873
|
# File 'app/models/category.rb', line 869
def url
@@url_cache.defer_get_set(self.id) do
"#{Discourse.base_path}/c/#{slug_path.join("/")}/#{self.id}"
end
end
|
#visible_group_names(user) ⇒ Object
791
792
793
|
# File 'app/models/category.rb', line 791
def visible_group_names(user)
self.groups.visible_groups(user)
end
|
#visible_posts ⇒ Object
384
385
386
387
388
389
390
391
392
393
|
# File 'app/models/category.rb', line 384
def visible_posts
query =
Post
.joins(:topic)
.where(["topics.category_id = ?", self.id])
.where("topics.visible = true")
.where("posts.deleted_at IS NULL")
.where("posts.user_deleted = false")
self.topic_id ? query.where(["topics.id <> ?", self.topic_id]) : query
end
|