summaryrefslogtreecommitdiff
path: root/app/models/node.rb
blob: 73eefd18a63eff558f08d138051951eebaed5e62 (plain)
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
class Node < ApplicationRecord
  # Mixins and Plugins
  include NestedTree

  # Associations
  has_many    :pages, -> { order("revision ASC") }, :dependent => :destroy
  belongs_to  :head,  :class_name => "Page",  :foreign_key => :head_id, :dependent => :destroy, optional: true
  belongs_to  :draft, :class_name => "Page",  :foreign_key => :draft_id, :dependent => :destroy, optional: true
  belongs_to  :autosave, :class_name => "Page", :foreign_key => :autosave_id, :dependent => :destroy, optional: true
  has_many    :permissions, :dependent => :destroy
  has_many    :events, :dependent => :destroy
  belongs_to  :lock_owner, :class_name => "User", :foreign_key => :locking_user_id, optional: true

  # Callbacks
  after_create  :initialize_empty_page
  before_save   :check_for_changed_slug
  after_save    :update_unique_names_of_children

  # Validations
  validates_length_of     :slug, :within => 1..255,    :unless => -> { parent_id.nil? || slug.blank? }
  validates_presence_of   :slug,                       :unless => -> { parent_id.nil? }
  validates_uniqueness_of :slug, :scope => :parent_id, :unless => -> { parent_id.nil? }
  validates_presence_of   :parent_id,                  :unless => -> { Node.root.nil? }

  # Class methods

  # Returns a page for a given node. If no revision is supplied, it returns
  # the last / current one. If a specific revision number is supplied, the
  # corresponding revision of that page is returned. Get the current / latest
  # revision with -1. It raises an Argument error if the revision is not a
  # Fixnum
  def self.find_page path, revision = -1
    unless revision.is_a?(Integer)
      raise ArgumentError, "revision must be a Integer"
    end

    node = Node.find_by_unique_name(path)

    if node
      case revision
      when -1
        return node.head
      else
        return node.pages.find_by_revision( revision )
      end
    end

    nil
  end

  # Instance Methods

  # Acquires (or reaffirms) the editing lock without creating a draft or
  # an autosave -- both are now deferred until there is real content to
  # hold.
  def lock_for_editing! current_user
    if self.lock_owner.nil? || self.lock_owner == current_user
      lock_for! current_user
      if self.draft
        self.draft.user = current_user if self.draft.user.nil?
        self.draft.editor = current_user
        self.draft.save!
      end
      self
    else
      raise(
        LockedByAnotherUser,
        "Page is locked by another user who is working on it! " \
        "Last modification: #{(self.autosave || self.draft || self.head).updated_at.to_fs(:db)}"
      )
    end
  end

  # Creates or updates the autosave buffer from the given attributes.
  # Autosave rows are never associated to the node via node_id -- they
  # must never appear in self.pages / the revisions list, which is the
  # whole reason autosave exists as a separate, unversioned layer.
  def autosave! attributes, current_user
    assert_locked_by! current_user

    unless self.autosave
      self.autosave = Page.create!(:editor => current_user)
      self.autosave.clone_attributes_from(self.draft || self.head) if self.draft || self.head
      self.save!
    end
    self.autosave.assign_attributes(attributes)
    self.autosave.save!
    self.autosave
  end

  # Promotes the current autosave into the draft (creating the draft if
  # none exists yet) and destroys the autosave afterward. This is what
  # the explicit "Save" action does; it never creates a new revision --
  # same as any other in-place draft edit. The new draft is created via
  # self.pages.create! rather than by repointing the autosave's own
  # node_id, because acts_as_list assigns the revision number at create
  # time, scoped to node_id -- a page created with node_id nil and
  # reassigned afterward would carry a wrong or missing revision number.
  def save_draft! current_user
    assert_locked_by! current_user
    return unless self.autosave

    if self.draft
      preserved_published_at = self.draft.published_at
      self.draft.clone_attributes_from self.autosave
      self.draft.published_at = preserved_published_at
      self.draft.user_id = self.autosave.user_id if self.autosave.user_id
      self.draft.editor  = current_user
      self.draft.save!
    else
      empty_page = self.pages.create!
      empty_page.clone_attributes_from self.autosave
      empty_page.user         = self.autosave.user_id ? self.autosave.user : (self.head ? self.head.user : current_user)
      empty_page.editor       = current_user
      empty_page.published_at = self.head.published_at if self.head
      empty_page.save!
      self.draft = empty_page
      self.save!
    end

    self.autosave.destroy
    self.autosave_id = nil
    self.save!
    self.draft.reload
  end

  def resolve_page_reference ref
    case ref.to_s
    when "head" then head
    when "draft" then draft
    when "autosave" then autosave
    else pages.find_by_revision(ref)
    end
  end

  # Which layer-pairs are meaningful to compare right now, given this
  # node's actual state. Head vs autosave only shows up when no draft
  # sits between them -- with a draft present, autosave is compared
  # against the draft, never past it straight to head.
  def available_layer_pairs
    pairs = []
    pairs << [:head, :draft]     if head && draft
    pairs << [:draft, :autosave] if draft && autosave
    pairs << [:head, :autosave]  if head && autosave && !draft
    pairs
  end

  def find_or_create_draft current_user
    self.wipe_draft!
    if draft && self.lock_owner == current_user
      draft
    elsif draft && self.lock_owner.nil?
      lock_for! current_user
      draft.user    = current_user if draft.user.nil?
      draft.editor  = current_user
      draft.save
      draft
    elsif draft && self.lock_owner != current_user
      raise(
        LockedByAnotherUser,
        "Page is locked by another user who is working on it! " \
        "Last modification: #{draft.updated_at.to_fs(:db)}"
      )
    else
      lock_for! current_user
      create_new_draft current_user
    end
  end

  def create_new_draft user
    empty_page        = self.pages.create!
    empty_page.user   = (self.head ? self.head.user : user)
    empty_page.editor = user
    empty_page.save

    empty_page.clone_attributes_from self.head

    self.draft = empty_page
    self.save
    self.draft.reload
  end

  # Discards exactly the topmost non-empty layer -- autosave if present,
  # else draft -- and reveals whatever's beneath it. Releases the lock
  # only once nothing is left to protect (no draft survives); leaves it
  # alone whenever a draft remains, since #edit still has real content
  # open.
  def revert! current_user
    assert_locked_by! current_user

    if self.autosave
      self.autosave.destroy
      self.autosave_id = nil
      self.save!
    elsif self.draft && self.head
      self.draft.destroy
      self.draft_id = nil
      self.save!
    end

    self.unlock! unless self.draft
    self.reload
  end

  def staged_slug=(value)
    if head.blank?
      self.slug = value
    else
      super
    end
  end

  def publish_draft!
    # Return nil if nothing to publish and no staged changes
    return nil unless self.draft || staged_slug || staged_parent_id

    if self.draft
      self.head = self.draft
      self.head.published_at ||= Time.now
      self.head.save!
      self.draft = nil
    end

    if staged_slug && (staged_slug != slug)
      self.slug = staged_slug
      self.staged_slug = nil
    end

    if staged_parent_id && (staged_parent_id != parent_id)
      new_parent = Node.find(staged_parent_id)

      if new_parent == self || self.descendants.include?(new_parent)
        raise ActiveRecord::RecordInvalid.new(self), "Cannot move a node under itself or one of its own descendants"
      end

      self.staged_parent_id = nil
      self.save!
      self.move_to_child_of(new_parent)
    else
      unless self.save
        raise ActiveRecord::RecordInvalid.new(self)
      end
    end

    self.reload
    self.update_unique_name
    self.send(:update_unique_names_of_children)
    self.unlock!
    self
  end

  # Releases whatever's stale and abandoned; never anything actively in
  # use. Three independent cases share one rule -- nothing is touched
  # unless it's been sitting untouched for over a day:
  #  - a lock held with no draft or autosave at all (the editor opened
  #    the page and never actually wrote anything)
  #  - a fresh autosave older than a day, never promoted to a draft
  #  - a draft older than a day that's still identical to head
  def wipe_draft!
    return if self.autosave && self.autosave.updated_at > 1.day.ago

    unless self.draft
      return if self.autosave.nil? && self.locked? && self.updated_at > 1.day.ago
      self.autosave&.destroy
      self.autosave_id = nil
      self.unlock!
      self.save!
      return
    end
    return unless self.head
    return unless self.draft.updated_at < 1.day.ago
    return if self.head.has_changes_to? self.draft

    self.draft.destroy
    self.draft_id = nil
    self.unlock!
    self.save!
    self.reload
  end

  def restore_revision! revision
    if page = self.pages.find_by_revision(revision)
      self.head = page
      self.save
    else
      nil
    end
  end

  # returns an array with all parts of a unique_name rather than a string
  def unique_path
    unique_name.to_s.split("/")
  end

  # returns array with pages up to root excluding root
  def path_to_root
    parent.nil? ? [slug] : parent.path_to_root.push(slug)
  end

  def current_unique_name
    path = path_to_root[1..-1] # excluding root
    self.unique_name = path.join("/")
  end

  def update_unique_name
    current_unique_name
    self.save
  end

  def locked?
    !self.lock_owner.nil?
  end

  def unlock!
    if self.lock_owner
      self.lock_owner = nil
      self.save
      self
    end
  end

  def title
    head ? head.title : draft.title
  end

  def update_unique_names?
    !children.empty? && !children.first.path_to_root.include?(self.slug)
  end

  def head?
    head_id
  end

  def update?
    unique_path.length == 3 && unique_path[0] == "updates"
  end

  def editable_page
    autosave || draft || head
  end

  # Returns immutable node id for all new nodes so that the atom feed entry ids
  # stay the same eventhough the slug or positions changes.
  # Can be removed after a year or so ;)
  def feed_id
    new_id_format_date = "2009-11-14".to_time
    self.created_at < new_id_format_date ? unique_path : id
  end

  # Full-text search across all locale translations using PostgreSQL tsvector.
  # Uses 'simple' dictionary (no stemming, no stopwords) so queries work
  # across German and English content without language detection.
  def self.search(term, _ = {})
    joins(head: :translations)
      .where("page_translations.search_vector @@ plainto_tsquery('simple', ?)", term)
      .distinct
  end

  # This one is for admin-only views, where finding a draft is the point.
  # Substring match on whichever of head/draft is present.
  def self.editor_search(term)
    words = term.to_s.split(/\s+/).reject(&:blank?)
    return none if words.empty?

    conditions = []
    binds = {}

    words.each_with_index do |word, i|
      key = "term#{i}"
      binds[key.to_sym] = "%#{sanitize_sql_like(word)}%"
      conditions << "(head_translations.title ILIKE :#{key} OR head_translations.abstract ILIKE :#{key} " \
                    "OR draft_translations.title ILIKE :#{key} OR draft_translations.abstract ILIKE :#{key})"
    end

    joins("LEFT JOIN page_translations head_translations ON head_translations.page_id = nodes.head_id")
      .joins("LEFT JOIN page_translations draft_translations ON draft_translations.page_id = nodes.draft_id")
      .where(conditions.join(" AND "), binds)
      .distinct
  end

  def self.drafts_and_autosaves(current_user_id: nil)
    scope = where("draft_id IS NOT NULL OR autosave_id IS NOT NULL")
    return scope.order("updated_at DESC") unless current_user_id

    scope.order(
      Arel.sql(sanitize_sql_array(["CASE WHEN locking_user_id = ? THEN 0 ELSE 1 END, updated_at DESC", current_user_id]))
    )
  end

  def self.recently_changed
    includes(:head).where(
      "pages.updated_at < ? AND pages.updated_at > ? AND nodes.parent_id IS NOT NULL",
      Time.now, Time.now - 14.days
    ).order("pages.updated_at desc").references(:head)
  end

  protected
    def lock_for! current_user
      self.lock_owner = current_user
      self.save
    end

    def assert_locked_by! current_user
      return if self.lock_owner == current_user
      raise(
        LockedByAnotherUser,
        "Page is locked by another user who is working on it! " \
        "Last modification: #{(self.autosave || self.draft || self.head).updated_at.to_fs(:db)}"
      )
    end

    # Creates an empty page and associates it to the given node. This means
    # freshly created node has an empty draft. A user can create nodes as he
    # wants to which will not appear on the public page until the author edits
    # that draft and publishes it.
    def initialize_empty_page
      if self.pages.empty?
        self.draft = self.pages.create!
        self.save
      end
    end

    def check_for_changed_slug
      if parent and changed.include? "slug"
        self.unique_name = current_unique_name
      end
    end

    # Watch out recursion ahead! update_unique_name itself triggers this
    # after_save callback which invokes update_unique_name on its children.
    # Hopefully until no childrens occur
    #
    # Queries parent_id directly rather than the NestedTree#children
    # association out of habit from the old awesome_nested_set-avoidance
    # workaround - no longer strictly necessary now that children is
    # equally safe, but left as-is since it already works correctly.
    def update_unique_names_of_children
      unless root?
        Node.where(:parent_id => self.id).each do |child|
          child.reload
          child.update_unique_name
          child.send(:update_unique_names_of_children)
        end
      end
    end
end