Class: User

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
HasCustomFields, HasDeprecatedColumns, HasDestroyedWebHook, Roleable, Searchable, SecondFactorManager
Defined in:
app/models/user.rb

Defined Under Namespace

Modules: NewTopicDuration Classes: BulkDestroy, Silence, Suspend

Constant Summary collapse

3
MAX_SIMILAR_USERS =
10
MAX_STAFF_DELETE_POST_COUNT =
5
EMAIL =
/([^@]+)@([^\.]+)/
FROM_STAGED =
"from_staged"
MAX_UNREAD_BACKLOG =
400
MAX_UNREAD_NOTIFICATIONS =

PERF: This safeguard is in place to avoid situations where a user with enormous amounts of unread data can issue extremely expensive queries

99
USER_FIELD_PREFIX =
"user_field_"
RECENT_TIME_READ_THRESHOLD =
60.days

Constants included from SecondFactorManager

SecondFactorManager::TOTP_ALLOWED_DRIFT_SECONDS

Constants included from HasCustomFields

HasCustomFields::CUSTOM_FIELDS_MAX_ITEMS, HasCustomFields::DEFAULT_FIELD_DESCRIPTOR

Constants included from Searchable

Searchable::PRIORITIES

Instance Attribute Summary collapse

Attributes included from HasCustomFields

#preloaded_custom_fields

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HasDestroyedWebHook

#enqueue_destroyed_web_hook

Methods included from SecondFactorManager

#authenticate_backup_code, #authenticate_second_factor, #authenticate_security_key, #authenticate_totp, #backup_codes_enabled?, #create_backup_codes, #create_totp, #generate_backup_codes, #get_totp_object, #has_any_second_factor_methods_enabled?, #has_multiple_second_factor_methods?, #hash_backup_code, #invalid_second_factor_authentication_result, #invalid_second_factor_method_result, #invalid_security_key_result, #invalid_totp_or_backup_code_result, #not_enabled_second_factor_method_result, #only_security_keys_enabled?, #only_totp_or_backup_codes_enabled?, #remaining_backup_codes, #require_rotp, #security_keys_enabled?, #totp_enabled?, #totp_or_backup_codes_enabled?, #totp_provisioning_uri, #valid_second_factor_method_for_user?

Methods included from HasCustomFields

#clear_custom_fields, #create_singular, #custom_field_preloaded?, #custom_fields, #custom_fields=, #custom_fields_clean?, #custom_fields_fk, #custom_fields_preloaded?, #on_custom_fields_change, #save_custom_fields, #set_preloaded_custom_fields, #upsert_custom_fields

Methods included from Roleable

#grant_admin!, #grant_moderation!, #regular?, #revoke_admin!, #revoke_moderation!, #save_and_refresh_staff_groups!, #set_default_notification_levels, #set_permission, #staff?, #whisperer?

Instance Attribute Details

#authenticated_with_oauthObject

Information if user was authenticated with OAuth



262
263
264
# File 'app/models/user.rb', line 262

def authenticated_with_oauth
  @authenticated_with_oauth
end

#custom_dataObject

Cache for user custom fields. Currently it is used to display quick search results



259
260
261
# File 'app/models/user.rb', line 259

def custom_data
  @custom_data
end

#import_modeObject

set to true to optimize creation and save for imports



256
257
258
# File 'app/models/user.rb', line 256

def import_mode
  @import_mode
end

#notification_channel_positionObject

This is just used to pass some information into the serializer



253
254
255
# File 'app/models/user.rb', line 253

def notification_channel_position
  @notification_channel_position
end

#send_welcome_messageObject

Whether we need to be sending a system message after creation



250
251
252
# File 'app/models/user.rb', line 250

def send_welcome_message
  @send_welcome_message
end

#skip_email_validationObject

Skip validating email, for example from a particular auth provider plugin



247
248
249
# File 'app/models/user.rb', line 247

def skip_email_validation
  @skip_email_validation
end

Class Method Details

.allowed_user_custom_fields(guardian) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'app/models/user.rb', line 456

def self.allowed_user_custom_fields(guardian)
  fields = []

  fields.push(*DiscoursePluginRegistry.public_user_custom_fields)

  if SiteSetting.public_user_custom_fields.present?
    fields.push(*SiteSetting.public_user_custom_fields.split("|"))
  end

  if guardian.is_staff?
    if SiteSetting.staff_user_custom_fields.present?
      fields.push(*SiteSetting.staff_user_custom_fields.split("|"))
    end

    fields.push(*DiscoursePluginRegistry.staff_user_custom_fields)
  end

  fields.uniq
end

.avatar_template(username, uploaded_avatar_id) ⇒ Object



1174
1175
1176
1177
1178
1179
# File 'app/models/user.rb', line 1174

def self.avatar_template(username, uploaded_avatar_id)
  username ||= ""
  return default_template(username) if !uploaded_avatar_id
  hostname = RailsMultisite::ConnectionManagement.current_hostname
  UserAvatar.local_avatar_template(hostname, username.downcase, uploaded_avatar_id)
end

.color_index(username, length) ⇒ Object



1214
1215
1216
# File 'app/models/user.rb', line 1214

def self.color_index(username, length)
  Digest::MD5.hexdigest(username)[0...15].to_i(16) % length
end

.count_by_first_post(start_date = nil, end_date = nil) ⇒ Object



1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'app/models/user.rb', line 1455

def self.count_by_first_post(start_date = nil, end_date = nil)
  result = joins("INNER JOIN user_stats AS us ON us.user_id = users.id")

  if start_date && end_date
    result = result.group("date(us.first_post_created_at)")
    result =
      result.where(
        "us.first_post_created_at > ? AND us.first_post_created_at < ?",
        start_date,
        end_date,
      )
    result = result.order("date(us.first_post_created_at)")
  end

  result.count
end

.count_by_signup_date(start_date = nil, end_date = nil, group_id = nil) ⇒ Object



1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'app/models/user.rb', line 1438

def self.(start_date = nil, end_date = nil, group_id = nil)
  result = self

  if start_date && end_date
    result = result.group("date(users.created_at)")
    result = result.where("users.created_at >= ? AND users.created_at <= ?", start_date, end_date)
    result = result.order("date(users.created_at)")
  end

  if group_id
    result = result.joins("INNER JOIN group_users ON group_users.user_id = users.id")
    result = result.where("group_users.group_id = ?", group_id)
  end

  result.count
end

.default_template(username) ⇒ Object



1165
1166
1167
1168
1169
1170
1171
1172
# File 'app/models/user.rb', line 1165

def self.default_template(username)
  if SiteSetting.default_avatars.present?
    urls = SiteSetting.default_avatars.split("\n")
    return urls[username_hash(username) % urls.size] if urls.present?
  end

  system_avatar_template(username)
end

.editable_user_custom_fields(by_staff: false) ⇒ Object



448
449
450
451
452
453
454
# File 'app/models/user.rb', line 448

def self.editable_user_custom_fields(by_staff: false)
  fields = []
  fields.push(*DiscoursePluginRegistry.self_editable_user_custom_fields)
  fields.push(*DiscoursePluginRegistry.staff_editable_user_custom_fields) if by_staff

  fields.uniq
end

.email_hash(email) ⇒ Object



635
636
637
# File 'app/models/user.rb', line 635

def self.email_hash(email)
  Digest::MD5.hexdigest(email.strip.downcase)
end

.find_by_email(email, primary: false) ⇒ Object



538
539
540
541
542
543
544
# File 'app/models/user.rb', line 538

def self.find_by_email(email, primary: false)
  if primary
    self.with_primary_email(Email.downcase(email)).first
  else
    self.with_email(Email.downcase(email)).first
  end
end

.find_by_username(username) ⇒ Object



546
547
548
# File 'app/models/user.rb', line 546

def self.find_by_username(username)
  find_by(username_lower: normalize_username(username))
end

.find_by_username_or_email(username_or_email) ⇒ Object



530
531
532
533
534
535
536
# File 'app/models/user.rb', line 530

def self.find_by_username_or_email(username_or_email)
  if username_or_email.include?("@")
    find_by_email(username_or_email)
  else
    find_by_username(username_or_email)
  end
end

.gravatar_template(email) ⇒ Object



1140
1141
1142
# File 'app/models/user.rb', line 1140

def self.gravatar_template(email)
  "//#{SiteSetting.gravatar_base_url}/avatar/#{self.email_hash(email)}.png?s={size}&r=pg&d=identicon"
