Class: NodesController

Inherits:
ApplicationController show all
Includes:
Zena::Use::Grid::ControllerMethods
Defined in:
app/controllers/nodes_controller.rb

Overview

Url

basepath          class and zip   optional mode   format

/projects/art/    project24       _print          .html

Examples:

/current/art/project24.html            << a project inside the 'art' page
/note24.html                           << a Note's page
/note24_print.html                     << a Note in 'print' mode
/current/art.html                      << 'art' page (this page has custom base set, this means no class or zip shown)
/current/art_print.html                << 'art' page in 'print' mode
/current/art/project24/image28.html    << image page (for comments, etc)
/current/art/project24/image28.jpg     << full image data
/current/art/project24/image28_pv.jpg  << image in the 'pv' image format
/current/art/project24/image28_print.html << image page in 'print' mode

Instance Method Summary collapse

Methods included from Zena::Use::Grid::ControllerMethods

#cell_edit, #cell_update, #table_update

Methods included from Zena::Use::Grid::Common

#get_table_from_json

Methods included from Zena::App

included

Instance Method Details

#asearchObject

this should not be needed.… but format.js never gets called otherwize.



107
108
109
110
111
112
113
# File 'app/controllers/nodes_controller.rb', line 107

def asearch
  do_search
  respond_to do |format|
    #format.html { render_and_cache :mode => 'search' }
    format.js { render :action => 'search'}
  end
end

#attributeObject

AJAX HELPER TODO: test



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
# File 'app/controllers/nodes_controller.rb', line 429

def attribute
  method = params[:attr]
  if (params[:pseudo_id] || params[:name]).blank? || !%w{title text summary name path short_path}.include?(method)
    # Error
    render :text => ''
    return
  end

  if id_query = params[:pseudo_id]
    # '+' are not escaped as they should in ajax query
    id_query.sub!(/ +$/) {|spaces| '+' * spaces.length }
    node_id = secure!(Node) { Node.translate_pseudo_id(id_query, :id, @node)}
    @node = secure!(Node) { Node.find(node_id) }
  elsif name_query = params[:name]
    # Get attribute by name
    # TODO: test
    if name_query =~ /^(.*)\.[a-z]{2,3}$/
      name_query = $1
    end

    conditions = [[]]

    if kpath = params[:kpath]
      conditions[0] << "kpath LIKE ?"
      conditions << "#{kpath}%"
    end

    name_query = "#{name_query}%"
    @node = secure!(Node) { Node.find_by_title(name_query, :conditions => conditions, :order => "zip DESC", :like => true)}
  end

  if %w{path short_path}.include?(method)
    path = @node.send(method)
    render :text => path.join('/ ')
  else
    @text = @node.send(method)
    if %w{text summary}.include?(method)
      render :text => "<%= zazen(@text) %>"
    else
      render :text => @text
    end
  end
rescue ActiveRecord::RecordNotFound
  render :text => (params[:pseudo_id] ? _('node not found') : _('new'))
end

#backupObject

Create a backup copy of the current redaction.



306
307
308
309
310
311
312
313
314
315
# File 'app/controllers/nodes_controller.rb', line 306

def backup
  version = secure_write!(Version) { Version.find(params[:id]) }
  @node   = version.node
  @node.backup
  if @node.errors.empty?
    flash.now[:notice] = _("Backup created.")
  else
    flash.now[:error] = _("Could not create backup.")
  end
end

#catch_allObject

Render badly formed urls



51
52
53
54
55
56
57
58
# File 'app/controllers/nodes_controller.rb', line 51

def catch_all
  query_params_list = []
  query_params.each do |k,v|
    next if v.kind_of?(Hash) # FIXME: we should support nested hashes. Can't we use something in rails here ?
    query_params_list << "#{k}=#{CGI.escape(v)}"
  end
  redirect_to "/" + ([prefix]+params[:path]).flatten.join('/') + (query_params_list == [] ? '' : "?#{query_params_list.join('&')}")
end

#clear_orderObject



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'app/controllers/nodes_controller.rb', line 503

