Class: NodesController

Inherits:
ApplicationController show all
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::App

included

Instance Method Details

#asearchObject

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



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

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



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

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.



367
368
369
370
371
372
373
374
375
376
# File 'app/controllers/nodes_controller.rb', line 367

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



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

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.to_s)}"
  end
  redirect_to "/" + ([prefix]+params[:path]).flatten.join('/') + (query_params_list == [] ? '' : "?#{query_params_list.join('&')}")
end

#clear_orderObject



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'app/controllers/nodes_controller.rb', line 586

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



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

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).
    zip = attrs.delete('parent_zip')
    parent = visitor.find_node(nil, zip, nil, request, true)
    
    @node = parent.new_child(attrs, false)
    if visitor.exec_acl && !(@node.kpath =~ %r{^#{visitor.exec_acl.create_kpath}})
      # Document creation can change initial klass depending on mime type. Make sure it is still allowed.
      @node.errors.add('klass', 'Not allowed')
    else
      @node.save
    end
  rescue ActiveRecord::RecordNotFound
    # Let normal processing insert errors
    @node = Node.new
    @node.errors.add('base', 'Not allowed')
  end
  @node.errors.add('file', file_error) if file_error

  if params[Zena::Use::Upload::UPLOAD_KEY]
    # Respond in parent from iframe.
    return render_upload
  end
  
  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], :new => 'true')
      }
      format.js do
        if params[:zjs]
          attrs = {'id' => @node.zip}
          params[:node].each do |k,v|
            v = @node.zafu_eval(k, params[:opts])
            attrs[k] = v
          end
          render :json => attrs.to_json, :status => :created
        end
      end
      format.xml  { render :xml => @node.to_xml(:root => 'node'), :status => :created, :location => node_url(@node) }
    else
      # ERROR
      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 do
        if params[:zjs]
          render :json => @node.errors, :status => :unprocessable_entity
        end
      end
      format.xml  { render :xml => @node.errors, :status => :unprocessable_entity }
    end
  end
end

#destroyObject



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

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 do
      
      if params[:zjs]
        node_json = @node.to_json
        if @node.destroy
          render :json => node_json, :status => 200
        else
          render :json => @node.errors, :status => :unprocessable_entity
        end
      else
        @parent = @node.parent
        @node.destroy
        # update_page_content(page, @parent)
      end
    end

  end
end

#dropObject

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



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

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)



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

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



412
413
414
# File 'app/controllers/nodes_controller.rb', line 412

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



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

def find
  search
end

#importObject

import sub-nodes from a file



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

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



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

def index
  if @node = secure(Node) { Node.find(current_site.home_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)


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

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 ?



561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'app/controllers/nodes_controller.rb', line 561

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



362
363
364
# File 'app/controllers/nodes_controller.rb', line 362

def save_text
  update
end

#searchObject

Find nodes starting from root node



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

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



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

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.v_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
        
        # content_path is used to cache by creating a symlink
        cache_ok = cache_page(:content_path  => content_path, :authenticated => @node.v_public?)
        
        if content_path
          if @node.v_public? && cache_ok
            # This is the simplest working solution to save cached version and use apache for serving (all xsendfile and such do not work with video streaming).
            redirect_to data_path(@node, :mode => params[:mode]) + "?1"
          else
            # 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
        end
      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



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

def update
  @node = visitor.find_node(nil, params[:id], nil, request, true)

  if params[:link_id]
    @link = Link.find_through(@node, params[:link_id])
  end
  
  params['node'] ||= {}
  file, file_error = get_attachment
  params['node']['file'] = file if file
  # Make sure we load the correct version for edited v_lang
  lang = params['node']['v_lang'] || visitor.lang
  @node.version(lang)
  @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 do
        @flash = flash
        if params[:zjs]
          if @node.errors.empty?
            attrs = {}
            params[:node].each do |k,v|
              v = @node.zafu_eval(k, params[:opts])
              attrs[k] = v
            end
            render :json => attrs.to_json, :status => :ok
          else
            render :json => @node.errors, :status => :unprocessable_entity
          end
        end
      end

      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. Enables using POST in JS for large text preview. Seen as ‘read’ in ACL.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'app/controllers/nodes_controller.rb', line 117

def zafu
  # We allow preview by using POST requests (long text in js) but they should appear as 'GET' in 
  # find_node.
  request.method = 'GET' if request.method == 'POST'
  
  @node = visitor.find_node(nil, params[:id], nil, request)

  if params[:link_id]
    @link = Link.find_through(@node, params[:link_id])
  end
  
  # security risk with ACL (change an object before display with extended rights). Must check no ACL before
  # preview. Only enable with proper security if this is really needed.
  # if params['node']
  #   @node.attributes = secure(Node) {Node.transform_attributes(params['node'], @node, true)}
  # end
  respond_to do |format|
    format.js { render :action => 'show' }
  end
end