Class: CategoriesController

Inherits:
ApplicationController show all
Includes:
TopicQueryParams
Defined in:
app/controllers/categories_controller.rb

Constant Summary collapse

SYMMETRICAL_CATEGORIES_TO_TOPICS_FACTOR =
1.5
MIN_CATEGORIES_TOPICS =
5
MAX_CATEGORIES_LIMIT =
25

Constants inherited from ApplicationController

ApplicationController::CHALLENGE_KEY, ApplicationController::HONEYPOT_KEY, ApplicationController::LEGACY_NO_THEMES, ApplicationController::LEGACY_NO_UNOFFICIAL_PLUGINS, ApplicationController::NO_PLUGINS, ApplicationController::NO_THEMES, ApplicationController::NO_UNOFFICIAL_PLUGINS, ApplicationController::SAFE_MODE

Constants included from CanonicalURL::ControllerExtensions

CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS

Instance Attribute Summary

Attributes inherited from ApplicationController

#theme_id

Instance Method Summary collapse

Methods included from TopicQueryParams

#build_topic_list_options

Methods inherited from ApplicationController

#application_layout, #can_cache_content?, #clear_notifications, #conditionally_allow_site_embedding, #current_homepage, #discourse_expires_in, #dont_cache_page, #ember_cli_required?, #fetch_user_from_params, #guardian, #handle_permalink, #handle_theme, #handle_unverified_request, #has_escaped_fragment?, #immutable_for, #login_method, #no_cookies, #perform_refresh_session, #post_ids_including_replies, #preload_json, #rate_limit_second_factor!, #redirect_with_client_support, #render_json_dump, #render_serialized, requires_plugin, #rescue_discourse_actions, #resolve_safe_mode, #secure_session, #serialize_data, #set_current_user_for_logs, #set_layout, #set_mobile_view, #set_mp_snapshot_fields, #show_browser_update?, #store_preloaded, #use_crawler_layout?, #with_resolved_locale

Methods included from VaryHeader

#ensure_vary_header

Methods included from ThemeResolver

resolve_theme_id

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, #get_or_check_readonly_mode, #get_or_check_staff_writes_only_mode, included, #staff_writes_only_mode?

Methods included from Hijack

#hijack

Methods included from GlobalPath

#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path

Methods included from JsonError

#create_errors_json

Methods included from CanonicalURL::ControllerExtensions

#canonical_url, #default_canonical, included

Methods included from CurrentUser

#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session

Instance Method Details

#categories_and_hotObject



85
86
87
# File 'app/controllers/categories_controller.rb', line 85

def categories_and_hot
  categories_and_topics(:hot)
end

#categories_and_latestObject



77
78
79
# File 'app/controllers/categories_controller.rb', line 77

def categories_and_latest
  categories_and_topics(:latest)
end

#categories_and_topObject



81
82
83
# File 'app/controllers/categories_controller.rb', line 81

def categories_and_top
  categories_and_topics(:top)
end

#createObject



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/controllers/categories_controller.rb', line 134

def create
  guardian.ensure_can_create!(Category)
  position = category_params.delete(:position)

  @category =
    begin
      Category.new(required_create_params.merge(user: current_user))
    rescue ArgumentError => e
      return render json: { errors: [e.message] }, status: 422
    end

  if @category.save
    @category.move_to(position.to_i) if position

    Scheduler::Defer.later "Log staff action create category" do
      @staff_action_logger.log_category_creation(@category)
    end

    render_serialized(@category, CategorySerializer)
  else
    render_json_error(@category)
  end
end

#destroyObject



233
234
235
236
237
238
239
240
241
242
# File 'app/controllers/categories_controller.rb', line 233

def destroy
  guardian.ensure_can_delete!(@category)
  @category.destroy

  Scheduler::Defer.later "Log staff action delete category" do
    @staff_action_logger.log_category_deletion(@category)
  end

  render json: success_json
end

#findObject



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'app/controllers/categories_controller.rb', line 285

