Class: Cms::ContentController

Inherits:
ApplicationController
  • Object
show all
Includes:
ActionController::Caching::Actions, ActionController::Caching::Pages
Defined in:
app/controllers/cms/content_controller.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#disable_cachingObject



219
220
221
# File 'app/controllers/cms/content_controller.rb', line 219

def disable_caching
  @allow_caching = false
end

#not_foundObject

Renders app/views/errors/404.rhtml with http status 404 Not Found.

Raises:

  • (ActionController::RoutingError)


55
56
57
58
59
60
61
# File 'app/controllers/cms/content_controller.rb', line 55

def not_found
  # logger.error "404 from #{request.referer}"
  # render :template => 'imagine_cms/errors/404', :status => 404
  
  # let Rails handle 404s natively (override if you want to handle manually)
  raise ActionController::RoutingError.new('404 Not Found')
end

#page_list_calendarObject



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
# File 'app/controllers/cms/content_controller.rb', line 324

def page_list_calendar
  @pg = CmsPage.find(params[:id])
  load_page_objects or return true
  
  @month = (params[:month] || Time.now.month).to_i
  @year = (params[:year] || Time.now.year).to_i
  @key = params[:key]
  first_of_month = Time.mktime(@year, @month, 1)
  last_of_month = first_of_month.end_of_month
  
  @css_prefix = params[:css_prefix] || 'calendar_'
  
  events = page_list_items(@pg, @key, :start_date => first_of_month, :end_date => last_of_month)
  
  @event_days = {}
  events.each do |e|
    if e.
      event_start = e..mday
      if e.article_end_date
        event_end = e.article_end_date > last_of_month ? last_of_month.mday : e.article_end_date.mday
      else
        event_end = event_start
      end
      
      for index in event_start..event_end
        @event_days[index] ||= ''
        @event_days[index] << erb_render(substitute_placeholders(@page_objects["#{@key}-template"], e))
      end
      
    end
  end
  @event_days.each do |index, val|
    @event_days[index] = (@page_objects["#{@key}-header"] || '') + val + (@page_objects["#{@key}-footer"] || '')
  end
  
  render :update do |page|
    page.replace_html "page_list_calendar_#{@key}_month_year", :partial => 'page_list_calendar_month_year'
    page.replace_html "page_list_calendar_#{@key}_days", :partial => 'page_list_calendar_days'
  end
end

#preview_templateObject



310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'app/controllers/cms/content_controller.rb', line 310

def preview_template
  @pg = CmsPage.new
  if params[:id] && (@cms_template = CmsTemplate.find_by_id(params[:id])) && (pg = @cms_template.pages.where('published_version >= 0').order('updated_on desc').first)
    @pg = pg
  else
    @cms_template = CmsTemplate.new(name: 'Template Preview')
    @pg.template = @cms_template
  end
  @page_objects = OpenStruct.new
  @pg.template.content = params[:content]

  render inline: render_cms_page_to_string(@pg, params[:content])
end

#rendering_error(exception = nil) ⇒ Object



63
64
65
66
67
68
69
# File 'app/controllers/cms/content_controller.rb', line 63

def rendering_error(exception = nil)
  logger.error "500 from #{request.referer} (exception: #{exception})"
  logger.error exception.annoted_source_code if exception.class.name == 'ActionView::Template::Error'
  
  @exception = exception.message
  render template: 'imagine_cms/errors/500', status: 500, formats: [ :html ]
end

#rss_feedObject



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
# File 'app/controllers/cms/content_controller.rb', line 268

def rss_feed
  min_time = Time.rfc2822(request.env["HTTP_IF_MODIFIED_SINCE"]) rescue nil
  if min_time && (Time.now - min_time) < 5.minutes
    render plain: '', status: '304 Not Modified' and return
  end
  
  @@cms_page_table_exists ||= CmsPage.table_exists?
  return not_found unless @@cms_page_table_exists
  
  @pg = CmsPage.find_by_id(params[:page_id])
  render nothing: true and return unless @pg && params[:page_list_name]
  key = "obj-page_list-#{params[:page_list_name].gsub(/[^\w]/, '_')}"
  
  load_page_objects or return false
  
  # populate @page_list_pages
  render_cms_page_to_string(@pg)
  
  @pages = @page_list_pages[key].first(20) rescue []  # why only first 20?
  @page_contents = {}
  
  unless @pages.empty?
    @most_recent_pub_date = @pages.first
    @pages.each { |pg| most_recent_pub_date = pg if pg.published_date > @most_recent_pub_date.published_date }
    
    if min_time && @most_recent_pub_date.published_date && @most_recent_pub_date.published_date <= min_time
      # use cached version
      render plain: '', status: '304 Not Modified' and return
    end
    
    @pages.each_with_index do |page, index|
      @page_contents[page.id] = render_to_string :inline => substitute_placeholders(@page_objects["#{key}-template"] || '', page, :index => index+1, :count => @pages.size)
    end
  end
  
  # send feed
  response.headers["Content-Type"] = "application/rss+xml"
  response.headers["Last-Modified"] = (@pages.first.published_date.httpdate rescue Time.now).to_s
  
  render 'rss_feed.xml', :layout => false
