cirandas.net

ref: master

app/models/article.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
class Article < ApplicationRecord

  module Editor
    TEXTILE = 'textile'
    TINY_MCE = 'tiny_mce'
    RAW_HTML = 'raw_html'
  end

  include SanitizeHelper
  include SanitizeTags

  attr_accessible :name, :body, :abstract, :profile, :tag_list, :parent,
                  :allow_members_to_edit, :translation_of_id, :language,
                  :license_id, :parent_id, :display_posts_in_current_language,
                  :category_ids, :posts_per_page, :moderate_comments,
                  :accept_comments, :feed, :published, :source, :source_name,
                  :highlighted, :notify_comments, :display_hits, :slug,
                  :external_feed_builder, :display_versions, :external_link,
                  :image_builder, :show_to_followers, :archived,
                  :author, :display_preview, :published_at, :person_followers,
                  :editor,
                  :created_by, :last_changed_by

  extend ActsAsHavingImage::ClassMethods
  acts_as_having_image

  include Noosfero::Plugin::HotSpot

  SEARCHABLE_FIELDS = {
    :name => {:label => _('Name'), :weight => 10},
    :abstract => {:label => _('Abstract'), :weight => 3},
    :body => {:label => _('Content'), :weight => 2},
    :slug => {:label => _('Slug'), :weight => 1},
    :filename => {:label => _('Filename'), :weight => 1},
  }

  SEARCH_FILTERS = {
    :order => %w[more_recent more_popular more_comments more_relevant],
    :display => %w[full]
  }

  N_('article')

  def initialize(*params)
    super
    if params.present? && params.first.present?
      if params.first.symbolize_keys.has_key?(:published)
        self.published = params.first.symbolize_keys[:published]
      elsif params.first[:profile].present? && !params.first[:profile].public_profile
        self.published = false
      end
    end
  end

  def self.default_search_display
    'full'
  end

  #FIXME This is necessary because html is being generated on the model...
  include ActionView::Helpers::TagHelper

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

  track_actions :create_article, :after_create, :keep_params => [:name, :url, :lead, :first_image], :if => Proc.new { |a| a.notifiable? }

  before_create do |article|
    if article.author
      article.author_name = article.author.name
    end
  end

  belongs_to :profile
  validates_presence_of :profile_id, :name
  validates_presence_of :slug, :path, :if => lambda { |article| !article.name.blank? }

  validates_length_of :name, :maximum => 150

  validates_uniqueness_of :slug, :scope => ['profile_id', 'parent_id'], :message => N_('The title (article name) is already being used by another article, please use another title.'), :if => lambda { |article| !article.slug.blank? }

  belongs_to :author, :class_name => 'Person'
  belongs_to :last_changed_by, :class_name => 'Person', :foreign_key => 'last_changed_by_id'
  belongs_to :created_by, :class_name => 'Person', :foreign_key => 'created_by_id'

  has_many :comments, -> { order 'created_at asc' }, class_name: 'Comment', as: 'source', dependent: :destroy

  has_many :article_followers, :dependent => :destroy
  has_many :person_followers, :class_name => 'Person', :through => :article_followers, :source => :person
  has_many :person_followers_emails, -> { select :email }, class_name: 'User', through: :person_followers, source: :user

  has_many :article_categorizations, -> { where 'articles_categories.virtual = ?', false }
  has_many :categories, -> { where 'categories.visible_for_articles = ?', true }, through: :article_categorizations

  has_many :article_categorizations_including_virtual, :class_name => 'ArticleCategorization'
  has_many :categories_including_virtual, :through => :article_categorizations_including_virtual, :source => :category

  extend ActsAsHavingSettings::ClassMethods
  acts_as_having_settings field: :setting

  store_accessor :metadata
  include MetadataScopes

  settings_items :display_hits, :type => :boolean, :default => true
  settings_items :author_name, :type => :string, :default => ""
  settings_items :allow_members_to_edit, :type => :boolean, :default => false
  settings_items :moderate_comments, :type => :boolean, :default => false
  has_and_belongs_to_many :article_privacy_exceptions, :class_name => 'Person', :join_table => 'article_privacy_exceptions'

  belongs_to :reference_article, :class_name => "Article", :foreign_key => 'reference_article_id'

  belongs_to :license

  has_many :translations, :class_name => 'Article', :foreign_key => :translation_of_id
  belongs_to :translation_of, :class_name => 'Article', :foreign_key => :translation_of_id
  before_destroy :rotate_translations

  acts_as_voteable

  after_save :invalidate_parent_cache

  before_create do |article|
    article.published_at ||= Time.now
    if article.reference_article && !article.parent
      parent = article.reference_article.parent
      if parent && parent.blog? && article.profile.has_blog?
        article.parent = article.profile.blog
      end
    end

    if article.created_by
      article.author_name = article.created_by.name
    end

  end

  after_destroy :destroy_activity
  def destroy_activity
    self.activity.destroy if self.activity
  end

  after_destroy :destroy_link_article
  def destroy_link_article
    Article.where(:reference_article_id => self.id, :type => LinkArticle).destroy_all
  end

  xss_terminate :only => [ :name ], :on => 'validation', :with => 'white_list'

  scope :in_category, -> category {
    includes('categories_including_virtual').where('categories.id' => category.id)
  }

  include TimeScopes

  scope :by_range, -> range {
    where 'articles.published_at BETWEEN :start_date AND :end_date', { start_date: range.first, end_date: range.last }
  }

  URL_FORMAT = /\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\Z/ix

  validates_format_of :external_link, :with => URL_FORMAT, :if => lambda { |article| !article.external_link.blank? }
  validate :known_language
  validate :used_translation
  validate :native_translation_must_have_language
  validate :translation_must_have_language

  validate :no_self_reference
  validate :no_cyclical_reference, :if => 'parent_id.present?'

  validate :parent_archived?

  validate :valid_slug

  RESERVED_SLUGS = %w[
    about
    activities
  ]

  def valid_slug
    errors.add(:title, _('is not available as article name.')) unless Article.is_slug_available?(slug)
  end

  def self.is_slug_available?(slug)
    !RESERVED_SLUGS.include?(slug)
  end

  def no_self_reference
    errors.add(:parent_id, _('self-reference is not allowed.')) if id && parent_id == id
  end

  def no_cyclical_reference
    current_parent = Article.find(parent_id)
    while current_parent
      if current_parent == self
        errors.add(:parent_id, _('cyclical reference is not allowed.'))
        break
      end
      current_parent = current_parent.parent
    end
  end

  def external_link=(link)
    if !link.blank? && link !~ /^[a-z]+:\/\//i
      link = 'http://' + link
    end
    self[:external_link] = link
  end

  def action_tracker_target
    self.profile
  end

  def self.human_attribute_name_with_customization(attrib, options={})
    case attrib.to_sym
    when :name
      _('Title')
    else
      _(self.human_attribute_name_without_customization(attrib))
    end
  end
  class << self
    alias_method_chain :human_attribute_name, :customization
  end

  def css_class_list
    [self.class.name.to_css_class]
  end

  def css_class_name
    [css_class_list].flatten.compact.join(' ')
  end

  def pending_categorizations
    @pending_categorizations ||= []
  end

  def add_category(c, reload=false)
    if new_record?
      pending_categorizations << c
    else
      ArticleCategorization.add_category_to_article(c, self)
      self.categories(reload)
    end
  end

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

  after_create :create_pending_categorizations
  def create_pending_categorizations
    pending_categorizations.each do |item|
      ArticleCategorization.add_category_to_article(item, self)
    end
    self.categories(true)
    pending_categorizations.clear
  end

  acts_as_taggable
  N_('Tag list')

  extend ActsAsFilesystem::ActsMethods
  acts_as_filesystem

  acts_as_versioned
  self.non_versioned_columns << 'setting'

  def version_condition_met?
    (['name', 'body', 'abstract', 'filename', 'start_date', 'end_date', 'image_id', 'license_id'] & changed).length > 0
  end

  def comment_data
    comments.map {|item| [item.title, item.body].join(' ') }.join(' ')
  end

  before_update do |article|
    article.advertise = true
  end

  before_save do |article|
    article.parent = article.parent_id ? Article.find(article.parent_id) : nil
    parent_path = article.parent ? article.parent.path : nil
    article.path = [parent_path, article.slug].compact.join('/')
  end

  # retrieves all articles belonging to the given +profile+ that are not
  # sub-articles of any other article.
  scope :top_level_for, -> profile {
    where 'parent_id is null and profile_id = ?', profile.id
  }

  scope :is_public, -> {
    joins(:profile).
    where("articles.advertise = ? AND articles.published = ? AND profiles.visible = ? AND profiles.public_profile = ?", true, true, true, true)
  }

  scope :more_recent, -> {
    order('articles.published_at desc, articles.id desc')
    .where("articles.advertise = ? AND articles.published = ? AND profiles.visible = ? AND profiles.public_profile = ? AND
    ((articles.type != ?) OR articles.type is NULL)",
    true, true, true, true, 'RssFeed')
  }

  # retrives the most commented articles, sorted by the comment count (largest
  # first)
  def self.most_commented(limit)
    order('comments_count DESC').paginate(page: 1, per_page: limit)
  end

  scope :more_popular, -> { order 'hits DESC' }
  scope :relevant_as_recent, -> {
   where "(articles.type != 'UploadedFile' and articles.type != 'RssFeed' and articles.type != 'Blog') OR articles.type is NULL"
  }

  def self.recent(limit = nil, extra_conditions = {}, pagination = true)
    result = where(extra_conditions).
      is_public.
      relevant_as_recent.
      limit(limit).
      order(['articles.published_at desc', 'articles.id desc'])

    pagination ? result.paginate({:page => 1, :per_page => limit}) : result
  end

  # produces the HTML code that is to be displayed as this article's contents.
  #
  # The implementation in this class just provides the +body+ attribute as the
  # HTML.  Other article types can override this method to provide customized
  # views of themselves.
  # (To override short format representation, override the lead method)
  def to_html(options = {})
    if options[:format] == 'short'
      article = self
      proc do
        display_short_format(article)
      end
    else
      body || ''
    end
  end

  # returns the data of the article. Must be overriden in each subclass to
  # provide the correct content for the article.
  def data
    body
  end

  # provides the icon name to be used for this article. In this class this
  # method just returns 'text-html', but subclasses may (and should) override
  # to return their specific icons.
  #
  # FIXME use mime_type and generate this name dinamically
  def self.icon_name(article = nil)
    'text-html'
  end

  # TODO Migrate the class method icon_name to instance methods.
  def icon_name
    self.class.icon_name(self)
  end

  def mime_type
    'text/html'
  end

  def mime_type_description
    _('HTML Text document')
  end

  def self.description
    raise NotImplementedError, "#{self} does not implement #description"
  end

  def self.short_description
    raise NotImplementedError, "#{self} does not implement #short_description"
  end

  def title
    name
  end

  include ActionView::Helpers::TextHelper
  def short_title
    truncate self.title, :length => 15, :omission => '...'
  end

  def belongs_to_blog?
    self.parent and self.parent.blog?
  end

  def belongs_to_forum?
    self.parent and self.parent.forum?
  end

  def person_followers_email_list
    person_followers_emails.map{|p|p.email}
  end

  def info_from_last_update
    last_comment = comments.last
    if last_comment
      {:date => last_comment.created_at, :author_name => last_comment.author_name, :author_url => last_comment.author_url}
    else
      {:date => updated_at, :author_name => author_name, :author_url => author_url}
    end
  end

  def full_path
    profile.hostname.blank? ? "/#{profile.identifier}/#{path}" : "/#{path}"
  end

  def url
    @url ||= self.profile.url.merge(:page => path.split('/'))
  end

  def view_url
    @view_url ||= is_a?(UploadedFile) ? url.merge(:view => true) : url
  end

  def comment_url_structure(comment, action = :edit)
    if comment.new_record?
      profile.url.merge(:page => path.split("/"), :controller => :comment, :action => :create)
    else
      profile.url.merge(:page => path.split("/"), :controller => :comment, :action => action || :edit, :id => comment.id)
    end
  end

  def allow_children?
    true
  end

  def has_posts?
    false
  end

  def download? view = nil
    false
  end

  def is_followed_by?(user)
    self.person_followers.include? user
  end

  def download_disposition
    'inline'
  end

  def download_headers
    { :filename => filename, :type => mime_type, :disposition => download_disposition}
  end

  def alternate_languages
    self.translations.map(&:language)
  end

  scope :native_translations, -> { where :translation_of_id => nil }

  def translatable?
    false
  end

  def native_translation
    self.translation_of.nil? ? self : self.translation_of
  end

  def possible_translations
    possibilities = environment.locales.keys - self.native_translation.translations(:select => :language).map(&:language) - [self.native_translation.language]
    possibilities << self.language unless self.language_changed?
    possibilities
  end

  def known_language
    unless self.language.blank?
      errors.add(:language, N_('Language not supported by the environment.')) unless environment.locales.key?(self.language)
    end
  end

  def used_translation
    unless self.language.blank? or self.translation_of.nil?
      errors.add(:language, N_('Language is already used')) unless self.possible_translations.include?(self.language)
    end
  end

  def translation_must_have_language
    unless self.translation_of.nil?
      errors.add(:language, N_('Language must be choosen')) if self.language.blank?
    end
  end

  def native_translation_must_have_language
    unless self.translation_of.nil?
      errors.add(:base, N_('A language must be choosen for the native article')) if self.translation_of.language.blank?
    end
  end

  def rotate_translations
    unless self.translations.empty?
      rotate = self.translations.to_a
      root = rotate.shift
      root.update_attribute(:translation_of_id, nil)
      root.translations = rotate
    end
  end

  def get_translation_to(locale)
    if self.language.nil? || self.language.blank? || self.language == locale
      self
    elsif self.native_translation.language == locale
      self.native_translation
    else
      self.native_translation.translations.where(:language => locale).first
    end
  end

  def published?
    if self.published
      if self.parent && !self.parent.published?
        return false
      end

      true
    else
      false
    end
  end

  def archived?
    (self.parent && self.parent.archived) || self.archived
  end

  def self.folder_types
    ['Folder', 'Blog', 'Forum', 'Gallery']
  end

  scope :published, -> { where 'articles.published = ?', true }
  scope :folders, -> profile { where 'articles.type IN (?)', profile.folder_types }
  scope :no_folders, -> profile { where 'articles.type NOT IN (?)', profile.folder_types }
  scope :galleries, -> { where "articles.type IN ('Gallery')" }
  scope :images, -> { where :is_image => true }
  scope :no_images, -> { where :is_image => false }
  scope :files, -> { where :type => 'UploadedFile' }
  scope :with_types, -> types { where 'articles.type IN (?)', types }

  scope :no_feeds, -> { where "type != 'RssFeed'" }
  scope :latest, -> { order "updated_at DESC" }

  scope :more_popular, -> { order 'articles.hits DESC' }
  scope :more_comments, -> { order "articles.comments_count DESC" }
  scope :more_recent, -> { order "articles.created_at DESC" }

  scope :display_filter, lambda {|user, profile|
    return published if (user.nil? && profile && profile.public?)
    return [] if user.nil? || (profile && !profile.public? && !profile.in_social_circle?(user))
    where(
      [
       "published = ? OR last_changed_by_id = ? OR profile_id = ? OR ?
        OR  (show_to_followers = ? AND ? AND profile_id IN (?))", true, user.id, user.id,
        profile.nil? ?  false : user.has_permission?(:view_private_content, profile),
        true, (profile.nil? ? true : profile.in_social_circle?(user)),  ( profile.nil? ? (user.friends.select('profiles.id')) : [profile.id])
      ]
    )
  }


  def display_unpublished_article_to?(user)
    user == author || allow_view_private_content?(user) || user == profile ||
    user.is_admin?(profile.environment) || user.is_admin?(profile) ||
    article_privacy_exceptions.include?(user) ||
    (self.show_to_followers && user.follows?(profile))
  end

  def display_to?(user = nil)
    if published?
      (profile.secret? || !profile.visible?) ? profile.display_info_to?(user) : true
    else
      if !user
        false
      else
        display_unpublished_article_to?(user)
      end
    end
  end

  def allow_post_content?(user = nil)
    return true if allow_edit_topic?(user)
    user && (profile.allow_post_content?(user) || allow_publish_content?(user) && (user == author))
  end

  def allow_publish_content?(user = nil)
    user && user.has_permission?('publish_content', profile)
  end

  def allow_view_private_content?(user = nil)
    user && user.has_permission?('view_private_content', profile)
  end

  alias :allow_delete?  :allow_post_content?

  def allow_spread?(user = nil)
    user && public?
  end

  def allow_create?(user)
    allow_post_content?(user) || allow_publish_content?(user)
  end

  def allow_edit?(user)
    return true if allow_edit_topic?(user)
    allow_post_content?(user) || user && allow_members_to_edit && user.is_member_of?(profile)
  end

  def allow_edit_topic?(user)
    self.belongs_to_forum? && (user == author) && user.present? && user.is_member_of?(profile)
  end

  def moderate_comments?
    moderate_comments == true
  end

  def comments_updated
    solr_save
  end

  def accept_category?(cat)
    cat.visible_for_articles
  end

  def public?
    profile.visible? && profile.public? && published?
  end

  def copy_without_save(options = {})
    attrs = attributes.reject! { |key, value| ATTRIBUTES_NOT_COPIED.include?(key.to_sym) }
    attrs.merge!(options)
    object = self.class.new
    attrs.each do |key, value|
      object.send(key.to_s+'=', value)
    end
    object
  end

  def copy(options = {})
    object = copy_without_save(options)
    object.save
    object
  end

  def copy!(options = {})
    object = copy_without_save(options)
    object.save!
    object
  end

  ATTRIBUTES_NOT_COPIED = [
    :id,
    :profile_id,
    :parent_id,
    :path,
    :slug,
    :updated_at,
    :created_at,
    :version,
    :lock_version,
    :type,
    :children_count,
    :comments_count,
    :hits,
  ]

  def self.find_by_old_path(old_path)
    self.includes(:versions).where('article_versions.path = ?', old_path).order('article_versions.id DESC').first
  end

  def hit
    if !archived?
      self.class.connection.execute('update articles set hits = hits + 1 where id = %d' % self.id.to_i)
      self.hits += 1
    end
  end

  def self.hit(articles)
    ids = []
    articles.each do |article|
      if !article.archived?
        ids << article.id
        article.hits += 1
      end
    end
    Article.where(:id => ids).update_all('hits = hits + 1') if !ids.empty?
  end

  def can_display_hits?
    true
  end

  def display_hits?
    can_display_hits? && display_hits
  end

  def display_media_panel?
    can_display_media_panel? && environment.enabled?('media_panel')
  end

  def can_display_media_panel?
    false
  end

  settings_items :display_preview, :type => :boolean, :default => false

  def display_preview?
    false
  end

  def image?
    false
  end

  def event?
    false
  end

  def gallery?
    false
  end

  def folder?
    false
  end

  def blog?
    false
  end

  def forum?
    false
  end

  def uploaded_file?
    false
  end

  settings_items :display_versions, :type => :boolean, :default => false

  def can_display_versions?
    false
  end

  def display_versions?
    can_display_versions? && display_versions
  end

  def get_version(version_number = nil)
    if version_number then self.versions.order('version').offset(version_number - 1).first else self.versions.earliest end
  end

  def author_by_version(version_number = nil)
    return author unless version_number
    author_id = get_version(version_number).last_changed_by_id
    profile.environment.people.where(id: author_id).first
  end

  def author_name(version_number = nil)
    person = author_by_version(version_number)
    if version_number
      person ? person.name : _('Unknown')
    else
      person ? person.name : (setting[:author_name] || _('Unknown'))
    end
  end

  def author_url(version_number = nil)
    person = author_by_version(version_number)
    person ? person.url : nil
  end

  def author_id(version_number = nil)
    person = author_by_version(version_number)
    person ? person.id : nil
  end

  #FIXME make this test
  def author_custom_image(size = :icon)
    author ? author.profile_custom_image(size) : nil
  end

  def version_license(version_number = nil)
    return license if version_number.nil?
    profile.environment.licenses.find_by(id: get_version(version_number).license_id)
  end

  def cacheable?
    true
  end

  alias :active_record_cache_key :cache_key
  def cache_key(params = {}, the_profile = nil, language = 'en')
    active_record_cache_key+'-'+language +
      (allow_post_content?(the_profile) ? "-owner" : '') +
      (params[:npage] ? "-npage-#{params[:npage]}" : '') +
      (params[:year] ? "-year-#{params[:year]}" : '') +
      (params[:month] ? "-month-#{params[:month]}" : '') +
      (params[:version] ? "-version-#{params[:version]}" : '')
  end

  def invalidate_parent_cache
    self.parent.touch if self.parent
    self.environment.touch if self.profile == self.environment.portal_community
  end

  def automatic_abstract
  	return '' if self.body.blank? or not self.body.is_a? String
  	a = strip_tags self.body
    automatic_abstract_img = (first_image.present?) ? "<img src='" + first_image + "' class = 'automatic-abstract-thumb'>" : ''
  	b = a.split[0...profile.environment.automatic_abstract_length].join(' ')
  	c = a.split.join(' ')
  	b = (b == c) ? b : b + " ..."
  	b = automatic_abstract_img + b
    b.squish
  end

  def first_paragraph
    paragraphs = Nokogiri::HTML.fragment(to_html).css('p')
    paragraphs.empty? ? '' : paragraphs.first.to_html
  end

  def lead(length = nil)
    content = abstract.blank? ? automatic_abstract.html_safe : abstract.html_safe
    length.present? ? content.truncate(length) : content
  end

  def short_lead
    truncate sanitize_html(self.lead), :length => 170, :omission => '...'
  end

  def notifiable?
    false
  end

  def accept_uploads?
    self.parent && self.parent.accept_uploads?
  end

  def body_images_paths
    paths = Nokogiri::HTML.fragment(self.body.to_s).css('img[src]').collect do |i|
      src = i['src']
      src = URI.escape src if self.new_record? # xss_terminate runs on save
      (self.profile && self.profile.environment) ? URI.join(self.profile.environment.top_url, src).to_s : src
    end
    paths.unshift(URI.join(self.profile.environment.top_url, self.image.public_filename).to_s) if self.image.present?
    paths
  end

  def more_comments_label
    amount = self.comments_count
    {
      0 => _('no comments'),
      1 => _('one comment')
    }[amount] || _("%s comments") % amount

  end

  def more_popular_label
    amount = self.hits
    {
      0 => _('no views'),
      1 => _('one view')
    }[amount] || _("%s views") % amount

  end

  def more_recent_label
    _('Created at: ')
  end

  def activity
    ActionTracker::Record.where(target_type: 'Article', target_id: self.id).first
  end

  def create_activity
    if notifiable? && !image?
      save_action_for_verb 'create_article', [:name, :url, :lead, :first_image], Proc.new{}, :author
    end
  end

  def first_image
    img = ( image.present? && { 'src' => File.join([Noosfero.root, image.public_filename].join) } ) ||
          # automatic_abstract conflict, this leads to infinite loop
          #Nokogiri::HTML.fragment(self.lead.to_s).css('img[src]').first ||
          Nokogiri::HTML.fragment(self.body.to_s).search('img').first
    img.nil? ? '' : img['src']
  end

  delegate :lat, :lng, :region, :region_id, :environment, :environment_id, :to => :profile, :allow_nil => true

  def has_macro?
    true
  end

  def to_liquid
    HashWithIndifferentAccess.new :name => name, :abstract => abstract, :body => body, :id => id, :parent_id => parent_id, :author => author
  end

  def self.can_display_blocks?
    false
  end

  def editor?(editor)
    self.editor == editor
  end

  private

  def parent_archived?
     if self.parent_id_changed? && self.parent && self.parent.archived?
       errors.add(:parent_folder, N_('is archived!!'))
     end
  end

  def strip_tags(html)
    html.gsub(/<[^>]+>/, ' ').gsub(/\s+/, ' ')
  end

end