def find
  categories = []
  serializer = params[:include_permissions] ? CategorySerializer : SiteCategorySerializer

  if params[:ids].present?
    categories = Category.secured(guardian).where(id: params[:ids])
  elsif params[:slug_path].present?
    category = Category.find_by_slug_path(params[:slug_path].split("/"))
    raise Discourse::NotFound if category.blank?
    guardian.ensure_can_see!(category)

    ancestors = Category.secured(guardian).with_ancestors(category.id).where.not(id: category.id)
    categories = [*ancestors, category]
  elsif params[:slug_path_with_id].present?
    category = Category.find_by_slug_path_with_id(params[:slug_path_with_id])
    raise Discourse::NotFound if category.blank?
    guardian.ensure_can_see!(category)

    ancestors = Category.secured(guardian).with_ancestors(category.id).where.not(id: category.id)
    categories = [*ancestors, category]
  end

  raise Discourse::NotFound if categories.blank?

  Category.preload_user_fields!(guardian, categories)

  render_serialized(categories, serializer, root: :categories, scope: guardian)
end

#find_by_slugObject



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'app/controllers/categories_controller.rb', line 244

def find_by_slug
  params.require(:category_slug)
  @category =
    Category.includes(:category_setting).find_by_slug_path(params[:category_slug].split("/"))

  raise Discourse::NotFound if @category.blank?

  if !guardian.can_see?(@category)
    if SiteSetting.detailed_404 && group = @category.access_category_via_group
      raise Discourse::InvalidAccess.new(
              "not in group",
              @category,
              custom_message: "not_in_group.title_category",
              custom_message_params: {
                group: group.name,
              },
              group: group,
            )
    else
      raise Discourse::NotFound
    end
  end

  @category.permission = CategoryGroup.permission_types[:full] if Category
    .topic_create_allowed(guardian)
    .where(id: @category.id)
    .exists?
  render_serialized(@category, CategorySerializer)
end

#hierarchical_searchObject



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
# File 'app/controllers/categories_controller.rb', line 314

def hierarchical_search
  term = params[:term].to_s.strip
  page = [1, params[:page].to_i].max
  offset = params[:offset].to_i
  parent_category_id = params[:parent_category_id].to_i if params[:parent_category_id].present?
  only =
    if params[:only].present?
      Category.secured(guardian).where(id: params[:only].to_a.map(&:to_i))
    else
      Category.secured(guardian)
    end
  except_ids = params[:except].to_a.map(&:to_i)
  include_uncategorized =
    (
      if params[:include_uncategorized].present?
        ActiveModel::Type::Boolean.new.cast(params[:include_uncategorized])
      else
        true
      end
    )

  except_ids << SiteSetting.uncategorized_category_id unless include_uncategorized

  except = Category.where(id: except_ids) if except_ids.present?

  limit =
    (
      if params[:limit].present?
        params[:limit].to_i.clamp(1, MAX_CATEGORIES_LIMIT)
      else
        MAX_CATEGORIES_LIMIT
      end
    )

  categories =
    Category
      .secured(guardian)
      .limited_categories_matching(only, except, parent_category_id, term)
      .preload(
        :uploaded_logo,
        :uploaded_logo_dark,
        :uploaded_background,
        :uploaded_background_dark,
        :tags,
        :tag_groups,
        :form_templates,
        category_required_tag_groups: :tag_group,
      )
      .joins("LEFT JOIN topics t on t.id = categories.topic_id")
      .select("categories.*, t.slug topic_slug")
      .limit(limit)
      .offset((page - 1) * limit + offset)
      .to_a

  if Site.preloaded_category_custom_fields.present?
    Category.preload_custom_fields(categories, Site.preloaded_category_custom_fields)
  end

  Category.preload_user_fields!(guardian, categories)

  response = { categories: serialize_data(categories, SiteCategorySerializer, scope: guardian) }

  render_json_dump(response)
end

#indexObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'app/controllers/categories_controller.rb', line 40

