cirandas.net

ref: master

app/models/profile.rb


   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  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
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 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
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 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
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 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
 313
 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
 378
 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
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 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
 560
 561
 562
 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
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 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
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 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
 777
 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
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 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
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 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
 996
 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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# A Profile is the representation and web-presence of an individual or an
# organization. Every Profile is attached to its Environment of origin,
# which by default is the one returned by Environment:default.
class Profile < ApplicationRecord

  attr_accessible :name, :identifier, :public_profile, :nickname,
    :custom_footer, :custom_header, :address, :zip_code, :contact_phone,
    :image_builder, :top_image_builder, :description, :closed, :template_id, :environment, :lat,
    :lng, :is_template, :fields_privacy, :preferred_domain_id, :category_ids,
    :country, :city, :state, :national_region_code, :email, :contact_email,
    :redirect_l10n, :notification_time, :redirection_after_login,
    :custom_url_redirection, :layout_template, :email_suggestions,
    :allow_members_to_invite, :invite_friends_only, :secret,
    :profile_admin_mail_notification, :allow_followers, :wall_access,
    :profile_kinds, :tag_list, :boxes_attributes

  attr_accessor :old_region_id

  # use for internationalizable human type names in search facets
  # reimplement on subclasses
  def self.type_name
    _('Profile')
  end

  SEARCHABLE_FIELDS = {
    :name => {:label => _('Name'), :weight => 10},
    :identifier => {:label => _('Username'), :weight => 5},
    :nickname => {:label => _('Nickname'), :weight => 2},
  }

  SEARCH_FILTERS = {
    :order => %w[more_recent],
    :display => %w[compact]
  }

  NUMBER_OF_BOXES = 4

  def self.default_search_display
    'compact'
  end

  module Roles
    def self.admin(env_id)
      find_role('admin', env_id)
    end
    def self.member(env_id)
      find_role('member', env_id)
    end
    def self.moderator(env_id)
      find_role('moderator', env_id)
    end
    def self.owner(env_id)
      find_role('owner', env_id)
    end
    def self.editor(env_id)
      find_role('editor', env_id)
    end
    def self.organization_member_roles(env_id)
      all_roles(env_id).select{ |r| r.key.match(/^profile_/) unless r.key.blank? || !r.profile_id.nil?}
    end
    def self.organization_custom_roles(env_id, profile_id)
      all_roles(env_id).where('profile_id = ?', profile_id)
    end
    def self.organization_roles(env_id, profile_id)
      all_roles(env_id).where("profile_id = ?  or key like 'profile_%'", profile_id)
    end
    def self.all_roles(env_id)
      Role.where(environment_id: env_id)
    end
    def self.method_missing(m, *args, &block)
      role = find_role(m, args[0])
      return role unless role.nil?
      super
    end
    private
    def self.find_role(name, env_id)
      ::Role.find_by key: "profile_#{name}", environment_id: env_id
    end
  end

  PERMISSIONS['Profile'] = {
    'edit_profile'         => N_('Edit profile'),
    'destroy_profile'      => N_('Destroy profile'),
    'manage_memberships'   => N_('Manage memberships'),
    'post_content'         => N_('Manage content'), # changed only presentation name to keep already given permissions
    'edit_profile_design'  => N_('Edit profile design'),
    'manage_products'      => N_('Manage products'),
    'manage_friends'       => N_('Manage friends'),
    'validate_enterprise'  => N_('Validate enterprise'),
    'perform_task'         => N_('Perform task'),
    'view_tasks'           => N_('View tasks'),
    'moderate_comments'    => N_('Moderate comments'),
    'edit_appearance'      => N_('Edit appearance'),
    'view_private_content' => N_('View private content'),
    'publish_content'      => N_('Publish content'),
    'invite_members'       => N_('Invite members'),
    'send_mail_to_members' => N_('Send e-Mail to members'),
    'manage_custom_roles'  => N_('Manage custom roles'),
    'manage_email_templates' => N_('Manage Email Templates'),
  }

  acts_as_accessible

  include Customizable
  acts_as_customizable

  include Noosfero::Plugin::HotSpot

  scope :memberships_of, -> person {
    distinct.select('profiles.*').
    joins(:role_assignments).
    where('role_assignments.accessor_type = ? AND role_assignments.accessor_id = ?', person.class.base_class.name, person.id)
  }
  #FIXME: these will work only if the subclass is already loaded
  scope :enterprises, -> {
    where((Enterprise.send(:subclasses).map(&:name) << 'Enterprise').map { |klass| "profiles.type = '#{klass}'"}.join(" OR "))
  }
  scope :communities, -> {
    where((Community.send(:subclasses).map(&:name) << 'Community').map { |klass| "profiles.type = '#{klass}'"}.join(" OR "))
  }
  scope :templates, -> template_id = nil {
    s = where is_template: true
    s = s.where id: template_id if template_id
    s
  }

  scope :with_templates, -> templates {
    where template_id: templates
  }
  scope :no_templates, -> { where is_template: false }

  scope :recent, -> limit=nil { order('id DESC').limit(limit) }


  # Returns a scoped object to select profiles in a given location or in a radius
  # distance from the given location center.
  # The parameter can be the `request.params` with the keys:
  # * `country`: Country code string.
  # * `state`: Second-level administrative country subdivisions.
  # * `city`: City full name for center definition, or as set by users.
  # * `lat`: The latitude to define the center of georef search.
  # * `lng`: The longitude to define the center of georef search.
  # * `distance`: Define the search radius in kilometers.
  # NOTE: This method may return an exception object, to inform filter error.
  # When chaining scopes, is hardly recommended you to add this as the last one,
  # if you can't be sure about the provided parameters.
  def self.by_location(params)
    params = params.with_indifferent_access
    if params[:distance].blank?
      where_code = []
      [ :city, :state, :country ].each do |place|
        unless params[place].blank?
          # ... So we must to find on this named location
          # TODO: convert location attrs to a table collumn
          where_code << "(profiles.data like '%#{place}: #{params[place]}%')"
        end
      end
      self.where where_code.join(' AND ')
    else # Filter in a georef circle
      unless params[:lat].blank? && params[:lng].blank?
        lat, lng = [ params[:lat].to_f, params[:lng].to_f ]
      end
      if !lat
        location = [ params[:city], params[:state], params[:country] ].compact.join(', ')
        if location.blank?
          return Exception.new (
            _('You must to provide `lat` and `lng`, or `city` and `country` to define the center of the search circle, defined by `distance`.')
          )
        end
        lat, lng = Noosfero::GeoRef.location_to_georef location
      end
      dist = params[:distance].to_f
      self.where "#{Noosfero::GeoRef.sql_dist lat, lng} <= #{dist}"
    end
  end

  include TimeScopes

  def members(by_field = '')
    scopes = plugins.dispatch_scopes(:organization_members, self)
    scopes << Person.members_of(self,by_field)
    return scopes.first if scopes.size == 1
    ScopeTool.union *scopes
  end

  def members_by(field,value = nil)
    if value and !value.blank?
      members_like(field,value).order('profiles.name')
    else
      members.order('profiles.name')
    end
  end

  def members_like(field,value)
    members(field).where("LOWER(#{field}) LIKE ?", "%#{value.downcase}%") if value
  end

  def members_by_role(roles)
    Person.members_of(self).by_role(roles)
  end

  extend ActsAsHavingSettings::ClassMethods
  acts_as_having_settings field: :data

  store_accessor :metadata
  include MetadataScopes

  def settings
    data
  end

  settings_items :redirect_l10n, :type => :boolean, :default => false
  settings_items :public_content, :type => :boolean, :default => true
  settings_items :description
  settings_items :fields_privacy, :type => :hash, :default => {}
  settings_items :email_suggestions, :type => :boolean, :default => false
  settings_items :profile_admin_mail_notification, :type => :boolean, :default => true

  settings_items :profile_kinds, :type => :hash, :default => {}
  after_save do |profile|
    profile.profile_kinds.each do |key, value|
      environment = profile.environment
      kind = environment.kinds.where(:id => key.to_s).first
      next unless kind.present?

      value == '1' ? kind.add_profile(profile) : kind.remove_profile(profile)
    end
  end
  before_save do |profile|
    unless profile.setting_changed?(:profile_kinds)
      profile.profile_kinds = {}
    end
  end

  def kinds_style_classes
    return nil if kinds.blank?
    kinds.map(&:style_class).join(' ')
  end

  extend ActsAsHavingBoxes::ClassMethods
  acts_as_having_boxes

  acts_as_taggable

  def self.qualified_column_names
    Profile.column_names.map{|n| [Profile.table_name, n].join('.')}.join(',')
  end

  scope :visible, -> { where visible: true, secret: false }
  scope :invisible, -> { where 'profiles.visible <> ?', true }
  scope :is_public, -> { where visible: true, public_profile: true, secret: false }

  scope :enabled, -> { where enabled: true }
  scope :disabled, -> { where 'profiles.enabled <> ?', true }

  # subclass specific
  scope :more_popular, -> { }
  scope :more_active, -> { order 'profiles.activities_count DESC' }
  scope :more_recent, -> { order "profiles.created_at DESC" }

  scope :followed_by, -> person{
    distinct.select('profiles.*').
    joins('left join profiles_circles ON profiles_circles.profile_id = profiles.id').
    joins('left join circles ON circles.id = profiles_circles.circle_id').
    where('circles.person_id = ?', person.id)
  }

  scope :in_circle, -> circle{
    distinct.select('profiles.*').
    joins('left join profiles_circles ON profiles_circles.profile_id = profiles.id').
    joins('left join circles ON circles.id = profiles_circles.circle_id').
    where('circles.id = ?', circle.id)
  }

  settings_items :wall_access, :type => :integer, :default => AccessLevels::LEVELS[:users]
  settings_items :allow_followers, :type => :boolean, :default => true
  alias_method :allow_followers?, :allow_followers

  acts_as_trackable :dependent => :destroy

  has_many :profile_activities
  has_many :action_tracker_notifications, :foreign_key => 'profile_id'
  has_many :tracked_notifications, -> { order 'updated_at DESC' }, through: :action_tracker_notifications, source: :action_tracker
  has_many :scraps_received, -> { order 'updated_at DESC' }, class_name: 'Scrap', foreign_key: :receiver_id, dependent: :destroy
  belongs_to :template, :class_name => 'Profile', :foreign_key => 'template_id'

  has_many :comments_received, :class_name => 'Comment', :through => :articles, :source => :comments

  has_many :email_templates, :foreign_key => :owner_id

  has_many :profile_followers
  has_many :followers, -> { uniq }, :class_name => 'Person', :through => :profile_followers, :source => :person

  # Although this should be a has_one relation, there are no non-silly names for
  # a foreign key on article to reference the template to which it is
  # welcome_page... =P
  belongs_to :welcome_page, :class_name => 'Article', :dependent => :destroy

  def welcome_page_content
    welcome_page && welcome_page.published ? welcome_page.body : nil
  end

  has_many :search_terms, :as => :context

  def scraps(scrap=nil)
    scrap = scrap.is_a?(Scrap) ? scrap.id : scrap
    scrap.nil? ? Scrap.all_scraps(self) : Scrap.all_scraps(self).find(scrap)
  end

  validates_length_of :description, :maximum => 550, :allow_nil => true

  # Valid identifiers must match this format.
  IDENTIFIER_FORMAT = /\A#{Noosfero.identifier_format}\Z/

  # These names cannot be used as identifiers for Profiles
  RESERVED_IDENTIFIERS = %w[
  admin
  system
  myprofile
  profile
  cms
  community
  test
  search
  not_found
  cat
  tag
  tags
  environment
  webmaster
  info
  root
  assets
  doc
  chat
  plugin
  site
  ]

  settings_items :products_per_catalog_page, :type => :integer, :default => 18

  belongs_to :user

  has_many :domains, :as => :owner
  belongs_to :preferred_domain, :class_name => 'Domain', :foreign_key => 'preferred_domain_id'
  belongs_to :environment

  has_many :articles, :dependent => :destroy
  belongs_to :home_page, :class_name => Article.name, :foreign_key => 'home_page_id'

  has_many :files, :class_name => 'UploadedFile'

  extend ActsAsHavingImage::ClassMethods
  acts_as_having_image
  acts_as_having_image field: :top_image

  has_many :tasks, :dependent => :destroy, :as => 'target'

  has_many :events, -> { order 'start_date' }, source: 'articles', class_name: 'Event'

  def find_in_all_tasks(task_id)
    begin
      Task.to(self).find(task_id)
    rescue
      nil
    end
  end

  has_many :profile_categorizations, -> { where 'categories_profiles.virtual = ?', false }
  has_many :categories, -> { where 'categories.visible_for_profiles = ?', true }, through: :profile_categorizations
  has_many :regions, -> { where(:type => ['Region', 'State', 'City']) }, :through => :profile_categorizations, :source => :category

  has_many :profile_categorizations_including_virtual, :class_name => 'ProfileCategorization'
  has_many :categories_including_virtual, :through => :profile_categorizations_including_virtual, :source => :category

  has_many :abuse_complaints, :foreign_key => 'requestor_id', :dependent => :destroy

  has_many :profile_suggestions, :foreign_key => :suggestion_id, :dependent => :destroy

  has_and_belongs_to_many :kinds

  def top_level_categorization
    ret = {}
    self.categories.each do |c|
      p = c.top_ancestor
      ret[p] = (ret[p] || []) + [c]
    end
    ret
  end

  def wall_access_levels
    AccessLevels.options(1)
  end

  def interests
    categories.select {|item| !item.is_a?(Region)}
  end

  belongs_to :region

  LOCATION_FIELDS = %w[address address_line2 district city state country_name zip_code]

  before_save :save_old_region
  def save_old_region
    self.old_region_id = self.region_id_was || self.region_id
  end

  def location(separator = ' - ')
    myregion = self.region
    if myregion
      myregion.hierarchy.reverse.first(2).map(&:name).join(separator)
    else
      LOCATION_FIELDS.map {|item| (self.respond_to?(item) && !self.send(item).blank?) ? self.send(item) : nil }.compact.join(separator)
    end
  end

  def geolocation
    unless location.blank?
      location
    else
      if environment.location.blank?
        environment.location = "BRA"
      end
      environment.location
    end
  end

  def country_name
    CountriesHelper::Object.instance.lookup(country) if respond_to?(:country)
  end

  def pending_categorizations
    @pending_categorizations ||= []
  end

  def add_category(c, reload=false)
    if new_record?
      pending_categorizations << c
    else
      ProfileCategorization.add_category_to_profile(c, self)
      self.categories(true)
    end
    self.categories(reload)
  end

  def category_ids=(ids)
    ProfileCategorization.remove_all_for(self)
    ids.uniq.each do |item|
      add_category(Category.find(item)) unless item.to_i.zero?
    end
  end

  after_create :create_pending_categorizations
  def create_pending_categorizations
    pending_categorizations.each do |item|
      ProfileCategorization.add_category_to_profile(item, self)
    end
    pending_categorizations.clear
  end

  def top_level_articles(reload = false)
    if reload
      @top_level_articles = nil
    end
    @top_level_articles ||= Article.top_level_for(self)
  end

  def self.is_available?(identifier, environment, profile_id=nil)
    return false unless identifier =~ IDENTIFIER_FORMAT &&
      !Profile::RESERVED_IDENTIFIERS.include?(identifier) &&
      (NOOSFERO_CONF['exclude_profile_identifier_pattern'].blank? || identifier !~ /#{NOOSFERO_CONF['exclude_profile_identifier_pattern']}/)
    return true if environment.nil?

    environment.is_identifier_available?(identifier, profile_id)
  end

  def self.visible_for_person(person)
    self.all
  end

  validates_presence_of :identifier, :name
  validates_length_of :nickname, :maximum => 40, :allow_nil => true
  validate :valid_template
  validate :valid_identifier

  def valid_identifier
    errors.add(:identifier, :not_available) unless Profile.is_available?(identifier, environment, id)
  end

  def valid_template
    if template_id.present? && template && !template.is_template
      errors.add(:template, _('is not a template.'))
    end
  end

  before_create :set_default_environment
  def set_default_environment
    if self.environment.nil?
      self.environment = Environment.default
    end
    true
  end

  # registar callback for creating boxes after the object is created.
  after_create :create_default_set_of_boxes

  # creates the initial set of boxes when the profile is created. Can be
  # overriden for each subclass to create a custom set of boxes for its
  # instances.
  def create_default_set_of_boxes
    if template
      apply_template(template, :copy_articles => false)
    else
      NUMBER_OF_BOXES.times do
        self.boxes << Box.new
      end

      if self.respond_to?(:default_set_of_blocks)
        default_set_of_blocks.each_with_index do |blocks,i|
          blocks.each do |block|
            self.boxes[i].blocks << block
          end
        end
      end
    end

    true
  end

  def copy_blocks_from(profile)
    template_boxes = profile.boxes.select{|box| box.position}
    self.boxes.destroy_all
    self.boxes = template_boxes.size.times.map { Box.new }

    template_boxes.each_with_index do |box, i|
      new_box = self.boxes[i]
      new_box.position = box.position
      box.blocks.each do |block|
        new_block = block.class.new(:title => block[:title])
        new_block.copy_from(block)
        new_box.blocks << new_block
        if block.mirror?
          block.add_observer(new_block)
        end
      end
    end
  end

  # this method should be overwritten to provide the correct template
  def default_template
    nil
  end

  def template_with_default
    template_without_default || default_template
  end
  alias_method_chain :template, :default

  def apply_template(template, options = {:copy_articles => true})
    self.template = template
    copy_blocks_from(template)
    copy_articles_from(template) if options[:copy_articles]
    self.apply_type_specific_template(template)

    # copy interesting attributes
    self.layout_template = template.layout_template
    self.theme = template.theme
    self.custom_footer = template[:custom_footer]
    self.custom_header = template[:custom_header]
    self.public_profile = template.public_profile

    # flush
    self.save(:validate => false)
  end

  def apply_type_specific_template(template)
  end

  xss_terminate :only => [ :name, :nickname, :address, :contact_phone, :description ], :on => 'validation'
  xss_terminate :only => [ :custom_footer, :custom_header ], :with => 'white_list'

  include SanitizeTags

  include WhiteListFilter
  filter_iframes :custom_header, :custom_footer
  def iframe_whitelist
    environment && environment.trusted_sites_for_iframe
  end

  # returns the contact email for this profile.
  #
  # Subclasses may -- and should -- override this method.
  def contact_email
    raise NotImplementedError
  end

  # This method must return a list of e-mail adresses to which notification messages must be sent.
  # The implementation in this class just delegates to +contact_email+. Subclasse may override this method.
  def notification_emails
    [contact_email]
  end

  # gets recent documents in this profile, ordered from the most recent to the
  # oldest.
  #
  # +limit+ is the maximum number of documents to be returned. It defaults to
  # 10.
  def recent_documents(limit = 10, options = {}, pagination = true)
    self.articles.recent(limit, options, pagination)
  end

  def last_articles limit = 10
    self.articles.limit(limit).where(
      "advertise = ? AND published = ? AND
      ((articles.type != ? and articles.type != ? and articles.type != ?) OR
      articles.type is NULL)",
      true, true, 'UploadedFile', 'RssFeed', 'Blog'
    ).order('articles.published_at desc, articles.id desc')
  end

  def to_liquid
    HashWithIndifferentAccess.new :name => name, :identifier => identifier
  end

  class << self

    # finds a profile by its identifier. This method is a shortcut to
    # +find_by_identifier+.
    #
    # Examples:
    #
    #  person = Profile['username']
    #  org = Profile.['orgname']
    def [](identifier)
      self.find_by identifier: identifier
    end

  end

  def superior_instance
    environment
  end

  # returns +false+
  def person?
    self.kind_of?(Person)
  end

  def enterprise?
    self.kind_of?(Enterprise)
  end

  def organization?
    self.kind_of?(Organization)
  end

  def community?
    self.kind_of?(Community)
  end

  # returns false.
  def is_validation_entity?
    false
  end

  def url
    @url ||= generate_url(:controller => 'content_viewer', :action => 'view_page', :page => [])
  end

  def admin_url
    { :profile => identifier, :controller => 'profile_editor', :action => 'index' }
  end

  def tasks_url
    { :profile => identifier, :controller => 'tasks', :action => 'index', :host => default_hostname }
  end

  def leave_url(reload = false)
    { :profile => identifier, :controller => 'profile', :action => 'leave', :reload => reload }
  end

  def join_url
    { :profile => identifier, :controller => 'profile', :action => 'join' }
  end

  def join_not_logged_url
    { :profile => identifier, :controller => 'profile', :action => 'join_not_logged' }
  end

  def check_membership_url
    { :profile => identifier, :controller => 'profile', :action => 'check_membership' }
  end

  def add_url
    { :profile => identifier, :controller => 'profile', :action => 'add' }
  end

  def check_friendship_url
    { :profile => identifier, :controller => 'profile', :action => 'check_friendship' }
  end

  def public_profile_url
    generate_url(:profile => identifier, :controller => 'profile', :action => 'index')
  end

  def people_suggestions_url
    generate_url(:profile => identifier, :controller => 'friends', :action => 'suggest')
  end

  def communities_suggestions_url
    generate_url(:profile => identifier, :controller => 'memberships', :action => 'suggest')
  end

  def generate_url(options)
    url_options.merge(options)
  end

  def url_options
    options = { :host => default_hostname }
    options[:profile] = self.identifier unless self.own_hostname
    options.merge(Noosfero.url_options)
  end

  def top_url(scheme = 'http')
    url = scheme + '://'
    url << url_options[:host]
    url << ':' << url_options[:port].to_s if url_options.key?(:port)
    url << Noosfero.root('')
    url.html_safe
  end

private :generate_url, :url_options

  def default_domain
    @default_domain ||= self.domains.sort_by{ |d| d.is_default ? 0 : 1 }.first
  end

  def hostname
    preferred_domain ? preferred_domain.name : own_hostname
  end

  def default_hostname
    @default_hostname ||= self.hostname || self.environment.default_hostname
  end

  def own_hostname
    default_domain ? default_domain.name : nil
  end

  def possible_domains
    environment.domains + self.domains
  end

  def article_tags
    articles.tag_counts.inject({}) do |memo,tag|
      memo[tag.name] = tag.count
      memo
    end
  end

  # Tells whether a specified profile has members or nor.
  #
  # On this class, returns <tt>false</tt> by default.
  def has_members?
    false
  end

  after_create :insert_default_article_set
  def insert_default_article_set
    if template
      self.save! if copy_articles_from template
    else
      default_set_of_articles.each do |article|
        article.profile = self
        article.advertise = false
        article.save!
      end
      self.save!
    end
  end

  # Override this method in subclasses of Profile to create a default article
  # set upon creation. Note that this method will be called *only* if there is
  # no template for the type of profile (i.e. if the template was removed or in
  # the creation of the template itself).
  #
  # This method must return an array of pre-populated articles, which will be
  # associated to the profile before being saved. Example:
  #
  #   def default_set_of_articles
  #     [Blog.new(:name => 'Blog'), Gallery.new(:name => 'Gallery')]
  #   end
  #
  # By default, this method returns an empty array.
  def default_set_of_articles
    []
  end

  def copy_articles_from other
    return false if other.top_level_articles.empty?
    other.top_level_articles.each do |a|
      copy_article_tree a
    end
    self.articles.reload
    true
  end

  def copy_article_tree(article, parent=nil)
    return if !copy_article?(article)
    original_article = self.articles.find_by name: article.name
    if original_article
      num = 2
      new_name = original_article.name + ' ' + num.to_s
      while self.articles.find_by name: new_name
        num = num + 1
        new_name = original_article.name + ' ' + num.to_s
      end
      original_article.update!(:name => new_name)
    end
    article_copy = article.copy(:profile => self, :parent => parent, :advertise => false)
    if article.profile.home_page == article
      self.home_page = article_copy
    end
    article.children.each do |a|
      copy_article_tree a, article_copy
    end
  end

  def copy_article?(article)
    !article.is_a?(RssFeed) &&
    !(is_template && article.slug=='welcome-page')
  end

  # Adds a person as member of this Profile.
  def add_member(person, invited=false, **attributes)
    if self.has_members? && (!self.secret || invited)
      if self.closed? && members.count > 0
        AddMember.create!(:person => person, :organization => self) unless self.already_request_membership?(person)
      else
        self.affiliate(person, Profile::Roles.admin(environment.id), attributes) if members.count == 0
        self.affiliate(person, Profile::Roles.member(environment.id), attributes)
        person.follow(self, Circle.find_or_create_by(:person => person, :name =>_('memberships'), :profile_type => 'Community'))
      end
      person.tasks.pending.of("InviteMember").select { |t| t.data[:community_id] == self.id }.each { |invite| invite.cancel }
      remove_from_suggestion_list person
    else
      raise _("%s can't have members") % self.class.name
    end
  end

  def remove_member(person)
    self.disaffiliate(person, Profile::Roles.all_roles(environment.id))
  end

  # adds a person as administrator os this profile
  def add_admin(person)
    self.affiliate(person, Profile::Roles.admin(environment.id))
    # FIXME: fix find_or_create_by on code below
    # circle = Circle.find_or_create_by(name: _('memberships'), profile_type: self.class.name, person: person)
    # person.follow(self, circle)
    circle = Circle.where(name: _('memberships'), profile_type: self.class.name, person: person).first
    person.follow(self, circle) if circle
  end

  def remove_admin(person)
    self.disaffiliate(person, Profile::Roles.admin(environment.id))
  end

  def add_moderator(person)
    if self.has_members?
      self.affiliate(person, Profile::Roles.moderator(environment.id))
    else
      raise _("%s can't has moderators") % self.class.name
    end
  end

  # returns +true+ if the given +user+ can see profile information about this
  # +profile+, and +false+ otherwise.
  def display_info_to?(user = nil)
    if self.public?
      true
    else
      display_private_info_to?(user)
    end
  end
  alias_method :display_to?, :display_info_to?

  after_save :update_category_from_region
  def update_category_from_region
    ProfileCategorization.remove_region(self)
    if region
      self.add_category(region)
    end
  end

  def accept_category?(cat)
    cat.visible_for_profiles
  end

  include ActionView::Helpers::TextHelper
  def short_name(chars = 40)
    if self[:nickname].blank?
      if chars
        truncate self.name, length: chars, omission: '...'
      else
        self.name
      end
    else
      self[:nickname]
    end
  end

  def custom_header
    self[:custom_header] || environment && environment.custom_header
  end

  def custom_header_expanded
    header = custom_header
    if header
      %w[name short_name].each do |att|
        if self.respond_to?(att) && header.include?("{#{att}}")
          header.gsub!("{#{att}}", self.send(att))
        end
      end
      header
    end
  end

  def custom_footer
    self[:custom_footer] || environment && environment.custom_footer
  end

  def custom_footer_expanded
    footer = custom_footer
    if footer
      %w[contact_person contact_email contact_phone location address district address_reference economic_activity city state country zip_code].each do |att|
        if self.respond_to?(att) && footer.match(/\{[^{]*#{att}\}/)
          if !self.send(att).nil? && !self.send(att).blank?
            footer = footer.gsub(/\{([^{]*)#{att}\}/, '\1' + self.send(att))
          else
            footer = footer.gsub(/\{[^}]*#{att}\}/, '')
          end
        end
      end
      footer
    end
  end

  def public?
    visible && public_profile
  end

  def privacy_setting
    self.public? ? _('Public profile') : _('Private profile')
  end

  def themes
    Theme.find_by_owner(self)
  end

  def find_theme(the_id)
    themes.find { |item| item.id == the_id }
  end

  settings_items :layout_template, :type => String, :default => 'default'

  has_many :blogs, :source => 'articles', :class_name => 'Blog'

  def blog
    self.has_blog? ? self.blogs.order(:id).first : nil
  end

  def has_blog?
    self.blogs.count.nonzero?
  end

  has_many :forums, :source => 'articles', :class_name => 'Forum'

  def forum
    self.has_forum? ? self.forums.order(:id).first : nil
  end

  def has_forum?
    self.forums.count.nonzero?
  end

  def admins
    return [] if environment.blank?
    admin_role = Profile::Roles.admin(environment.id)
    return [] if admin_role.blank?
    self.members_by_role(admin_role)
  end

  def enable_contact?
    !environment.enabled?('disable_contact_' + self.class.name.downcase)
  end

  include Noosfero::Plugin::HotSpot

  def folder_types
    types = Article.folder_types
    plugins.dispatch(:content_types).each {|type|
      if type < Folder
        types << type.name
      end
    }
    types
  end

  def folders
    articles.folders(self)
  end

  def image_galleries
    articles.galleries
  end

  def blocks_to_expire_cache
    []
  end

  def cache_keys(params = {})
    []
  end

  validate :image_valid

  def image_valid
    unless self.image.nil?
      self.image.valid?
      self.image.errors.delete(:empty) # dont validate here if exists uploaded data
      self.image.errors.each do |attr,msg|
        self.errors.add(attr, msg)
      end
    end
  end

  # FIXME: horrible workaround to circular dependancy in environment.rb
  after_update do |profile|
    ProfileSweeper.new().after_update(profile)
  end

  # FIXME: horrible workaround to circular dependancy in environment.rb
  after_create do |profile|
    ProfileSweeper.new().after_create(profile)
  end

  def update_header_and_footer(header, footer)
    self.custom_header = header
    self.custom_footer = footer
    self.save(:validate => false)
  end

  def update_theme(theme)
    self.update_attribute(:theme, theme)
  end

  def update_layout_template(template)
    self.update_attribute(:layout_template, template)
  end

  def members_cache_key(params = {})
    page = params[:npage] || '1'
    sort = (params[:sort] ==  'desc') ? params[:sort] : 'asc'
    cache_key + '-members-page-' + page + '-' + sort
  end

  def more_recent_label
    _("Since: ")
  end

  def recent_actions
    tracked_actions.recent
  end

  def recent_notifications
    tracked_notifications.recent
  end

  def more_active_label
    amount = recent_actions.count
    amount += recent_notifications.count if organization?
    {
      0 => _('no activity'),
      1 => _('one activity')
    }[amount] || _("%s activities") % amount
  end

  def more_popular_label
    amount = self.members_count
    {
      0 => _('no members'),
      1 => _('one member')
    }[amount] || _("%s members") % amount
  end

  include Noosfero::Gravatar

  def profile_custom_icon(gravatar_default=nil)
    image.public_filename(:icon) if image.present?
  end

  #FIXME make this test
  def profile_custom_image(size = :icon)
    image_path = profile_custom_icon if size == :icon
    image_path ||= image.public_filename(size) if image.present?
    image_path
  end

  def jid(options = {})
    domain = options[:domain] || environment.default_hostname
    "#{identifier}@#{domain}"
  end
  def full_jid(options = {})
    "#{jid(options)}/#{short_name}"
  end

  def is_on_homepage?(url, page=nil)
    if page
      page == self.home_page
    else
      url == '/' + self.identifier
    end
  end

  def opened_abuse_complaint
    abuse_complaints.opened.first
  end

  def disable
    self.visible = false
    self.save
  end

  def enable
    self.visible = true
    self.save
  end

  def control_panel_settings_button
    {:title => _('Edit Profile'), :icon => 'edit-profile'}
  end

  def self.identification
    name
  end

  def exclude_verbs_on_activities
    %w[]
  end

  # Customize in subclasses
  def activities
    self.profile_activities.includes(:activity).order('updated_at DESC')
  end

  def may_display_field_to? field, user = nil
    if not self.active_fields.include? field.to_s
      self.send "may_display_#{field}_to?", user rescue true
    else
      not (!self.public_fields.include? field.to_s and (!user or (user != self and !user.is_a_friend?(self))))
    end
  end

  # field => privacy (e.g.: "address" => "public")
  def fields_privacy
    self.data[:fields_privacy] ||= {}
    custom_field_privacy = {}
    self.custom_field_values.includes(:custom_field).pluck("custom_fields.name", :public).to_h.map do |field, is_public|
      custom_field_privacy[field] = 'public' if is_public
    end
    self.data[:fields_privacy].merge!(custom_field_privacy)

    self.data[:fields_privacy]
  end

  def custom_field_value(field_name)
    value = nil
    begin
     value = self.send(field_name)
    rescue NoMethodError
      value = self.custom_field_values.by_field(field_name).pluck(:value).first
    end
    value
  end

  # abstract
  def active_fields
    []
  end

  def public_fields
    self.active_fields
  end

  def control_panel_settings_button
    {:title => _('Profile Info and settings'), :icon => 'edit-profile'}
  end

  def followed_by?(person)
    (person == self) || (person.is_member_of?(self)) || (person.in? self.followers)
  end

  def in_social_circle?(person)
    (person == self) || (person.is_member_of?(self))
  end

  def display_private_info_to?(user)
    if user.nil?
      false
    else
      (user == self) || (user.is_admin?(self.environment)) || user.is_admin?(self) || user.memberships.include?(self)
    end
  end

  def can_view_field? current_person, field
    display_private_info_to?(current_person) || (public_fields.include?(field) && public?)
  end

  validates_inclusion_of :redirection_after_login, :in => Environment.login_redirection_options.keys, :allow_nil => true
  def preferred_login_redirection
    redirection_after_login.blank? ? environment.redirection_after_login : redirection_after_login
  end
  settings_items :custom_url_redirection, type: String, default: nil

  def remove_from_suggestion_list(person)
    suggestion = person.suggested_profiles.find_by suggestion_id: self.id
    suggestion.disable if suggestion
  end

  def allow_invitation_from(person)
    false
  end

  def allow_post_content?(person = nil)
    person.kind_of?(Profile) && person.has_permission?('post_content', self)
  end

  def allow_edit?(person = nil)
    person.kind_of?(Profile) && person.has_permission?('edit_profile', self)
  end

  def allow_destroy?(person = nil)
    person.kind_of?(Profile) && person.has_permission?('destroy_profile', self)
  end

  def in_circle?(circle, follower)
    ProfileFollower.with_follower(follower).with_circle(circle).with_profile(self).present?
  end

  def available_blocks(person)
    blocks = [ ArticleBlock, TagsCloudBlock, InterestTagsBlock, RecentDocumentsBlock, ProfileInfoBlock, LinkListBlock, MyNetworkBlock, FeedReaderBlock, ProfileImageBlock, LocationBlock, SlideshowBlock, ProfileSearchBlock, HighlightsBlock, MenuBlock ]
    # block exclusive to profiles that have blog
    blocks << BlogArchivesBlock if self.has_blog?
    # block exclusive for environment admin
    blocks << RawHTMLBlock if person.present? && person.is_admin?(self.environment)
    blocks + plugins.dispatch(:extra_blocks, type: self.class)
  end
end