def clear_order
  kpath = (params[:kpath] || 'ZZ')[0..1]
  allOk = true

  children = secure!(Node) { Node.find(:all, :conditions => ['parent_id = ? AND kpath like ?', @node[:id], "#{kpath}%"])}

  children.each do |child|
    child.position = 0.0
    allOk = child.save && allOk
  end

  if !allOk
    @errors = _('Could not clear order.')
  end

  respond_to do |format|
    format.js
  end
end

#createObject



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
# File 'app/controllers/nodes_controller.rb', line 214

def create
  attrs = params['node']
  file, file_error = get_attachment
  if file
    attrs['file'] = file
    attrs['klass'] = 'Document'
  end

  attrs = secure(Node) { Node.transform_attributes(attrs) }

  begin
    # Make sure we can load parent (also enables ACL to work for us here).
    parent = visitor.find_node(nil, attrs.delete('parent_zip'), nil, request)
    @node = parent.new_child(attrs, false)
    @node.save
  rescue ActiveRecord::RecordNotFound
    # Let normal processing insert errors
    @node = secure!(Node) { Node.create_node(attrs) }
  end
  @node.errors.add('file', file_error) if file_error

  respond_to do |format|
    if @node.errors.empty?
      flash.now[:notice] = 'Node was successfully created.'
      format.html {
        redirect_to  params[:redir] || zen_path(@node, :mode => params[:mode])
      }
      format.js
      format.xml  { render :xml => @node.to_xml(:root => 'node'), :status => :created, :location => node_url(@node) }
    else
      format.html do
        flash[:error] = error_messages_for('node', :object => @node)
        if request.referer
          redirect_to request.referer
        else
          raise ActiveRecord::RecordNotFound
        end
      end
      format.js
      format.xml  { render :xml => @node.errors, :status => :unprocessable_entity }
    end
  end
end

#destroyObject



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
# File 'app/controllers/nodes_controller.rb', line 272

def destroy
  respond_to do |format|
    format.html do
      if @node.destroy
        # These flash messages tend to hang around stupidly
        # flash[:notice] = _("Node destroyed.")
        redirect_to params[:redir] || zen_path(@node.parent)
      else
        flash.now[:notice] = _("Could not destroy node.")
        render :action => 'show'
      end
    end

    format.xml  do
      node_xml = @node.to_xml #need to be allocated before destroying
      if node_xml && @node.destroy
        render :xml => node_xml, :status => 200
      else
        @node.errors.add(:visitor, visitor.) if RAILS_ENV == 'development'
        render :xml => @node.errors, :status => :unprocessable_entity
      end
    end

    format.js

  end
end

#dropObject

This method is called when an element is dropped on a node.



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
# File 'app/controllers/nodes_controller.rb', line 125

def drop
  set       = params[:set]
  other_zip = params[:drop].split('_').last
  other  = secure!(Node) { Node.find_by_zip(other_zip)}

  if attributes = params[:node]
    if params[:node][:id] == '#{id}'
      # swap (a way to preview content by drag & drop)
      @node = other
    elsif params[:change] == 'receiver'
      attributes[:_copy] = other
      @node.update_attributes_with_transformation(attributes)
      if !@node.errors.empty?
        @errors = @node.errors
      end
    else
      attributes[:_copy] = @node
      other.update_attributes_with_transformation(attributes)
      if !other.errors.empty?
        @errors = other.errors
      end
    end
  else
    p = params.dup
    p.delete(:action)
    p.delete(:controller)
    params.merge!(other.replace_attributes_in_values(p))
  end

  respond_to do |format|
    format.js
  end
end

#editObject

modifications of the node itself (dates, groups, revert editions, etc)



259
260
261
262
263
264
265
266
267
268
269
270
# File 'app/controllers/nodes_controller.rb', line 259

def edit
  respond_to do |format|
    format.html do
      @title_for_layout = title_for_layout
    end

    format.js do
      # zafu edit
      render :template => 'nodes/edit.rjs' # FIXME: this should not be needed. Rails bug ?
    end
  end
end

#exportObject



351
352
353
# File 'app/controllers/nodes_controller.rb', line 351

def export
  send_file(@node.archive.path, :filename=>"#{@node.title}.tgz", :type => 'application/x-gzip', :x_sendfile => ENABLE_XSENDFILE)
end

#findObject

Find nodes starting from a given node



102
103
104
# File 'app/controllers/nodes_controller.rb', line 102