def index
  discourse_expires_in 1.minute

  @category_list = fetch_category_list

  respond_to do |format|
    format.html do
      @title =
        if current_homepage == "categories" && SiteSetting.short_site_description.present?
          "#{SiteSetting.title} - #{SiteSetting.short_site_description}"
        elsif current_homepage != "categories"
          "#{I18n.t("js.filters.categories.title")} - #{SiteSetting.title}"
        end

      @description = SiteSetting.site_description

      store_preloaded(
        @category_list.preload_key,
        MultiJson.dump(CategoryListSerializer.new(@category_list, scope: guardian)),
      )

      @topic_list = fetch_topic_list

      if @topic_list.present? && @topic_list.topics.present?
        store_preloaded(
          @topic_list.preload_key,
          MultiJson.dump(TopicListSerializer.new(@topic_list, scope: guardian)),
        )
      end

      render
    end

    format.json { render_serialized(@category_list, CategoryListSerializer) }
  end
end

#moveObject



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'app/controllers/categories_controller.rb', line 89

def move
  guardian.ensure_can_create_category!

  params.require("category_id")
  params.require("position")

  if category = Category.find(params["category_id"])
    category.move_to(params["position"].to_i)
    render json: success_json
  else
    render status: 500, json: failed_json
  end
end

#redirectObject



35
36
37
38
# File 'app/controllers/categories_controller.rb', line 35

def redirect
  return if handle_permalink("/category/#{params[:path]}")
  redirect_to path("/c/#{params[:path]}")
end

#reorderObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'app/controllers/categories_controller.rb', line 103

def reorder
  guardian.ensure_can_create_category!

  params.require(:mapping)
  change_requests = MultiJson.load(params[:mapping])
  by_category = Hash[change_requests.map { |cat, pos| [Category.find(cat.to_i), pos] }]

  unless guardian.is_admin?
    unless by_category.keys.all? { |c| guardian.can_see_category? c }
      raise Discourse::InvalidAccess
    end
  end

  by_category.each do |cat, pos|
    cat.position = pos
    cat.save! if cat.will_save_change_to_position?
  end

  render json: success_json
end

#searchObject



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'app/controllers/categories_controller.rb', line 379

def search
  term = params[:term].to_s.strip
  parent_category_id = params[:parent_category_id].to_i if params[:parent_category_id].present?
  include_uncategorized =
    (
      if params[:include_uncategorized].present?
        ActiveModel::Type::Boolean.new.cast(params[:include_uncategorized])
      else
        true
      end
    )
  if params[:select_category_ids].is_a?(Array)
    select_category_ids = params[:select_category_ids].map(&:presence)
  end
  if params[:reject_category_ids].is_a?(Array)
    reject_category_ids = params[:reject_category_ids].map(&:presence)
  end
  include_subcategories =
    if params[:include_subcategories].present?
      ActiveModel::Type::Boolean.new.cast(params[:include_subcategories])
    else
      true
    end
  include_ancestors =
    if params[:include_ancestors].present?
      ActiveModel::Type::Boolean.new.cast(params[:include_ancestors])
    else
      false
    end
  prioritized_category_id = params[:prioritized_category_id].to_i if params[
    :prioritized_category_id
  ].present?
  limit =
    (
      if params[:limit].present?
        params[:limit].to_i.clamp(1, MAX_CATEGORIES_LIMIT)
      else
        MAX_CATEGORIES_LIMIT
      end
    )
  page = [1, params[:page].to_i].max

  categories = Category.secured(guardian)

  if term.present? && words = term.split
    words.each { |word| categories = categories.where("name ILIKE ?", "%#{word}%") }
  end

  categories =
    (
      if parent_category_id != -1
        categories.where(parent_category_id: parent_category_id)
      else
        categories.where(parent_category_id: nil)
      end
    ) if parent_category_id.present?

  categories =
    categories.where.not(id: SiteSetting.uncategorized_category_id) if !include_uncategorized

  categories = categories.where(id: select_category_ids) if select_category_ids

  categories = categories.where.not(id: reject_category_ids) if reject_category_ids

  categories = categories.where(parent_category_id: nil) if !include_subcategories

  categories_count = categories.count

  categories =
    categories
      .includes(
        :uploaded_logo,
        :uploaded_logo_dark,
        :uploaded_background,
        :uploaded_background_dark,
        :tags,
        :tag_groups,
        :form_templates,
        category_required_tag_groups: :tag_group,
      )
      .joins("LEFT JOIN topics t on t.id = categories.topic_id")
      .select("categories.*, t.slug topic_slug")
      .order(
        "starts_with(lower(categories.name), #{ActiveRecord::Base.connection.quote(term)}) DESC",
        "categories.parent_category_id IS NULL DESC",
        "categories.id IS NOT DISTINCT FROM #{ActiveRecord::Base.connection.quote(prioritized_category_id)} DESC",
        "categories.parent_category_id IS NOT DISTINCT FROM #{ActiveRecord::Base.connection.quote(prioritized_category_id)} DESC",
        "categories.id ASC",
      )
      .limit(limit)
      .offset((page - 1) * limit)

  if Site.preloaded_category_custom_fields.present?
    Category.preload_custom_fields(categories, Site.preloaded_category_custom_fields)
  end

  Category.preload_user_fields!(guardian, categories)

  response = {
    categories_count: categories_count,
    categories: serialize_data(categories, SiteCategorySerializer, scope: guardian),
  }

  if include_ancestors
    ancestors = Category.secured(guardian).ancestors_of(categories.map(&:id))
    Category.preload_user_fields!(guardian, ancestors)
    response[:ancestors] = serialize_data(ancestors, SiteCategorySerializer, scope: guardian)
  end

  render_json_dump(response)