end

.human_user_id?(user_id) ⇒ Boolean

Returns:

  • (Boolean)


476
477
478
# File 'app/models/user.rb', line 476

def self.human_user_id?(user_id)
  user_id > 0
end

.last_seen_redis_key(user_id, now) ⇒ Object



1103
1104
1105
1106
# File 'app/models/user.rb', line 1103

def self.last_seen_redis_key(user_id, now)
  now_date = now.to_date
  "user:#{user_id}:#{now_date}"
end

.letter_avatar_color(username) ⇒ Object



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
# File 'app/models/user.rb', line 1199

def self.letter_avatar_color(username)
  username ||= ""
  if SiteSetting.restrict_letter_avatar_colors.present?
    hex_length = 6
    colors = SiteSetting.restrict_letter_avatar_colors
    length = colors.count("|") + 1
    num = color_index(username, length)
    index = (num * hex_length) + num
    colors[index, hex_length]
  else
    color = LetterAvatar::COLORS[color_index(username, LetterAvatar::COLORS.length)]
    color.map { |c| c.to_s(16).rjust(2, "0") }.join
  end
end

.max_password_lengthObject



409
410
411
# File 'app/models/user.rb', line 409

def self.max_password_length
  UserPassword::MAX_PASSWORD_LENGTH
end

.max_unread_notificationsObject



741
742
743
# File 'app/models/user.rb', line 741

def self.max_unread_notifications
  @max_unread_notifications ||= MAX_UNREAD_NOTIFICATIONS
end

.max_unread_notifications=(val) ⇒ Object



745
746
747
# File 'app/models/user.rb', line 745

def self.max_unread_notifications=(val)
  @max_unread_notifications = val
end

.new_from_params(params) ⇒ Object



503
504
505
506
507
508
509
510
# File 'app/models/user.rb', line 503

def self.new_from_params(params)
  user = User.new
  user.name = params[:name]
  user.email = params[:email]
  user.password = params[:password]
  user.username = params[:username]
  user
end

.normalize_username(username) ⇒ Object



417
418
419
# File 'app/models/user.rb', line 417

def self.normalize_username(username)
  username.to_s.unicode_normalize.downcase if username.present?
end

.preload_recent_time_read(users) ⇒ Object



1714
1715
1716
1717
1718
1719
1720
1721
1722
# File 'app/models/user.rb', line 1714

def self.preload_recent_time_read(users)
  times =
    UserVisit
      .where(user_id: users.map(&:id))
      .where("visited_at >= ?", RECENT_TIME_READ_THRESHOLD.ago)
      .group(:user_id)
      .sum(:time_read)
  users.each { |u| u.preload_recent_time_read(times[u.id] || 0) }
end

.reserved_username?(username) ⇒ Boolean

Returns:

  • (Boolean)


438
439
440
441
442
443
444
445
446
# File 'app/models/user.rb', line 438