def find
  search
end

#importObject

import sub-nodes from a file



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
# File 'app/controllers/nodes_controller.rb', line 318

def import
  defaults = params[:node]
  klass = defaults.delete(:klass)
  if klass == 'Skin' && !defaults.has_key?('v_status')
    defaults['v_status'] = Zena::Status::Pub
  end
  attachment, error = get_attachment
  if error
    responds_to_parent do
      page.replace 'form_errors', error
    end
  else
    # TODO: UploadProgress.setAsProcessing..... would be nice...
    @nodes = secure!(Node) { Node.create_nodes_from_folder(
      :klass    => klass,
      :archive  => attachment,
      :parent   => @node,
      :defaults => defaults
    )}.values
    # parse pseudo_ids
    parse_assets(@nodes)

    responds_to_parent do # execute the redirect in the main window
      render :update do |page|
        page.call 'UploadProgress.setAsFinished'
        page.delay(1) do # allow the progress bar fade to complete
          page.replace_html 'import_tab', :partial => 'import_results'
        end
      end
    end
  end
end

#indexObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/controllers/nodes_controller.rb', line 31

def index
  if @node = secure(Node) { Node.find(current_site.root_id) }
    respond_to do |format|
      format.html { render_and_cache :mode => '+index' }
      format.xml  { render :xml => @node.to_xml }
    end
  elsif base_node = visitor.node_without_secure
    if node = visitor.find_node(nil, base_node.zip, nil, request)
      # If the visitor is acl authorized to view his own node,
      # redirect there.
      redirect_to zen_path(node)
    else
      raise ActiveRecord::RecordNotFound
    end
  else
    raise ActiveRecord::RecordNotFound
  end
end

#not_foundObject

This method is used to test the 404 page when editing zafu templates. It is mapped from ‘/en/404.html’. Look at def Rendering#render_404

Raises:

  • (ActiveRecord::RecordNotFound)


62
63
64
# File 'app/controllers/nodes_controller.rb', line 62

def not_found
  raise ActiveRecord::RecordNotFound
end

#orderObject

TODO: test change the position of the children of the current element. TODO: what happens if not all the children are present due to access rights ?



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'app/controllers/nodes_controller.rb', line 478

def order
  allOK = true
  positions = []
  params.each do |k,v|
    if k =~ /^sort_(.*)/
      positions = v
      break
    end
  end

  positions.each_with_index do |zip,idx|
    child = secure!(Node) { Node.find_by_zip(zip) }
    child.position = idx.to_f + 1.0
    allOk = child.save && allOK
  end

  respond_to do |format|
    if allOK
      format.html { render :text => _('Order updated')}
    else
      format.html { render :text => _('Could not update order.')}
    end
  end
end

#save_textObject

TODO: test



301
302
303
# File 'app/controllers/nodes_controller.rb', line 301

def save_text
  update
end

#searchObject

Find nodes starting from root node



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
# File 'app/controllers/nodes_controller.rb', line 67

def search
  respond_to do |format|
    format.html do
      begin
        do_search
      rescue ::QueryBuilder::Error => err
        flash.now[:error] = err.message
      end
      render_and_cache :mode => '+search', :cache => false
    end

    format.xml do
      begin
        do_search
        if @nodes.kind_of?(Fixnum)
          # count
          render :xml => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<count type=\"integer\">#{@nodes}</count>\n"
        elsif @nodes
          render :xml => Array(@nodes).to_xml(:root => 'nodes')
        else
          render :xml => [].to_xml(:root => 'nodes')
        end
      rescue ::QueryBuilder::Error => err
        render :xml => [{:message => err.message}].to_xml(:root => 'errors'), :status => 401
      end
    end

    format.js do
      do_search
      render :action => 'search'
    end
  end
end

#showObject



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
# File 'app/controllers/nodes_controller.rb', line 159