end

#set_notificationsObject



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'app/controllers/categories_controller.rb', line 219

def set_notifications
  category_id = params[:category_id].to_i
  notification_level = params[:notification_level].to_i

  CategoryUser.set_notification_level_for_category(current_user, notification_level, category_id)
  render json:
           success_json.merge(
             {
               indirectly_muted_category_ids:
                 CategoryUser.indirectly_muted_category_ids(current_user),
             },
           )
end

#showObject



124
125
126
127
128
129
130
131
132
# File 'app/controllers/categories_controller.rb', line 124

def show
  guardian.ensure_can_see!(@category)

  if Category.topic_create_allowed(guardian).where(id: @category.id).exists?
    @category.permission = CategoryGroup.permission_types[:full]
  end

  render_serialized(@category, CategorySerializer)
end

#updateObject



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'app/controllers/categories_controller.rb', line 158

def update
  guardian.ensure_can_edit!(@category)

  json_result(@category, serializer: CategorySerializer) do |cat|
    old_category_params = category_params.dup

    cat.move_to(category_params[:position].to_i) if category_params[:position]
    category_params.delete(:position)

    old_custom_fields = cat.custom_fields.dup
    if category_params[:custom_fields]
      category_params[:custom_fields].each do |key, value|
        if value.present?
          cat.custom_fields[key] = value
        else
          cat.custom_fields.delete(key)
        end
      end
    end
    category_params.delete(:custom_fields)

    # properly null the value so the database constraint doesn't catch us
    category_params[:email_in] = nil if category_params[:email_in].blank?
    category_params[:minimum_required_tags] = 0 if category_params[:minimum_required_tags].blank?

    old_permissions = cat.permissions_params
    old_permissions = { "everyone" => 1 } if old_permissions.empty?

    if result = cat.update(category_params)
      Scheduler::Defer.later "Log staff action change category settings" do
        @staff_action_logger.log_category_settings_change(
          @category,
          old_category_params,
          old_permissions: old_permissions,
          old_custom_fields: old_custom_fields,
        )
      end
    end

    DiscourseEvent.trigger(:category_updated, cat) if result

    result
  end
end

#update_slugObject



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/controllers/categories_controller.rb', line 203

def update_slug
  @category = Category.find(params[:category_id].to_i)
  guardian.ensure_can_edit!(@category)

  custom_slug = params[:slug].to_s

  if custom_slug.blank?
    error = @category.errors.full_message(:slug, I18n.t("errors.messages.blank"))
    render_json_error(error)
  elsif @category.update(slug: custom_slug)
    render json: success_json
  else
    render_json_error(@category)
  end
end

#visible_groupsObject



274
275
276
277
278
279
280
281
282
283
# File 'app/controllers/categories_controller.rb', line 274

def visible_groups
  @guardian.ensure_can_see!(@category)

  groups =
    if !@category.groups.exists?(id: Group::AUTO_GROUPS[:everyone])
      @category.groups.merge(Group.visible_groups(current_user)).pluck("name")
    end

  render json: success_json.merge(groups: groups || [])
end