end

#searchObject



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
# File 'app/controllers/cms/content_controller.rb', line 224

def search
  @pages = []
  @terms = []
  @terms = params[:q].split(/[^\w\-]+/).reject { |t| t.length < 3 } if params[:q]
  
  unless @terms.empty?
    CmsPage.index_all
    
    base_query = CmsPage.includes(:tags).references(:cms_page_tags).where('published_version >= 0').limit(100)
    
    query = base_query.dup
    @terms.each do |term|
      term_variants = [ term, term.singularize, term.pluralize ].uniq.map { |v| v.gsub(/[\[\]\|\:\>\(\)\?]/, '').gsub(/\+/, '\+') }.join('|')
      query = query.where("(title regexp ?)", "[[:<:]](#{term_variants})[[:>:]]")
    end
    @pages.concat query.all
    
    query = base_query.dup.where('search_index is not null')
    @terms.each do |term|
      term_variants = [ term, term.singularize, term.pluralize ].uniq.map { |v| v.gsub(/[\[\]\|\:\>\(\)\?]/, '').gsub(/\+/, '\+') }.join('|')
      query = query.where("cms_page_tags.name regexp :regex or search_index regexp :regex",
                          regex: "[[:<:]](#{term_variants})[[:>:]]")
    end
    query.each { |pg| @pages << pg unless @pages.include?(pg) }
    
    # fulltext doesn't work with innodb... may need to make a separate myisam
    # table just for search. (this would be better because it would sort by relevance)
    # @pages.concat CmsPage.where('match (title, search_index) against (?)', params[:q])
  end
  @pages = @pages.first(100)
  
  logger.debug "Search returned #{@pages.size} matching pages for terms #{@terms}"
  
  @pg = CmsPage.new
  @pg.template = CmsTemplate.find_by_name('Search') || CmsTemplate.new
  @page_title = 'Search Results'
  
  load_page_objects or return
  
  @page_objects['obj-text-search_results'] = render_to_string(partial: 'search')
  
  render inline: render_cms_page_to_string(@pg)
end

#showObject

Routes: match ‘plcalendar(/:action(/:id))’ => ‘cms/content#page_list_calendar’ root :to => ‘cms/content#show’ match ‘*content_path’ => ‘cms/content#show’



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
# File 'app/controllers/cms/content_controller.rb', line 16

def show
  return not_found unless params[:content_path].is_a? Array
  
  @content_levels = (params[:prefix] || []).concat(params[:content_path])
  @content_path = File.join([ 'content' ].concat(@content_levels))
  template_found = false
  
  # set "legacy" vars
  begin
    if template_exists?(@content_path)
      params[:section] = @content_levels.first unless @content_levels.size < 2
      params[:subsection] = @content_levels[1] unless @content_levels.size < 3
      params[:page] = @content_levels.last
      template_found = true
    elsif template_exists?(File.join([ @content_path, 'index' ]))
      @content_path = File.join([ @content_path, 'index' ])
      params[:section] = @content_levels.first unless @content_levels.size < 1
      params[:subsection] = @content_levels[1] unless @content_levels.size < 2
      params[:page] = 'index'
      template_found = true
    end
  rescue StandardError => e
    if e.message =~ /string contains null byte/
      # do nothing
    else
      raise e
    end
  end
  
  if template_found
    render template: @content_path
  elsif show_from_db
    return
  else
    return not_found
  end
end

#show_from_dbObject



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
# File 'app/controllers/cms/content_controller.rb', line 71