def show
  respond_to do |format|

    format.html { render_and_cache }

    if !params[:prefix]
      # /nodes/18.xml not treated the same as /en/page18.xml (render_and_cache)
      format.xml { render :xml => @node.to_xml }
    end

    format.any do
      if asset = params[:asset]
        # math rendered as png, ...
        filename     = "#{asset}.#{params[:format]}"
        content_path = @node.asset_path(filename)
        content_type = (Zena::EXT_TO_TYPE[params[:format]] || ['application/octet-stream'])[0]
        send_file(content_path, :filename=>filename, :type => content_type, :disposition=>'inline', :x_sendfile => ENABLE_XSENDFILE)
        cache_page(:content_path => content_path, :authenticated => @node.public?) # content_path is used to cache by creating a symlink
      elsif @node.kind_of?(Document) && params[:format] == @node.ext
        # Get document data (inline if possible)
        content_path = nil

        if @node.kind_of?(Image) && !Zena::Use::ImageBuilder.dummy?
          if img_format = Iformat[params[:mode]]
            content_path = @node.filepath(img_format)
            # force creation of image data
            @node.file(img_format)
          end
        elsif @node.kind_of?(TextDocument)
          send_data(@node.text, :filename => @node.filename, :type => @node.content_type, :disposition => 'inline')
        else
          content_path = @node.filepath
        end

        if content_path
          # FIXME RAILS: remove 'stream => false' when rails streaming is fixed
          send_file(content_path, :filename => @node.filename, :type => @node.content_type, :disposition => 'inline', :stream => false, :x_sendfile => ENABLE_XSENDFILE)
        end

        cache_page(:content_path => content_path, :authenticated => @node.public?) # content_path is used to cache by creating a symlink
      else
        render_and_cache
        # FIXME: redirect to document format should occur in render_and_cache
        #if has skin for format
        #  render_and_cache
        #elsif params[:format] == 'xml'
        #  render :xml => @node.to_xml }
        #else
        #  return redirect_to(zen_path(@node), :mode => params[:mode])
        #end
      end
    end
  end
end

#updateObject



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
# File 'app/controllers/nodes_controller.rb', line 355

def update
  params['node'] ||= {}
  file, file_error = get_attachment
  params['node']['file'] = file if file

  @v_status_before_update = @node.v_status
  @node.update_attributes_with_transformation(params['node'])
  # What is this 'extfile' thing ?
  @node.errors.add('extfile', file_error) if file_error

  if @node.errors.empty?
    flash.now[:notice] = _('node updated')
  else
    flash.now[:error]  = _('could not update')
  end

  if params[:iframe]
    responds_to_parent do # execute the redirect in the iframe's parent window
      render :update do |page|
        page.call "UploadProgress.setAsFinished"
        page.delay(1) do # allow the progress bar fade to complete
          page.redirect_to edit_node_version_path(:node_id => @node[:zip], :id=>(@node.v_number || 0), :close => (params[:validate] ? true : nil))
        end
      end
    end # parent iframe (upload)
  else
    respond_to do |format|
      format.html do
        if @node.errors.empty?
          if params[:edit] == 'popup'
            redirect_to edit_node_version_path(:node_id => @node[:zip], :id => 0, :close => (params[:validate] ? true : nil))
          else
            redirect_to params[:redir] || zen_path(@node, :mode => params[:mode])
          end
        else
          begin
            if request.referer
              route = ActionController::Routing::Routes.recognize_path(request.referer[%r{https?://[^/]+(.*)},1])
            else
              route = {:action => 'show'}
            end
            if route[:action] == 'index'
              mode = '+index'
            elsif route[:action] == 'search'
              mode = '+search'
            elsif path = route[:path]
              if path.last =~ Zena::Use::Urls::ALLOWED_REGEXP
                zip  = $3
                name = $4
                mode = $5 == '' ? nil : $5[1..-1]
              end
            end
          rescue ActionController::RoutingError
            mode = nil
          end
          render_and_cache :mode => mode, :cache => false
        end
      end # html

      format.js { @flash = flash }

      format.xml do
        if @node.errors.empty?
          render :xml => @node.to_xml, :status => :ok, :location => node_url(@node)
        else
          render :xml => @node.errors, :status => :unprocessable_entity
        end
      end # xml
    end
  end
end

#zafuObject

RJS method. show.js not working… ? FIXME: remove.



117
118
119
120
121
122
# File 'app/controllers/nodes_controller.rb', line 117

def zafu
  return self.update if params[:method] == 'put'
  respond_to do |format|
    format.js { render :action => 'show' }
  end
end