def self.reserved_username?(username)
  username = normalize_username(username)

  return true if SiteSetting.here_mention == username

  SiteSetting.reserved_usernames_map.any? do |reserved|
    username.match?(/\A#{Regexp.escape(reserved.unicode_normalize).gsub('\*', ".*")}\z/)
  end
end

.should_update_last_seen?(user_id, now = Time.zone.now) ⇒ Boolean

Returns:

  • (Boolean)


1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'app/models/user.rb', line 1116

def self.should_update_last_seen?(user_id, now = Time.zone.now)
  return true if SiteSetting.active_user_rate_limit_secs <= 0

  Discourse.redis.set(
    last_seen_redis_key(user_id, now),
    "1",
    nx: true,
    ex: SiteSetting.active_user_rate_limit_secs,
  )
end

.suggest_name(string) ⇒ Object



525
526
527
528
# File 'app/models/user.rb', line 525

def self.suggest_name(string)
  return "" if string.blank?
  (string[/\A[^@]+/].presence || string[/[^@]+\z/]).tr(".", " ").titleize
end

.system_avatar_template(username) ⇒ Object



1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'app/models/user.rb', line 1181

def self.system_avatar_template(username)
  normalized_username = normalize_username(username)

  # TODO it may be worth caching this in a distributed cache, should be benched
  if SiteSetting.external_system_avatars_enabled
    url = SiteSetting.external_system_avatars_url.dup
    url = +"#{Discourse.base_path}#{url}" unless url =~ %r{\Ahttps?://}
    url.gsub! "{color}", letter_avatar_color(normalized_username)
    url.gsub! "{username}", UrlHelper.encode_component(username)
    url.gsub! "{first_letter}",
              UrlHelper.encode_component(normalized_username.grapheme_clusters.first)
    url.gsub! "{hostname}", Discourse.current_hostname
    url
  else
    "#{Discourse.base_path}/letter_avatar/#{normalized_username}/{size}/#{LetterAvatar.version}.png"
  end
end

.update_ip_address!(user_id, new_ip:, old_ip:) ⇒ Object



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'app/models/user.rb', line 1063

def self.update_ip_address!(user_id, new_ip:, old_ip:)
  can_update_ip_address =
    DiscoursePluginRegistry.apply_modifier(:user_can_update_ip_address, user_id: user_id)
  return if !can_update_ip_address

  unless old_ip == new_ip || new_ip.blank?
    DB.exec(<<~SQL, user_id: user_id, ip_address: new_ip)
      UPDATE users
      SET ip_address = :ip_address
      WHERE id = :user_id
    SQL

    if SiteSetting.keep_old_ip_address_count > 0
      DB.exec(<<~SQL, user_id: user_id, ip_address: new_ip, current_timestamp: Time.zone.now)
      INSERT INTO user_ip_address_histories (user_id, ip_address, created_at, updated_at)
      VALUES (:user_id, :ip_address, :current_timestamp, :current_timestamp)
      ON CONFLICT (user_id, ip_address)
      DO
        UPDATE SET updated_at = :current_timestamp
      SQL

      DB.exec(<<~SQL, user_id: user_id, offset: SiteSetting.keep_old_ip_address_count)
      DELETE FROM user_ip_address_histories
      WHERE id IN (
        SELECT
          id
        FROM user_ip_address_histories
        WHERE user_id = :user_id
        ORDER BY updated_at DESC
        OFFSET :offset
      )
      SQL
    end
  end
end

.user_tipsObject



369
370
371
372
373
374
375
376
377
378
# File 'app/models/user.rb', line 369

def self.user_tips
  @user_tips ||=
    Enum.new(
      first_notification: 1,
      topic_timeline: 2,
      post_menu: 3,
      topic_notification_levels: 4,
      suggested_topics: 5,
    )
end

.username_available?(username, email = nil, allow_reserved_username: false) ⇒ Boolean

Returns:

  • (Boolean)


421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'app/models/user.rb', line 421

def self.username_available?(username, email = nil, allow_reserved_username: false)
  lower = normalize_username(username)
  return false if !allow_reserved_username && reserved_username?(lower)
  return true if !username_exists?(lower)

  # staged users can use the same username since they will take over the account
  email.present? &&
    User.joins(:user_emails).exists?(
      staged: true,
      username_lower: lower,
      user_emails: {
        primary: true,
        email: email,
      },
    )
end

.username_hash(username) ⇒ Object



1156
1157
1158
1159
1160
1161
1162
1163
# File 'app/models/user.rb', line 1156

def self.username_hash(username)
  username
    .each_char
    .reduce(0) do |result, char|
      [((result << 5) - result) + char.ord].pack("L").unpack("l").first
    end
    .abs
end

.username_lengthObject



413
414
415
# File 'app/models/user.rb', line 413

def self.username_length
  SiteSetting.min_username_length.to_i..SiteSetting.max_username_length.to_i
end

Instance Method Details

#activateObject



1404
1405
1406
1407
1408
# File 'app/models/user.rb', line 1404

def activate
  email_token = self.email_tokens.create!(email: self.email, scope: EmailToken.scopes[:signup])
  EmailToken.confirm(email_token.token, scope: EmailToken.scopes[:signup])
  reload
end

#active_do_not_disturb_timingsObject



1822
1823
1824
1825
# File 'app/models/user.rb', line 1822

def active_do_not_disturb_timings
  now = Time.zone.now
  do_not_disturb_timings.where("starts_at <= ? AND ends_at > ?", now, now)
end

#admin?Boolean

a touch faster than automatic

Returns:

  • (Boolean)


1387
1388
1389
# File 'app/models/user.rb', line 1387

def admin?
  admin
end

#all_sidebar_sectionsObject



384
385
386
387
388
389
# File 'app/models/user.rb', line 384

def all_sidebar_sections
  sidebar_sections
    .or(SidebarSection.public_sections)
    .includes(:sidebar_urls)
    .order("(section_type IS NOT NULL) DESC, (public IS TRUE) DESC")
end

#all_unread_notifications_countObject



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'app/models/user.rb', line 778

def all_unread_notifications_count
  @all_unread_notifications_count ||=
    begin
      sql = <<~SQL
      SELECT COUNT(*) FROM (
        SELECT 1 FROM
        notifications n
        LEFT JOIN topics t ON t.id = n.topic_id
         WHERE t.deleted_at IS NULL AND
          n.user_id = :user_id AND
          n.id > :seen_notification_id AND
          NOT read
        LIMIT :limit
      ) AS X
    SQL

      DB.query_single(
        sql,
        user_id: id,
        seen_notification_id: seen_notification_id,
        limit: User.max_unread_notifications,
      )[
        0
      ].to_i
    end
end

#allow_live_notifications?Boolean

Returns:

  • (Boolean)


1835
1836
1837
# File 'app/models/user.rb', line 1835

def allow_live_notifications?
  seen_since?(30.days.ago)
end

#anonymous?Boolean

Returns:

  • (Boolean)


1638
1639
1640
# File 'app/models/user.rb', line 1638

def anonymous?
  SiteSetting.allow_anonymous_posting && trust_level >= 1 && !!anonymous_user_master
end

#apply_watched_wordsObject



1585
1586
1587
1588
1589
1590
1591
# File 'app/models/user.rb', line 1585

def apply_watched_words
  validatable_user_fields.each do |id, value|
    field = WordWatcher.censor_text(value)
    field = WordWatcher.replace_text(field)
    set_user_field(id, field)
  end
end

#associated_accountsObject



1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
# File 'app/models/user.rb', line 1556

def associated_accounts
  result = []

  Discourse.authenticators.each do |authenticator|
     = authenticator.description_for_user(self)
    unless .empty?
      result << { name: authenticator.name, description:  }
    end
  end

  result
end

#avatar_templateObject



1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
# File 'app/models/user.rb', line 1222

def avatar_template
   =
    is_system_user? && SiteSetting.logo_small && SiteSetting.use_site_small_logo_as_system_avatar

  if 
    Discourse.store.cdn_url(SiteSetting.logo_small.url)
  else
    self.class.avatar_template(username, uploaded_avatar_id)
  end
end

#avatar_template_urlObject



1152
1153
1154
# File 'app/models/user.rb', line 1152

def avatar_template_url
  UrlHelper.schemaless UrlHelper.absolute avatar_template
end

#badge_countObject



1426
1427
1428
# File 'app/models/user.rb', line 1426

def badge_count
  user_stat&.distinct_badge_count
end

#belonging_to_group_idsObject



556
557
558
# File 'app/models/user.rb', line 556

def belonging_to_group_ids
  @belonging_to_group_ids ||= group_users.pluck(:group_id)
end

#bookmarks_of_type(type) ⇒ Object



496
497
498
# File 'app/models/user.rb', line 496

def bookmarks_of_type(type)
  bookmarks.where(bookmarkable_type: type)
end

#bot?Boolean

Returns:

  • (Boolean)


484
485
486
# File 'app/models/user.rb', line 484

def bot?
  !self.human?
end

#bump_last_seen_notification!Object



813
814
815
816
817
818
819
820
821
822
# File 'app/models/user.rb', line 813

def bump_last_seen_notification!
  query = self.notifications.visible
  query = query.where("notifications.id > ?", seen_notification_id) if seen_notification_id
  if max_notification_id = query.maximum(:id)
    update!(seen_notification_id: max_notification_id)
    true
  else
    false
  end
end

#bump_last_seen_reviewable!Object



824
825
826
827
828
829
830
831
832
833
834
# File 'app/models/user.rb', line 824

def bump_last_seen_reviewable!
  query = Reviewable.unseen_list_for(self, preload: false)

  query = query.where("reviewables.id > ?", last_seen_reviewable_id) if last_seen_reviewable_id
  max_reviewable_id = query.maximum(:id)

  if max_reviewable_id
    update!(last_seen_reviewable_id: max_reviewable_id)
    publish_reviewable_counts
  end
end

#bump_required_fields_versionObject



1906
1907
1908
# File 'app/models/user.rb', line 1906

def bump_required_fields_version
  update(required_fields_version: UserRequiredFieldsVersion.current)
end

#change_trust_level!(level, opts = nil) ⇒ Object



1418
1419
1420
# File 'app/models/user.rb', line 1418

def change_trust_level!(level, opts = nil)
  Promotion.new(self).change_trust_level!(level, opts)
end

#change_username(new_username, actor = nil) ⇒ Object



597
598
599
# File 'app/models/user.rb', line 597

def change_username(new_username, actor = nil)
  UsernameChanger.change(self, new_username, actor)
end

#clear_last_seen_cache!(now = Time.zone.now) ⇒ Object



1112
1113
1114
# File 'app/models/user.rb', line 1112

def clear_last_seen_cache!(now = Time.zone.now)
  Discourse.redis.del(last_seen_redis_key(now))
end

#clear_status!Object



1859
1860
1861
1862
# File 'app/models/user.rb', line 1859

def clear_status!
  user_status.destroy! if user_status
  publish_user_status(nil)
end

#confirm_password?(password) ⇒ Boolean

Returns:

  • (Boolean)


991
992
993
994
# File 'app/models/user.rb', line 991

def confirm_password?(password)
  return false if !user_password
  user_password.confirm_password?(password)
end

#create_or_fetch_secure_identifierObject



1793
1794
1795
1796
1797
1798
# File 'app/models/user.rb', line 1793

def create_or_fetch_secure_identifier
  return secure_identifier if secure_identifier.present?
  new_secure_identifier = SecureRandom.hex(20)
  self.update(secure_identifier: new_secure_identifier)
  new_secure_identifier
end

#create_reviewableObject



1755
1756
1757
1758
1759
1760
# File 'app/models/user.rb', line 1755

def create_reviewable
  return unless SiteSetting.must_approve_users? || SiteSetting.invite_only?
  return if approved?

  Jobs.enqueue(:create_user_reviewable, user_id: self.id)
end

#create_user_profileObject



1625
1626
1627
# File 'app/models/user.rb', line 1625

def 
  UserProfile.create!(user_id: id)
end

#create_visit_record!(date, opts = {}) ⇒ Object



1017
1018
1019
1020
1021
1022
1023
1024
# File 'app/models/user.rb', line 1017

def create_visit_record!(date, opts = {})
  user_stat.update_column(:days_visited, user_stat.days_visited + 1)
  user_visits.create!(
    visited_at: date,
    posts_read: opts[:posts_read] || 0,
    mobile: opts[:mobile] || false,
  )
end

#created_topic_countObject Also known as: topic_count



601
602
603
# File 'app/models/user.rb', line 601

def created_topic_count
  stat.topic_count
end

#deactivate(performed_by) ⇒ Object



1410
1411
1412
1413
1414
1415
1416
# File 'app/models/user.rb', line 1410

def deactivate(performed_by)
  self.update!(active: false)

  if reviewable = ReviewableUser.pending.find_by(target: self)
    reviewable.perform(performed_by, :delete_user)
  end
end

#delete_posts_in_batches(guardian, batch_size = 20) ⇒ Object



1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'app/models/user.rb', line 1298

def delete_posts_in_batches(guardian, batch_size = 20)
  raise Discourse::InvalidAccess unless guardian.can_delete_all_posts? self

  Reviewable.where(created_by_id: id).delete_all

  posts
    .order("post_number desc")
    .limit(batch_size)
    .each { |p| PostDestroyer.new(guardian.user, p).destroy }
end

#display_nameObject



1851
1852
1853
1854
1855
1856
1857
# File 'app/models/user.rb', line 1851

def display_name
  if SiteSetting.prioritize_username_in_ux?
    username
  else
    name.presence || username
  end
end

#do_not_disturb?Boolean

Returns:

  • (Boolean)


1818
1819
1820
# File 'app/models/user.rb', line 1818

def do_not_disturb?
  active_do_not_disturb_timings.exists?
end

#do_not_disturb_untilObject



1827
1828
1829
# File 'app/models/user.rb', line 1827

def do_not_disturb_until
  active_do_not_disturb_timings.maximum(:ends_at)
end

#effective_localeObject



488
489
490
491
492
493
494
# File 'app/models/user.rb', line 488

def effective_locale
  if SiteSetting.allow_user_locale && self.locale.present?
    self.locale
  else
    SiteSetting.default_locale
  end
end

#emailObject



1675
1676
1677
# File 'app/models/user.rb', line 1675

def email
  primary_email&.email
end

#email=(new_email) ⇒ Object

Shortcut to set the primary email of the user. Automatically removes any identical secondary emails.



1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
# File 'app/models/user.rb', line 1681

def email=(new_email)
  if primary_email
    primary_email.email = new_email
  else
    build_primary_email email: new_email, skip_validate_email: !should_validate_email_address?
  end

  if secondary_match =
       user_emails.detect { |ue|
         !ue.primary && Email.downcase(ue.email) == Email.downcase(new_email)
       }
    secondary_match.mark_for_destruction
    primary_email.skip_validate_unique_email = true
  end
end

#email_confirmed?Boolean

Returns:

  • (Boolean)


1399
1400
1401
1402
# File 'app/models/user.rb', line 1399

def email_confirmed?
  email_tokens.where(email: email, confirmed: true).present? || email_tokens.empty? ||
    single_sign_on_record&.external_email&.downcase == email
end

#email_hashObject



639
640
641
# File 'app/models/user.rb', line 639

def email_hash
  User.email_hash(email)
end

#emailsObject



1697
1698
1699
# File 'app/models/user.rb', line 1697

def emails
  self.user_emails.order("user_emails.primary DESC NULLS LAST").pluck(:email)
end

#encoded_username(lower: false) ⇒ Object



1814
1815
1816
# File 'app/models/user.rb', line 1814

def encoded_username(lower: false)
  UrlHelper.encode_component(lower ? username_lower : username)
end

#enqueue_member_welcome_messageObject



573
574
575
576
# File 'app/models/user.rb', line 573

def enqueue_member_welcome_message
  return unless SiteSetting.send_tl1_welcome_message?
  Jobs.enqueue(:send_system_message, user_id: id, message_type: "welcome_tl1_user")
end

#enqueue_staff_welcome_message(role) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'app/models/user.rb', line 583

def enqueue_staff_welcome_message(role)
  return unless staff?
  return if is_singular_admin?

  Jobs.enqueue(
    :send_system_message,
    user_id: id,
    message_type: "welcome_staff",
    message_options: {
      role: role.to_s,
    },
  )
end

#enqueue_tl2_promotion_messageObject



578
579
580
581
# File 'app/models/user.rb', line 578

def enqueue_tl2_promotion_message
  return unless SiteSetting.send_tl2_promotion_message
  Jobs.enqueue(:send_system_message, user_id: id, message_type: "tl2_promotion_message")
end

#enqueue_welcome_message(message_type) ⇒ Object



568
569
570
571
# File 'app/models/user.rb', line 568

def enqueue_welcome_message(message_type)
  return unless SiteSetting.send_welcome_message?
  Jobs.enqueue(:send_system_message, user_id: id, message_type: message_type)
end


1430
1431
1432
1433
1434
1435
1436
# File 'app/models/user.rb', line 1430

def featured_user_badges(limit = nil)
  if limit.nil?
    default_featured_user_badges
  else
    user_badges.grouped_with_count.where("featured_rank <= ?", limit)
  end
end

#find_emailObject



1513
1514
1515
1516
1517
1518
1519
1520
# File 'app/models/user.rb', line 1513

def find_email
  if last_sent_email_address.present? &&
       EmailAddressValidator.valid_value?(last_sent_email_address)
    last_sent_email_address
  else
    email
  end
end

#first_post_created_atObject



1552
1553
1554
# File 'app/models/user.rb', line 1552

def first_post_created_at
  user_stat.try(:first_post_created_at)
end

#flag_linked_posts_as_spamObject

Flag all posts from a user as spam



1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'app/models/user.rb', line 1484

def flag_linked_posts_as_spam
  results = []

  disagreed_flag_post_ids =
    PostAction
      .where(post_action_type_id: post_action_type_view.types[:spam])
      .where.not(disagreed_at: nil)
      .pluck(:post_id)

  topic_links
    .includes(:post)
    .where.not(post_id: disagreed_flag_post_ids)
    .each do |tl|
      message =
        I18n.t(
          "flag_reason.spam_hosts",
          base_path: Discourse.base_path,
          locale: SiteSetting.default_locale,
        )
      results << PostActionCreator.create(Discourse.system_user, tl.post, :spam, message: message)
    end

  results
end

#flags_given_countObject



1259
1260
1261
1262
1263
1264
# File 'app/models/user.rb', line 1259

def flags_given_count
  PostAction.where(
    user_id: id,
    post_action_type_id: post_action_type_view.flag_types_without_additional_message.values,
  ).count
end

#flags_received_countObject



1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'app/models/user.rb', line 1270

def flags_received_count
  posts
    .includes(:post_actions)
    .where(
      "post_actions.post_action_type_id" =>
        post_action_type_view.flag_types_without_additional_message.values,
    )
    .count
end

#from_staged?Boolean

Returns:

  • (Boolean)


1733
1734
1735
# File 'app/models/user.rb', line 1733

def from_staged?
  custom_fields[User::FROM_STAGED]
end

#full_suspend_reasonObject



1337
1338
1339
# File 'app/models/user.rb', line 1337

def full_suspend_reason
  suspend_record.try(:details) if suspended?
end

#full_urlObject



1847
1848
1849
# File 'app/models/user.rb', line 1847

def full_url
  "#{Discourse.base_url}/u/#{encoded_username}"
end

#group_granted_trust_levelObject



560
561
562
# File 'app/models/user.rb', line 560

def group_granted_trust_level
  GroupUser.where(user_id: id).includes(:group).maximum("groups.grant_trust_level")
end

#grouped_unread_notificationsObject



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
# File 'app/models/user.rb', line 698

def grouped_unread_notifications
  results = DB.query(<<~SQL, user_id: self.id, limit: MAX_UNREAD_BACKLOG)
    SELECT X.notification_type AS type, COUNT(*) FROM (
      SELECT n.notification_type
      FROM notifications n
      LEFT JOIN topics t ON t.id = n.topic_id
      WHERE t.deleted_at IS NULL
        AND n.user_id = :user_id
        AND NOT n.read
      LIMIT :limit
    ) AS X
    GROUP BY X.notification_type
  SQL
  results.map! { |row| [row.type, row.count] }
  results.to_h
end

#guardianObject



1391
1392
1393
# File 'app/models/user.rb', line 1391

def guardian
  Guardian.new(self)
end

Returns:

  • (Boolean)


1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
# File 'app/models/user.rb', line 1762

def has_more_posts_than?(max_post_count)
  return true if user_stat && (user_stat.topic_count + user_stat.post_count) > max_post_count
  return true if max_post_count < 0

  DB.query_single(<<~SQL, user_id: self.id).first > max_post_count
    SELECT COUNT(1)
    FROM (
      SELECT 1
      FROM posts p
             JOIN topics t ON (p.topic_id = t.id)
      WHERE p.user_id = :user_id AND
        p.deleted_at IS NULL AND
        t.deleted_at IS NULL AND
        (
          t.archetype <> 'private_message' OR
            EXISTS(
                SELECT 1
                FROM topic_allowed_users a
                WHERE a.topic_id = t.id AND a.user_id > 0 AND a.user_id <> :user_id
              ) OR
            EXISTS(
                SELECT 1
                FROM topic_allowed_groups g
                WHERE g.topic_id = p.topic_id
              )
          )
      LIMIT #{max_post_count + 1}
    ) x
  SQL
end

#has_password?Boolean

Returns:

  • (Boolean)


977
978
979
# File 'app/models/user.rb', line 977

def has_password?
  user_password ? true : false
end

#has_status?Boolean

Returns:

  • (Boolean)


1879
1880
1881
# File 'app/models/user.rb', line 1879

def has_status?
  user_status && !user_status.expired?
end

#has_trust_level?(level) ⇒ Boolean

Use this helper to determine if the user has a particular trust level. Takes into account admin, etc.

Returns:

  • (Boolean)

Raises:



1374
1375
1376
1377
1378
# File 'app/models/user.rb', line 1374

def has_trust_level?(level)
  raise InvalidTrustLevel.new("Invalid trust level #{level}") unless TrustLevel.valid?(level)

  admin? || moderator? || staged? || TrustLevel.compare(trust_level, level)
end

#has_trust_level_or_staff?(level) ⇒ Boolean

Returns:

  • (Boolean)


1380
1381
1382
1383
1384
# File 'app/models/user.rb', line 1380

def has_trust_level_or_staff?(level)
  return admin? if level.to_s == "admin"
  return staff? if level.to_s == "staff"
  has_trust_level?(level.to_i)
end

#has_uploaded_avatarObject



1509
1510
1511
# File 'app/models/user.rb', line 1509

def has_uploaded_avatar
  uploaded_avatar.present?
end

#human?Boolean

Returns:

  • (Boolean)


480
481
482
# File 'app/models/user.rb', line 480

def human?
  User.human_user_id?(self.id)
end

#ignored_user_idsObject



656
657
658
# File 'app/models/user.rb', line 656

def ignored_user_ids
  @ignored_user_ids ||= ignored_users.pluck(:id)
end

#in_any_groups?(group_ids) ⇒ Boolean

Returns:

  • (Boolean)


550
551
552
553
554
# File 'app/models/user.rb', line 550

def in_any_groups?(group_ids)
  group_ids.include?(Group::AUTO_GROUPS[:everyone]) ||
    (is_system_user? && (Group.auto_groups_between(:admins, :trust_level_4) & group_ids).any?) ||
    (group_ids & belonging_to_group_ids).any?
end

#increment_post_edits_countObject



1251
1252
1253
# File 'app/models/user.rb', line 1251

def increment_post_edits_count
  stat.increment!(:post_edits_count)
end

#invited_byObject



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'app/models/user.rb', line 613

def invited_by
  # this is unfortunate, but when an invite is redeemed,
  # any user created by the invite is created *after*
  # the invite's redeemed_at
  invite_redemption_delay = 5.seconds
  used_invite =
    Invite
      .with_deleted
      .joins(:invited_users)
      .where(
        "invited_users.user_id = ? AND invited_users.redeemed_at <= ?",
        self.id,
        self.created_at + invite_redemption_delay,
      )
      .first
  used_invite.try(:invited_by)
end

#is_singular_admin?Boolean

Returns:

  • (Boolean)


1642
1643
1644
# File 'app/models/user.rb', line 1642

def is_singular_admin?
  User.where(admin: true).where.not(id: id).human_users.blank?
end

#is_system_user?Boolean

Returns:

  • (Boolean)


1218
1219
1220
# File 'app/models/user.rb', line 1218

def is_system_user?
  id == Discourse::SYSTEM_USER_ID
end

#last_seen_redis_key(now) ⇒ Object



1108
1109
1110
# File 'app/models/user.rb', line 1108

def last_seen_redis_key(now)
  User.last_seen_redis_key(id, now)
end

#like_countObject

The following count methods are somewhat slow - definitely don’t use them in a loop. They might need to be denormalized



1235
1236
1237
# File 'app/models/user.rb', line 1235

def like_count
  UserAction.where(user_id: id, action_type: UserAction::WAS_LIKED).count
end

#like_given_countObject



1239
1240
1241
# File 'app/models/user.rb', line 1239

def like_given_count
  UserAction.where(user_id: id, action_type: UserAction::LIKE).count
end

#logged_inObject



1651
1652
1653
1654
1655
# File 'app/models/user.rb', line 1651

def logged_in
  DiscourseEvent.trigger(:user_logged_in, self)

  DiscourseEvent.trigger(:user_first_logged_in, self) if !self.seen_before?
end

#logged_outObject



1646
1647
1648
1649
# File 'app/models/user.rb', line 1646

def logged_out
  MessageBus.publish "/logout/#{self.id}", self.id, user_ids: [self.id]
  DiscourseEvent.trigger(:user_logged_out, self)
end

#mature_staged?Boolean

Returns:

  • (Boolean)


1737
1738
1739
# File 'app/models/user.rb', line 1737

def mature_staged?
  from_staged? && self.created_at && self.created_at < 1.day.ago
end

#muted_user_idsObject



660
661
662
# File 'app/models/user.rb', line 660

def muted_user_ids
  @muted_user_ids ||= muted_users.pluck(:id)
end

#needs_required_fields_check?Boolean

Returns:

  • (Boolean)


1902
1903
1904
# File 'app/models/user.rb', line 1902

def needs_required_fields_check?
  (required_fields_version || 0) < UserRequiredFieldsVersion.current
end

#new_new_view_enabled?Boolean

Returns:

  • (Boolean)


1883
1884
1885
# File 'app/models/user.rb', line 1883

def new_new_view_enabled?
  in_any_groups?(SiteSetting.experimental_new_new_view_groups_map)
end

#new_personal_messages_notifications_countObject



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'app/models/user.rb', line 719

def new_personal_messages_notifications_count
  args = {
    user_id: self.id,
    seen_notification_id: self.seen_notification_id,
    private_message: Notification.types[:private_message],
  }

  DB.query_single(<<~SQL, args).first
    SELECT COUNT(*)
    FROM notifications
    WHERE user_id = :user_id
    AND id > :seen_notification_id
    AND NOT read
    AND notification_type = :private_message
  SQL
end

#new_user?Boolean

Returns:

  • (Boolean)


1004
1005
1006
1007
# File 'app/models/user.rb', line 1004

def new_user?
  (created_at >= 24.hours.ago || trust_level == TrustLevel[0]) && trust_level < TrustLevel[2] &&
    !staff?
end

#new_user_posting_on_first_day?Boolean

Returns:

  • (Boolean)


996
997
998
999
1000
1001
1002
# File 'app/models/user.rb', line 996

def new_user_posting_on_first_day?
  !staff? && trust_level < TrustLevel[2] &&
    (
      trust_level == TrustLevel[0] || self.first_post_created_at.nil? ||
        self.first_post_created_at >= 24.hours.ago
    )
end

#next_best_titleObject



1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
# File 'app/models/user.rb', line 1741

def next_best_title
  group_titles_query = groups.where("groups.title <> ''")
  group_titles_query =
    group_titles_query.order("groups.id = #{primary_group_id} DESC") if primary_group_id
  group_titles_query = group_titles_query.order("groups.primary_group DESC").limit(1)

  if next_best_group_title = group_titles_query.pick(:title)
    return next_best_group_title
  end

  next_best_badge_title = badges.where(allow_title: true).pick(:name)
  next_best_badge_title ? Badge.display_name(next_best_badge_title) : nil
end

#number_of_deleted_postsObject



1601
1602
1603
# File 'app/models/user.rb', line 1601

def number_of_deleted_posts
  Post.with_deleted.where(user_id: self.id).where.not(deleted_at: nil).count
end

#number_of_flagged_postsObject



1605
1606
1607
# File 'app/models/user.rb', line 1605

def number_of_flagged_posts
  ReviewableFlaggedPost.where(target_created_by: self.id).count
end

#number_of_flags_givenObject



1613
1614
1615
1616
1617
1618
1619
# File 'app/models/user.rb', line 1613

def number_of_flags_given
  PostAction
    .where(user_id: self.id)
    .where(disagreed_at: nil)
    .where(post_action_type_id: post_action_type_view.notify_flag_type_ids)
    .count
end

#number_of_rejected_postsObject



1609
1610
1611
# File 'app/models/user.rb', line 1609

def number_of_rejected_posts
  ReviewableQueuedPost.rejected.where(target_created_by_id: self.id).count
end

#number_of_suspensionsObject



1621
1622
1623
# File 'app/models/user.rb', line 1621

def number_of_suspensions
  UserHistory.for(self, :suspend_user).count
end

#on_tl3_grace_period?Boolean

Returns:

  • (Boolean)


1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
# File 'app/models/user.rb', line 1526

def on_tl3_grace_period?
  return true if SiteSetting.tl3_promotion_min_duration.to_i.days.ago.year < 2013

  UserHistory
    .for(self, :auto_trust_level_change)
    .where("created_at >= ?", SiteSetting.tl3_promotion_min_duration.to_i.days.ago)
    .where(previous_value: TrustLevel[2].to_s)
    .where(new_value: TrustLevel[3].to_s)
    .exists?
end

#passkey_credential_idsObject



1808
1809
1810
1811
1812
# File 'app/models/user.rb', line 1808

def passkey_credential_ids
  security_keys.where(factor_type: UserSecurityKey.factor_types[:first_factor]).pluck(
    :credential_id,
  )
end

#passwordObject



933
934
935
# File 'app/models/user.rb', line 933

def password
  "" # so that validator doesn't complain that a password attribute doesn't exist
end

#password=(pw) ⇒ Object



921
922
923
924
925
926
927
928
929
930
931
# File 'app/models/user.rb', line 921

def password=(pw)
  # special case for passwordless accounts
  return if pw.blank?

  if user_password
    user_password.password = pw
  else
    build_user_password(password: pw)
  end
  @raw_password = pw # still required to maintain compatibility with usage of password-related User interface
end

#password_algorithmObject



946
947
948
949
950
951
952
953
# File 'app/models/user.rb', line 946

def password_algorithm
  Discourse.deprecate(
    "User#password_algorithm is deprecated, use UserPassword#password_algorithm instead.",
    drop_from: "3.3",
    raise_error: false,
  )
  user_password&.password_algorithm
end

#password_expired?(password) ⇒ Boolean

Returns:

  • (Boolean)


985
986
987
988
989
# File 'app/models/user.rb', line 985

def password_expired?(password)
  return false if user_password.nil? || user_password.password_expired_at.nil?
  user_password.password_hash ==
    hash_password(password, user_password.password_salt, user_password.password_algorithm)
end

#password_hashObject



937
938
939
940
941
942
943
944
# File 'app/models/user.rb', line 937

def password_hash
  Discourse.deprecate(
    "User#password_hash is deprecated, use UserPassword#password_hash instead.",
    drop_from: "3.3",
    raise_error: false,
  )
  user_password&.password_hash
end

#password_required!Object

Indicate that this is NOT a passwordless account for the purposes of validation



965
966
967
# File 'app/models/user.rb', line 965

def password_required!
  @password_required = true
end

#password_required?Boolean

Returns:

  • (Boolean)


969
970
971
# File 'app/models/user.rb', line 969

def password_required?
  !!@password_required
end

#password_validation_required?Boolean

Returns:

  • (Boolean)


973
974
975
# File 'app/models/user.rb', line 973

def password_validation_required?
  password_required? || @raw_password.present?
end

#password_validatorObject



981
982
983
# File 'app/models/user.rb', line 981

def password_validator
  PasswordValidator.new(attributes: :password).validate_each(self, :password, @raw_password)
end

#populated_required_custom_fields?Boolean

Returns:

  • (Boolean)


1895
1896
1897
1898
1899
1900
# File 'app/models/user.rb', line 1895

def populated_required_custom_fields?
  UserField
    .for_all_users
    .pluck(:id)
    .all? { |field_id| custom_fields["#{User::USER_FIELD_PREFIX}#{field_id}"].present? }
end

#post_action_type_viewObject



1255
1256
1257
# File 'app/models/user.rb', line 1255

def post_action_type_view
  @post_action_type_view ||= PostActionTypeView.new
end

#post_countObject



1243
1244
1245
# File 'app/models/user.rb', line 1243

def post_count
  stat.post_count
end

#post_edits_countObject



1247
1248
1249
# File 'app/models/user.rb', line 1247

def post_edits_count
  stat.post_edits_count
end

#posted_too_much_in_topic?(topic_id) ⇒ Boolean

Returns:

  • (Boolean)


1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'app/models/user.rb', line 1284

def posted_too_much_in_topic?(topic_id)
  # Does not apply to staff and non-new members...
  return false if staff? || (trust_level != TrustLevel[0])
  # ... your own topics or in private messages
  topic = Topic.where(id: topic_id).first
  return false if topic.try(:private_message?) || (topic.try(:user_id) == self.id)

  last_action_in_topic = UserAction.last_action_in_topic(id, topic_id)
  since_reply = Post.where(user_id: id, topic_id: topic_id)
  since_reply = since_reply.where("id > ?", last_action_in_topic) if last_action_in_topic

  (since_reply.count >= SiteSetting.newuser_max_replies_per_topic)
end

#preload_recent_time_read(time) ⇒ Object



1724
1725
1726
# File 'app/models/user.rb', line 1724

def preload_recent_time_read(time)
  @recent_time_read = time
end

#private_topics_countObject



1280
1281
1282
# File 'app/models/user.rb', line 1280

def private_topics_count
  topics_allowed.where(archetype: Archetype.private_message).count
end

#publish_do_not_disturb(ends_at: nil) ⇒ Object



899
900
901
# File 'app/models/user.rb', line 899

def publish_do_not_disturb(ends_at: nil)
  MessageBus.publish("/do-not-disturb/#{id}", { ends_at: ends_at&.httpdate }, user_ids: [id])
end

#publish_notifications_stateObject



849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'app/models/user.rb', line 849

def publish_notifications_state
  return if !self.allow_live_notifications?

  # publish last notification json with the message so we can apply an update
  notification = notifications.visible.order("notifications.created_at desc").first
  json = NotificationSerializer.new(notification).as_json if notification

  sql = (<<~SQL)
     SELECT * FROM (
       SELECT n.id, n.read FROM notifications n
       LEFT JOIN topics t ON n.topic_id = t.id
       WHERE
        t.deleted_at IS NULL AND
        n.high_priority AND
        n.user_id = :user_id AND
        NOT read
      ORDER BY n.id DESC
      LIMIT 20
    ) AS x
    UNION ALL
    SELECT * FROM (
     SELECT n.id, n.read FROM notifications n
     LEFT JOIN topics t ON n.topic_id = t.id
     WHERE
      t.deleted_at IS NULL AND
      (n.high_priority = FALSE OR read) AND
      n.user_id = :user_id
     ORDER BY n.id DESC
     LIMIT 20
    ) AS y
  SQL

  recent = DB.query(sql, user_id: id).map! { |r| [r.id, r.read] }

  payload = {
    unread_notifications: unread_notifications,
    unread_high_priority_notifications: unread_high_priority_notifications,
    read_first_notification: read_first_notification?,
    last_notification: json,
    recent: recent,
    seen_notification_id: seen_notification_id,
  }

  payload[:all_unread_notifications_count] = all_unread_notifications_count
  payload[:grouped_unread_notifications] = grouped_unread_notifications
  payload[:new_personal_messages_notifications_count] = new_personal_messages_notifications_count

  MessageBus.publish("/notification/#{id}", payload, user_ids: [id])
end

#publish_reviewable_counts(extra_data = nil) ⇒ Object



836
837
838
839
840
841
842
843
# File 'app/models/user.rb', line 836

def publish_reviewable_counts(extra_data = nil)
  data = {
    reviewable_count: self.reviewable_count,
    unseen_reviewable_count: Reviewable.unseen_reviewable_count(self),
  }
  data.merge!(extra_data) if extra_data.present?
  MessageBus.publish("/reviewable_counts/#{self.id}", data, user_ids: [self.id])
end

#publish_user_status(status) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
# File 'app/models/user.rb', line 903

def publish_user_status(status)
  if status
    payload = {
      description: status.description,
      emoji: status.emoji,
      ends_at: status.ends_at&.iso8601,
    }
  else
    payload = nil
  end

  MessageBus.publish(
    "/user-status",
    { id => payload },
    group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
  )
end

#read_first_notification?Boolean

Returns:

  • (Boolean)


845
846
847
# File 'app/models/user.rb', line 845

def read_first_notification?
  self.seen_notification_id != 0 || user_option.skip_new_user_tips
end

#readable_nameObject



1422
1423
1424
# File 'app/models/user.rb', line 1422

def readable_name
  name.present? && name != username ? "#{name} (#{username})" : username
end

#recent_time_readObject



1728
1729
1730
1731
# File 'app/models/user.rb', line 1728

def recent_time_read
  @recent_time_read ||=
    self.user_visits.where("visited_at >= ?", RECENT_TIME_READ_THRESHOLD.ago).sum(:time_read)
end

#refresh_avatarObject



1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
# File 'app/models/user.rb', line 1537

def refresh_avatar
  return if @import_mode

  avatar = user_avatar || create_user_avatar

  if self.primary_email.present? && SiteSetting.automatically_download_gravatars? &&
       !avatar.last_gravatar_download_attempt
    Jobs.cancel_scheduled_job(:update_gravatar, user_id: self.id, avatar_id: avatar.id)
    Jobs.enqueue_in(1.second, :update_gravatar, user_id: self.id, avatar_id: avatar.id)
  end

  # mark all the user's quoted posts as "needing a rebake"
  Post.rebake_all_quoted_posts(self.id) if saved_change_to_uploaded_avatar_id?
end

#relative_urlObject



1843
1844
1845
# File 'app/models/user.rb', line 1843

def relative_url
  "#{Discourse.base_path}/u/#{encoded_username}"
end

#reloadObject



643
644
645
646
647
648
649
650
651
652
653
654
# File 'app/models/user.rb', line 643

def reload
  @unread_notifications = nil
  @all_unread_notifications_count = nil
  @unread_total_notifications = nil
  @unread_pms = nil
  @unread_bookmarks = nil
  @unread_high_prios = nil
  @ignored_user_ids = nil
  @muted_user_ids = nil
  @belonging_to_group_ids = nil
  super
end

#reviewable_countObject



809
810
811
# File 'app/models/user.rb', line 809

def reviewable_count
  Reviewable.list_for(self, include_claimed_by_others: false).count
end

#saltObject



955
956
957
958
959
960
961
962
# File 'app/models/user.rb', line 955

def salt
  Discourse.deprecate(
    "User#password_salt is deprecated, use UserPassword#password_salt instead.",
    drop_from: "3.3",
    raise_error: false,
  )
  user_password&.password_salt
end

#second_factor_security_key_credential_idsObject



1804
1805
1806
# File 'app/models/user.rb', line 1804

def second_factor_security_key_credential_ids
  second_factor_security_keys.pluck(:credential_id)
end

#second_factor_security_keysObject



1800
1801
1802
# File 'app/models/user.rb', line 1800

def second_factor_security_keys
  security_keys.where(factor_type: UserSecurityKey.factor_types[:second_factor])
end

#secondary_emailsObject



1701
1702
1703
# File 'app/models/user.rb', line 1701

def secondary_emails
  self.user_emails.secondary.pluck(:email)
end

#secure_category_idsObject



1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'app/models/user.rb', line 1472

def secure_category_ids
  cats =
    if self.admin? && !SiteSetting.suppress_secured_categories_from_admin
      Category.unscoped.where(read_restricted: true)
    else
      secure_categories.references(:categories)
    end

  cats.pluck("categories.id").sort
end

#secured_sidebar_category_ids(user_guardian = nil) ⇒ Object



391
392
393
394
395
396
# File 'app/models/user.rb', line 391

def secured_sidebar_category_ids(user_guardian = nil)
  user_guardian ||= guardian

  SidebarSectionLink.where(user_id: self.id, linkable_type: "Category").pluck(:linkable_id) &
    user_guardian.allowed_category_ids
end

#seen_before?Boolean

Returns:

  • (Boolean)


1009
1010
1011
# File 'app/models/user.rb', line 1009

def seen_before?
  last_seen_at.present?
end

#seen_since?(datetime) ⇒ Boolean

Returns:

  • (Boolean)


1013
1014
1015
# File 'app/models/user.rb', line 1013

def seen_since?(datetime)
  seen_before? && last_seen_at >= datetime
end

#set_automatic_groupsObject



1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
# File 'app/models/user.rb', line 1657

def set_automatic_groups
  return if !active || staged || !email_confirmed?

  Group
    .where(automatic: false)
    .where("LENGTH(COALESCE(automatic_membership_email_domains, '')) > 0")
    .each do |group|
      domains = group.automatic_membership_email_domains.gsub(".", '\.')

      if email =~ Regexp.new("@(#{domains})$", true) && !group.users.include?(self)
        group.add(self)
        GroupActionLogger.new(Discourse.system_user, group).log_add_user_to_group(self)
      end
    end

  @belonging_to_group_ids = nil
end

#set_random_avatarObject



1629
1630
1631
1632
1633
1634
1635
1636
# File 'app/models/user.rb', line 1629

def set_random_avatar
  if SiteSetting.selectable_avatars_mode != "disabled"
    if upload = SiteSetting.selectable_avatars.sample
      update_column(:uploaded_avatar_id, upload.id)
      UserAvatar.create!(user_id: id, custom_upload_id: upload.id)
    end
  end
end

#set_status!(description, emoji, ends_at = nil) ⇒ Object



1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
# File 'app/models/user.rb', line 1864

def set_status!(description, emoji, ends_at = nil)
  status = {
    description: description,
    emoji: emoji,
    set_at: Time.zone.now,
    ends_at: ends_at,
    user_id: id,
  }
  validate_status!(status)
  UserStatus.upsert(status)

  reload_user_status
  publish_user_status(user_status)
end

#set_user_field(field_id, value) ⇒ Object



1581
1582
1583
# File 'app/models/user.rb', line 1581

def set_user_field(field_id, value)
  custom_fields["#{USER_FIELD_PREFIX}#{field_id}"] = value
end

#shelved_notificationsObject



1831
1832
1833
# File 'app/models/user.rb', line 1831

def shelved_notifications
  ShelvedNotification.joins(:notification).where("notifications.user_id = ?", self.id)
end

#should_skip_user_fields_validation?Boolean

Returns:

  • (Boolean)


380
381
382
# File 'app/models/user.rb', line 380

def should_skip_user_fields_validation?
  custom_fields_clean? || SiteSetting.disable_watched_word_checking_in_user_fields
end

#should_validate_email_address?Boolean

Returns:

  • (Boolean)


631
632
633
# File 'app/models/user.rb', line 631

def should_validate_email_address?
  !skip_email_validation && !staged?
end

#silence_reasonObject



1321
1322
1323
# File 'app/models/user.rb', line 1321

def silence_reason
  silenced_record.try(:details) if silenced?
end

#silenced?Boolean

Returns:

  • (Boolean)


1313
1314
1315
# File 'app/models/user.rb', line 1313

def silenced?
  !!(silenced_till && silenced_till > Time.zone.now)
end

#silenced_atObject



1325
1326
1327
# File 'app/models/user.rb', line 1325

def silenced_at
  silenced_record.try(:created_at) if silenced?
end

#silenced_forever?Boolean

Returns:

  • (Boolean)


1329
1330
1331
# File 'app/models/user.rb', line 1329

def silenced_forever?
  silenced_till > 100.years.from_now
end

#silenced_recordObject



1317
1318
1319
# File 'app/models/user.rb', line 1317

def silenced_record
  UserHistory.for(self, :silence_user).order("id DESC").first
end

#similar_usersObject



1910
1911
1912
1913
1914
1915
# File 'app/models/user.rb', line 1910

def similar_users
  User
    .real
    .where.not(id: self.id)
    .where(ip_address: self.ip_address, admin: false, moderator: false)
end

#small_avatar_urlObject

Don’t pass this up to the client - it’s meant for server side use This is used in

- self oneboxes in open graph data
- emails


1148
1149
1150
# File 'app/models/user.rb', line 1148

def small_avatar_url
  avatar_template_url.gsub("{size}", "45")
end

#suspend_reasonObject



1341
1342
1343
1344
1345
1346
1347
# File 'app/models/user.rb', line 1341

def suspend_reason
  if details = full_suspend_reason
    return details.split("\n")[0]
  end

  nil
end

#suspend_recordObject



1333
1334
1335
# File 'app/models/user.rb', line 1333

def suspend_record
  UserHistory.for(self, :suspend_user).order("id DESC").first
end

#suspended?Boolean

Returns:

  • (Boolean)


1309
1310
1311
# File 'app/models/user.rb', line 1309

def suspended?
  !!(suspended_till && suspended_till > Time.zone.now)
end

#suspended_forever?Boolean

Returns:

  • (Boolean)


1368
1369
1370
# File 'app/models/user.rb', line 1368

def suspended_forever?
  suspended_till > 100.years.from_now
end

#suspended_messageObject



1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'app/models/user.rb', line 1349

def suspended_message
  return nil unless suspended?

  message = "login.suspended"
  if suspend_reason
    if suspended_forever?
      message = "login.suspended_with_reason_forever"
    else
      message = "login.suspended_with_reason"
    end
  end

  I18n.t(
    message,
    date: I18n.l(suspended_till, format: :date_only),
    reason: Rack::Utils.escape_html(suspend_reason),
  )
end

#sync_notification_channel_positionObject

tricky, we need our bus to be subscribed from the right spot



608
609
610
611
# File 'app/models/user.rb', line 608

def sync_notification_channel_position
  @unread_notifications_by_type = nil
  self.notification_channel_position = MessageBus.last_id("/notification/#{id}")
end

#tl3_requirementsObject



1522
1523
1524
# File 'app/models/user.rb', line 1522

def tl3_requirements
  @lq ||= TrustLevel3Requirements.new(self)
end

#total_unread_notificationsObject



805
806
807
# File 'app/models/user.rb', line 805

def total_unread_notifications
  @unread_total_notifications ||= notifications.where("read = false").count
end

#unconfirmed_emailsObject



1705
1706
1707
1708
1709
1710
# File 'app/models/user.rb', line 1705

def unconfirmed_emails
  self
    .email_change_requests
    .where.not(change_state: EmailChangeRequest.states[:complete])
    .pluck(:new_email)
end

#unread_high_priority_notificationsObject



715
716
717
# File 'app/models/user.rb', line 715

def unread_high_priority_notifications
  @unread_high_prios ||= unread_notifications_of_priority(high_priority: true)
end

#unread_notificationsObject



749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'app/models/user.rb', line 749

def unread_notifications
  @unread_notifications ||=
    begin
      # perf critical, much more efficient than AR
      sql = <<~SQL
      SELECT COUNT(*) FROM (
        SELECT 1 FROM
        notifications n
        LEFT JOIN topics t ON t.id = n.topic_id
         WHERE t.deleted_at IS NULL AND
          n.high_priority = FALSE AND
          n.user_id = :user_id AND
          n.id > :seen_notification_id AND
          NOT read
        LIMIT :limit
      ) AS X
    SQL

      DB.query_single(
        sql,
        user_id: id,
        seen_notification_id: seen_notification_id,
        limit: User.max_unread_notifications,
      )[
        0
      ].to_i
    end
end

#unread_notifications_of_priority(high_priority:) ⇒ Object



681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'app/models/user.rb', line 681

def unread_notifications_of_priority(high_priority:)
  # perf critical, much more efficient than AR
  sql = <<~SQL
      SELECT COUNT(*)
        FROM notifications n
   LEFT JOIN topics t ON t.id = n.topic_id
       WHERE t.deleted_at IS NULL
         AND n.high_priority = :high_priority
         AND n.user_id = :user_id
         AND NOT read
  SQL

  # to avoid coalesce we do to_i
  DB.query_single(sql, user_id: id, high_priority: high_priority)[0].to_i
end

#unread_notifications_of_type(notification_type, since: nil) ⇒ Object



664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'app/models/user.rb', line 664

def unread_notifications_of_type(notification_type, since: nil)
  # perf critical, much more efficient than AR
  sql = <<~SQL
      SELECT COUNT(*)
        FROM notifications n
   LEFT JOIN topics t ON t.id = n.topic_id
       WHERE t.deleted_at IS NULL
         AND n.notification_type = :notification_type
         AND n.user_id = :user_id
         AND NOT read
         #{since ? "AND n.created_at > :since" : ""}
  SQL

  # to avoid coalesce we do to_i
  DB.query_single(sql, user_id: id, notification_type: notification_type, since: since)[0].to_i
end

#unstage!Object



512
513
514
515
516
517
518
519
520
521
522
523
# File 'app/models/user.rb', line 512

def unstage!
  if self.staged
    ActiveRecord::Base.transaction do
      self.staged = false
      self.custom_fields[FROM_STAGED] = true
      self.notifications.destroy_all
      save!
    end

    DiscourseEvent.trigger(:user_unstaged, self)
  end
end

#update_ip_address!(new_ip_address) ⇒ Object



1099
1100
1101
# File 'app/models/user.rb', line 1099

def update_ip_address!(new_ip_address)
  User.update_ip_address!(id, new_ip: new_ip_address, old_ip: ip_address)
end

#update_last_seen!(now = Time.zone.now, force: false) ⇒ Object



1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
# File 'app/models/user.rb', line 1127

def update_last_seen!(now = Time.zone.now, force: false)
  if !force
    return if !User.should_update_last_seen?(self.id, now)
  end

  update_previous_visit(now)
  # using update_column to avoid the AR transaction
  update_column(:last_seen_at, now)
  update_column(:first_seen_at, now) unless self.first_seen_at

  DiscourseEvent.trigger(:user_seen, self)
end

#update_posts_read!(num_posts, opts = {}) ⇒ Object



1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'app/models/user.rb', line 1041

def update_posts_read!(num_posts, opts = {})
  now = opts[:at] || Time.zone.now
  _retry = opts[:retry] || false

  if user_visit = visit_record_for(now.to_date)
    user_visit.posts_read += num_posts
    user_visit.mobile = true if opts[:mobile]
    user_visit.save
    user_visit
  else
    begin
      create_visit_record!(now.to_date, posts_read: num_posts, mobile: opts.fetch(:mobile, false))
    rescue ActiveRecord::RecordNotUnique
      if !_retry
        update_posts_read!(num_posts, opts.merge(retry: true))
      else
        raise
      end
    end
  end
end

#update_timezone_if_missing(timezone) ⇒ Object



1034
1035
1036
1037
1038
1039
# File 'app/models/user.rb', line 1034

def update_timezone_if_missing(timezone)
  return if timezone.blank? || !TimezoneValidator.valid?(timezone)

  # we only want to update the user's timezone if they have not set it themselves
  UserOption.where(user_id: self.id, timezone: nil).update_all(timezone: timezone)
end

#update_visit_record!(date) ⇒ Object



1030
1031
1032
# File 'app/models/user.rb', line 1030

def update_visit_record!(date)
  create_visit_record!(date) unless visit_record_for(date)
end

#user_fields(field_ids = nil) ⇒ Object



1571
1572
1573
1574
1575
# File 'app/models/user.rb', line 1571

def user_fields(field_ids = nil)
  field_ids = (@all_user_field_ids ||= UserField.pluck(:id)) if field_ids.nil?

  field_ids.map { |fid| [fid.to_s, custom_fields["#{USER_FIELD_PREFIX}#{fid}"]] }.to_h
end

#username_equals_to?(another_username) ⇒ Boolean

Returns:

  • (Boolean)


1839
1840
1841
# File 'app/models/user.rb', line 1839

def username_equals_to?(another_username)
  username_lower == User.normalize_username(another_username)
end

#username_format_validatorObject



1395
1396
1397
# File 'app/models/user.rb', line 1395

def username_format_validator
  UsernameValidator.perform_validation(self, "username")
end

#validatable_user_fieldsObject



1593
1594
1595
1596
1597
1598
1599
# File 'app/models/user.rb', line 1593

def validatable_user_fields
  # ignore multiselect fields since they are admin-set and thus not user generated content
  @public_user_field_ids ||=
    UserField.public_fields.where.not(field_type: "multiselect").pluck(:id)

  user_fields(@public_user_field_ids)
end

#validatable_user_fields_valuesObject



1577
1578
1579
# File 'app/models/user.rb', line 1577

def validatable_user_fields_values
  validatable_user_fields.values.join(" ")
end

#visible_groupsObject



564
565
566
# File 'app/models/user.rb', line 564

def visible_groups
  groups.visible_groups(self)
end

#visible_sidebar_tags(user_guardian = nil) ⇒ Object



398
399
400
401
402
403
404
405
406
407
# File 'app/models/user.rb', line 398

def visible_sidebar_tags(user_guardian = nil)
  user_guardian ||= guardian

  DiscourseTagging.filter_visible(
    Tag.where(
      id: SidebarSectionLink.where(user_id: self.id, linkable_type: "Tag").select(:linkable_id),
    ),
    user_guardian,
  )
end

#visit_record_for(date) ⇒ Object



1026
1027
1028
# File 'app/models/user.rb', line 1026

def visit_record_for(date)
  user_visits.find_by(visited_at: date)
end

#warnings_received_countObject



1266
1267
1268
# File 'app/models/user.rb', line 1266

def warnings_received_count
  user_warnings.count
end

#watched_precedence_over_mutedObject



1887
1888
1889
1890
1891
1892
1893
# File 'app/models/user.rb', line 1887

def watched_precedence_over_muted
  if user_option.watched_precedence_over_muted.nil?
    SiteSetting.watched_precedence_over_muted
  else
    user_option.watched_precedence_over_muted
  end
end