def show_from_db
  @@cms_page_table_exists ||= CmsPage.table_exists?
  return unless @@cms_page_table_exists
  
  logger.debug 'Rendering content from database'
  
  begin
    @content_levels = params[:content_path]
    db_path = params[:content_path]
    edit_mode = false
    @allow_caching = true
    
    # check for /login
    if db_path.last == 'login'
      db_path.pop
      if @pg = CmsPage.find_by_path(db_path.join('/'))
        db_path << 'version'
        db_path << (@pg.published_version <= 0 ? @pg.version : @pg.published_version).to_s
        @allow_caching = false
        
        if is_logged_in_user?
          redirect_to '/' + db_path.join('/') and return true
        else
          flash[:notice] = "Please log in now in order to switch to Preview Mode on the page you were just viewing."
          session[:saved_user_uri] = '/' + db_path.join('/')
          redirect_to controller: '/management/user', action: 'login' and return true
        end
      end
    end
    
    # check for /edit
    if db_path.last == 'edit'
      db_path.pop
      edit_mode = true
      @allow_caching = false
    end
    
    # check for 2-part suffixes (/version/[#], /form/[action])
    test = db_path.last(2)
    
    if test.size == 2
      if test.first == 'version' && test.last.to_i > 0
        params[:version] = db_path.pop
        db_path.pop
        @allow_caching = false
      elsif test.first == 'form'
        @form_action = db_path.pop
        db_path.pop
        @allow_caching = false
        
        # restore saved instance variables
        if session[:saved_instance_variables].is_a? Hash
          session[:saved_instance_variables].each do |k, v|
            instance_variable_set "@#{k}", v
          end
          session[:saved_instance_variables] = nil
        end
      end
    end
    
    # check for 3-part suffixes (/segment/[offset]/[plname])
    test = db_path.last(3)
    
    if test.size == 3
      if test[0] == 'segment' && !test[1].blank? && !test[2].blank?
        @page_list_segment = true
        params[:page_list_name] = db_path.pop
        params[:offset] = db_path.pop
        db_path.pop
        
        # don't cache to disk on server, but do allow browsers and proxies to cache briefly
        @allow_caching = false
        expires_in 1.minutes, public: true if Rails.env.production?
      end
    end
    
    if db_path.last == 'index'
      db_path.pop
      params[:page] = 'index'
    end
    
    if @pg ||= (CmsPage.includes(:template).find_by_path(db_path.join('/')) || CmsPage.includes(:template).find_by_path(db_path.map { |segment| segment.gsub(/([A-Za-z\d])_/, '\1-') }.join('/')))
      if edit_mode
        redirect_to controller: '/manage/cms_pages', action: 'edit_page_content', id: @pg and return true
      else
        # return if page is offline and viewer is not an admin
        if @pg.published_version < 0
          if !is_logged_in_user?
            return false
          else
            # display, but don't cache
            @allow_caching = false
          end
        end
        
        # redirect if redirect enabled
        if @pg.respond_to?(:redirect_enabled) && @pg.redirect_enabled
          redirect_to @pg.redirect_to and return true
        end
        
        # load appropriate page version and associated objects
        # if we had to authenticate, load_page_objects = false, but return true so we don't call not_found
        load_page_objects or return true
        
        # set "legacy" vars
        params[:section] = @content_levels.size < 1 ? '' : @content_levels.first
        params[:subsection] = @content_levels[1] unless @content_levels.size < 3
        if @content_levels.size == 1
          params[:page] = 'index'
        elsif @content_levels.size > 1
          params[:page] = @content_levels.last
        end
        
        @page_title = @pg.title
        
        template_content = render_cms_page_to_string(@pg)
        
        # logger.debug @page_objects.map { |k,v| "#{k}: #{v}\n" }
        
        # this is kind of ugly, having this in the middle of my rendering code
        if @page_list_segment
          name = params[:page_list_name]
          key = "obj-page_list-#{name.gsub(/[^\w]/, '_')}"
          render inline: render_page_list_segment(name, @page_list_pages[key]) and return true
        end
        # end of page list segment code
        
        render inline: template_content
        
        if UseCmsPageCaching && @allow_caching && perform_caching && request.format == Mime[:html]
          cache_page(nil, nil, nil)
        end
        
        return true
      end
    end
  rescue ActionController::RoutingError
    # no need to log this
  rescue StandardError => e
    logger.error "Error rendering from db: #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
    rendering_error(e) and return true
  end
  
  # if we haven't rendered something from the db by now, return false
  false
end