Class: Manage::CmsPagesController

Inherits:
ApplicationController
  • Object
show all
Includes:
ActionController::Caching::Pages
Defined in:
app/controllers/manage/cms_pages_controller.rb

Instance Method Summary collapse

Instance Method Details



1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'app/controllers/manage/cms_pages_controller.rb', line 1137

def add_to_gallery
  @pg = CmsPage.find_by_id(params[:id])
  galleries_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  @galleries = Dir.entries(galleries_dir).sort
  @gallery_dir = File.join(galleries_dir, params[:gallery_id])    
  images = Dir.glob("#{@gallery_dir}/*-thumb.{jpg,jpeg,png,gif}")
  
  temp_location = File.join(@gallery_dir ,'temp')
  FileUtils.rm_rf(temp_location)
  Dir.mkdir(temp_location)
  
  data = params[:gallery_file][:data]
  data_dest = File.join(temp_location, data.original_filename)
  File.open(data_dest, 'wb') { |f| f.write(data.read) }
  
  last_id = images.size
  ext = File.extname(data_dest).downcase
  
  if ext != '.zip'
    localfile = File.join(@gallery_dir, (last_id + 1).to_s + ext)
    thumbfile = File.join(@gallery_dir, (last_id + 1).to_s + '-thumb' + ext)
    
    File.open(localfile, "w") { |f| f.write(File.open(data_dest).read) }
    
    # create blank captions.yml if it doesn't already exist
    create_captions_file(@pg.id)
    
    localfile = resize_image(localfile)
    
    small = MiniMagick::Image.open(localfile)
    small.crop_resized(GalleryThumbWidth, GalleryThumbHeight)
    small.write(thumbfile)
    
    File.chmod(0644, localfile, thumbfile)
    
    create_preview_images(force: true)
    
  elsif ext == '.zip'
    begin
      Zip::File.foreach(data.path) do |zipentry|
        next if ![ '.jpg', '.jpeg', '.png', '.gif' ].include?(File.extname(zipentry.name).downcase) || zipentry.size < 1000
        upload_progress.message = "Extracting #{File.basename(zipentry.name)}"
        localfile = File.join(temp_location, ((last_id+1).to_s + File.extname(zipentry.name)).downcase)
        
        begin
          zipentry.extract(localfile)
          last_id += 1
        rescue StandardError => e
          logger.error(e)
        end
      end
    rescue StandardError => e
      logger.debug params.inspect
      logger.error(e)
      finish_upload_status "''" and return
    end
    
    @images = Dir.glob("#{temp_location}/*.{jpg,jpeg,png,gif}")
    
    @images.each do |img|
      localfile = File.join(@gallery_dir, File.basename(img, File.extname(img))) + '.jpg'
      tempfile = File.join(temp_location, File.basename(img, File.extname(img))) + File.extname(img)
      thumbfile = File.join(@gallery_dir, File.basename(img, File.extname(img))) + '-thumb.jpg'
      
      small = MiniMagick::Image.open(tempfile)
      small.crop_resized(GalleryThumbWidth, GalleryThumbHeight)
      small.write(thumbfile)
      
      FileUtils.cp(tempfile, localfile)
      resize_image(localfile)
      
      File.chmod(0644, localfile, thumbfile)
    end
    
    # smaller images for gallery index
    management_dir = File.join(@gallery_dir, 'management')
    
    preview_images = []
    Dir.glob("#{@gallery_dir}/*.{jpg,jpeg,png,gif}").each { |img| preview_images << img unless File.basename(img).include?('thumb') }
    
    preview_images.each { |img| create_preview_image(img, management_dir, true) }
  end
  
  File.delete(data_dest)
  
  upload_progress.message = "File received successfully."
  finish_upload_status "'#{File.basename(data_dest)}'" and return
end


957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
# File 'app/controllers/manage/cms_pages_controller.rb', line 957

def complete_gallery
  @pg = CmsPage.find(params[:id])
  target_dir = File.join('assets', 'content', @pg.path)
  @dirname = File.join(target_dir, File.basename(params[:dirname]))
  @thumbs = session[:gallery_thumbs_ordered]
  max_width = params[:max_width].to_i
  max_width = GalleryMaxWidth unless max_width > 0
  max_height = params[:max_height].to_i
  max_height = GalleryMaxHeight unless max_height > 0
  
  create_captions_file(@pg.id, { :gallery_id => File.basename(params[:dirname]) })
  
  @thumbs.each_with_index do |thumb, index|
    thumb.gsub!(/-thumb/, '')
    tempfile = File.join(Rails.root, 'public', @dirname, 'temp', thumb + '.jpg')
    tempthumbfile = File.join(Rails.root, 'public', @dirname, 'temp', thumb + '-thumb.jpg')
    
    localfile = File.join(Rails.root, 'public', @dirname, (index+1).to_s + '.jpg')
    thumbfile = File.join(Rails.root, 'public', @dirname, (index+1).to_s + '-thumb.jpg')
    
    im = MiniMagick::Image.open(tempfile)
    if im[:width] > max_width || im[:height] > max_height
      im.resize("#{max_width}x#{max_height}")
    end
    im.write(localfile)
    
    small = MiniMagick::Image.open(tempfile)
    small.crop_resized(GalleryThumbWidth, GalleryThumbHeight)
    small.write(thumbfile)
    
    File.chmod(0644, localfile, thumbfile)
    
    begin
      File.unlink(tempfile)
      File.unlink(tempthumbfile)
    rescue StandardError => e
      # not that big a deal if we can't delete
    end
  end
  
  begin
    Dir.rmdir(File.join(Rails.root, 'public', @dirname, 'temp'))
  rescue StandardError => e
    # not that big a deal if we can't delete
  end
  
  create_preview_images
  
  render :partial => 'complete_gallery'
end


690
691
692
693
694
695
696
697
698
699
700
# File 'app/controllers/manage/cms_pages_controller.rb', line 690

def create_file_link
  @pg = CmsPage.find_by_id(params[:id])
  localfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, File.basename(params[:filename]))
  @filename = localfile.split('/').map { |s| CGI::escape(s) }.join('/') + "?#{File.mtime(localfile).to_i}"
  
  bucket = ImagineCmsConfig['amazon_s3'][Rails.env]['file_bucket'] rescue nil
  prefix = ImagineCmsConfig['amazon_s3']['file_prefix'] rescue nil
  upload_to_s3(localfile, @pg, bucket, prefix)
  
  render :partial => 'create_file_link'
end

#crop_feature_imageObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 795

def crop_feature_image
  @pg = CmsPage.find_by_id(params[:id])
  origfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, File.basename(params[:filename]))
  newfilename = File.basename(params[:filename], File.extname(params[:filename])) + '-feature' + File.extname(params[:filename])
  localfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, newfilename)
  FileUtils.mv(origfile, localfile)
  
  # get out now if user clicked finish
  if params[:next_clicked].to_i != 1
    @image_file = localfile + "?#{File.mtime(localfile).to_i}"
    upload_to_s3(localfile, @pg)
    render :partial => 'crop_results_feature_image' and return
  end
  
  
  # if we're still here... let's crop!
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(localfile, File.extname(localfile))) + '-croptest' + File.extname(localfile)
  
  # make a smaller version to help with cropping
  im = MiniMagick::Image.open(localfile)
  im.resize("500x400>")
  im.write(testfile)
  File.chmod(0644, testfile)
  
  @width = im[:width]
  @height = im[:height]
  @height = 1 if @height == 0
  @image_file = File.basename(testfile)
  @aspect_ratio = @width.to_f/@height
  
  render :partial => 'crop_feature_image'
end

#crop_imageObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 589

def crop_image
  @pg = CmsPage.find_by_id(params[:id])
  localfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, File.basename(params[:filename]))
  File.chmod(0644, localfile)
  
  # get out now if user clicked finish
  if params[:next_clicked].to_i != 1
    @image_file = localfile + "?#{File.mtime(localfile).to_i}"
    upload_to_s3(localfile, @pg)
    
    render :partial => 'crop_results' and return
  end
  
  
  # if we're still here... let's crop!
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(localfile, File.extname(localfile))) + '-croptest' + File.extname(localfile)
  
  # make a smaller version to help with cropping
  im = MiniMagick::Image.open(localfile)
  im.resize "500x400>"
  im.write(testfile)
  File.chmod(0644, testfile)
  
  @width = im[:width]
  @height = im[:height]
  @height = 1 if @height == 0
  @image_file = File.basename(testfile)
  @aspect_ratio = @width.to_f/@height
  
  render :partial => 'crop_image'
end

#crop_thumbObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 708

def crop_thumb
  @pg = CmsPage.find_by_id(params[:id])
  origfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, File.basename(params[:filename]))
  newfilename = File.basename(params[:filename], File.extname(params[:filename])) + '-thumb' + File.extname(params[:filename])
  localfile = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, newfilename)
  FileUtils.mv(origfile, localfile)
  File.chmod(0644, localfile)
  
  # get out now if user clicked finish
  if params[:next_clicked].to_i != 1
    @image_file = localfile + "?#{File.mtime(localfile).to_i}"
    upload_to_s3(localfile, @pg)
    render :partial => 'crop_results_thumb' and return
  end
  
  
  # if we're still here... let's crop!
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(localfile, File.extname(localfile))) + '-croptest' + File.extname(localfile)
  
  # make a smaller version to help with cropping
  im = MiniMagick::Image.open(localfile)
  im.resize("500x400>")
  im.write(testfile)
  File.chmod(0644, testfile)
  
  @width = im[:width]
  @height = im[:height]
  @height = 1 if @height == 0
  @image_file = File.basename(testfile)
  @aspect_ratio = @width.to_f/@height
  
  render :partial => 'crop_thumb'
end


1272
1273
1274
1275
1276
1277
1278
1279
1280
# File 'app/controllers/manage/cms_pages_controller.rb', line 1272

def delete_gallery
  @pg = CmsPage.find_by_id(params[:id])
  galleries_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  gallery_dir = File.join(galleries_dir, params[:gallery_id])
  
  FileUtils.rm_rf(gallery_dir)
  
  redirect_to :action => 'select_gallery', :id => params[:id]
end

#delete_pageObject



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'app/controllers/manage/cms_pages_controller.rb', line 151

def delete_page
  @pg = CmsPage.find_by_id(params[:id])
  
  if !@pg
    flash[:error] = "Sorry, couldn't find the requested page."
  elsif @pg.children.size > 0
    flash[:error] = "This page contains other pages. Please delete those first if you are sure you want to delete this page."
  elsif @pg.id == 1
    flash[:error] = "You cannot delete the home page."
  else
    flash[:notice] = "Page deleted."
    session[:cms_pages_path] = @pg.parent.path rescue nil
    @pg.destroy
  end
  
  redirect_to action: 'index'
end

#delete_photoObject



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
# File 'app/controllers/manage/cms_pages_controller.rb', line 1226

def delete_photo
  if request.post?
    @pg = CmsPage.find_by_id(params[:id])
    
    # create blank captions.yml if it doesn't already exist
    create_captions_file(@pg.id)
    
    gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, params[:gallery_id])
    captions = YAML.load(File.open(File.join(gallery_dir, 'captions.yml')).read).to_a
    
    image_id = params[:image].split('.').first.to_i
    
    begin ; File.delete(File.join(gallery_dir, image_id.to_s + '.jpg')) ; rescue ; end
    begin ; File.delete(File.join(gallery_dir, image_id.to_s + '-thumb.jpg')) ; rescue ; end
    begin ; File.delete(File.join(gallery_dir, 'management', image_id.to_s + '.jpg')) ; rescue ; end
    
    all_images = Dir.glob(File.join(gallery_dir, '*.{jpg,jpeg,png,gif}'))
    images = []
    all_images.each { |img| images << img if !File.basename(img).include?('thumb') && File.basename(img).split('.').first.to_i > image_id }
    
    image_names = []
    images.each_with_index { |img, index| image_names << File.basename(img).split('.').first.to_i }
    image_names.sort!
    
    new_captions = []
    for i in 0...image_id do
      new_captions[i] = captions[i] || ''
    end
    
    image_names.each do |img|
      FileUtils.mv(File.join(gallery_dir, img.to_s + '.jpg'), File.join(gallery_dir, image_id.to_s + '.jpg'))
      FileUtils.mv(File.join(gallery_dir, img.to_s + '-thumb.jpg'), File.join(gallery_dir, image_id.to_s + '-thumb.jpg'))
      FileUtils.mv(File.join(gallery_dir, 'management', img.to_s + '.jpg'), File.join(gallery_dir, 'management', image_id.to_s + '.jpg'))
      
      new_captions[image_id] = captions[img] || ''
      
      image_id += 1
    end
    
    yaml = YAML.dump(new_captions)
    File.open(File.join(gallery_dir, 'captions.yml'), "w") { |f| f << yaml }
  end
  
  redirect_to :action => 'gallery_management', :id => params[:id], :gallery_id => params[:gallery_id]
end

#disable_cachingObject



536
# File 'app/controllers/manage/cms_pages_controller.rb', line 536

def disable_caching ; end

#edit_pageObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 47

def edit_page
  @pg = CmsPage.find_by_id(params[:id])
  validate_user_access or return
  @pg ||= CmsPage.new
  
  @parent = @pg.parent || CmsPage.find_by_id(params[:parent_id])
  if @parent
    @pg.parent ||= @parent
    @pg.template ||= @parent.template
  end
  
  @attrs = CmsPageObject.where(obj_type: 'attribute').pluck(:name).uniq.sort
  @taglist = CmsPageTag.pluck(:name).uniq.sort
  
  if params[:mode] == 'ajax_new' || params[:mode] == 'ajax_edit'
    @pg.published_version = -1 if params[:mode] == 'ajax_new'
    load_page_objects
    load_template_options
    render :partial => 'edit_page' and return
  end
  
  if request.post?
    params[:pg] ||= {}
    
    if params[:pg][:article_date_year]
      params[:pg][:article_date] = Time.zone.parse("#{params[:pg].delete(:article_date_year)}-#{params[:pg].delete(:article_date_month)}-#{params[:pg].delete(:article_date_day)}")
    end
    if params[:pg][:article_end_date_year]
      params[:pg][:article_end_date] = Time.zone.parse("#{params[:pg].delete(:article_end_date_year)}-#{params[:pg].delete(:article_end_date_month)}-#{params[:pg].delete(:article_end_date_day)}")
    end
    if params[:pg][:published_date_year]
      params[:pg][:published_date] = Time.zone.parse("#{params[:pg].delete(:published_date_year)}-#{params[:pg].delete(:published_date_month)}-#{params[:pg].delete(:published_date_day)}")
    end
    if params[:pg][:expires]
      date = Time.zone.parse("#{params[:pg].delete(:expiration_date_year)}-#{params[:pg].delete(:expiration_date_month)}-#{params[:pg].delete(:expiration_date_day)}")
      params[:pg][:expiration_date] = date if params[:pg][:expires] == 'true'
    end
    
    @pg.assign_attributes(cms_page_params)
    unless params[:use_article_date_range].to_i > 0
      @pg.article_end_date = nil
    end
    @pg.updated_by ||= session[:user_id]
    @pg.updated_by_username ||= session[:user_username]
    @pg.published_version = 0 if @pg.respond_to?(:redirect_enabled) && @pg.redirect_enabled
    
    if @pg.send(@pg.new_record? ? :save : :save_without_revision)
      # now try to save tags
      existing_tags = @pg.tags.map(&:name)
      tags_to_delete = [] ; @pg.tags.each { |t| tags_to_delete << t }
      params[:tags].split(',').map(&:strip).reject(&:blank?).each do |t|
        if existing_tags.include?(t)
          # still in use, don't delete
          tags_to_delete = tags_to_delete.reject { |tag| tag.name == t }
        else
          # doesn't exist, create
          @pg.tags.create(name: t)
        end
      end
      tags_to_delete.each { |t| t.destroy }
      
      # now try to save page objects (just attributes in this case)
      objects_to_delete = @pg.objects.where("obj_type = 'attribute' or obj_type = 'option'").to_a
      
      params[:page_objects].to_unsafe_h.each do |key, val|
        next if val.blank?
        
        if key =~ /^obj-(\w+?)-(.+?)$/
          obj = @pg.objects.where(name: $2, obj_type: $1).first
          obj ||= @pg.objects.build(name: $2, obj_type: $1)
          obj.content = val
          obj.save!
          objects_to_delete.reject! { |obj| obj.name == $2 }
        end
      end if params[:page_objects]
      
      objects_to_delete.each { |t| t.destroy }
      
      case params[:return_to]
      when 'preview'
        render :update do |page|
          page.redirect_to "#{@pg.path.blank? ? '' : '/' + @pg.path}/version/#{@pg.published_version > 0 ? @pg.published_version : @pg.version}"
        end
      else
        flash[:notice] = 'Page saved.'
        session[:cms_pages_path] = @pg.path
        render :update do |page|
          page.redirect_to action: 'index'
        end
      end
      
    else
      # save failed, display errors
      logger.error "Save failed: #{CmsPage.without_revision { @pg.save }} #{@pg.errors.full_messages.join('; ')}"
      render :update do |page|
        page.replace_html 'save_errors', @pg.errors.full_messages.join('<br>')
        page << "try { $('btn_next').disabled = false; } catch (e) {}"
        page << "try { $('btn_finish').disabled = false; } catch (e) {}"
        page << "try { $('btn_save').disabled = false; $('btn_save').value = 'Save'; } catch (e) {}"
      end and return
    end
  end
end

#edit_page_contentObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 213

def edit_page_content
  @pg = CmsPage.find(params[:id])
  validate_user_access or return
  
  @page_objects = params[:page_objects] ? OpenStruct.new(params[:page_objects].to_unsafe_h) : OpenStruct.new
  
  if request.get?
    @pg.version = params[:version] if params[:version] && params[:version].to_i != @pg.version
    @pg.objects.where(cms_page_version: @pg.version).each do |obj|
      key = "obj-#{obj.obj_type.to_s}-#{obj.name}"
      @page_objects[key] = obj.content.html_safe
    end
    
    # set "legacy" vars
    @content_levels = @pg.path.split('/')
    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
    
    @cms_head ||= ''
    @taglist = CmsPageTag.pluck(:name).uniq.sort
    
    @template_content = substitute_placeholders(@pg.template.content, @pg)
    render layout: 'application'
  
  elsif request.post?
    CmsPage.transaction do
      # need to revise this later if we implement deletion of page objects
      old_objs = @pg.objects.where(cms_page_version: @pg.version).to_a
      
      @pg.updated_by = session[:user_id]
      @pg.updated_by_username = session[:user_username]
      
      # if basic user, make sure published version is not set to 'latest'
      if (UseCmsAccessLevels && !user_has_permission?(:manage_cms_full_access)) && @pg.published_version == 0
        @pg.published_version = @pg.version
      end
      
      @pg.updated_on = Time.now.utc
      @pg.save  # create a new version for new page objects to reference
      
      # do a little bit of classification... for now, just identify page lists
      page_lists = []
      @page_objects.each do |key,val|
        key =~ /^obj-(\w+?)-(\w+?)-sources-tag-count$/
        if $1 == 'page_list'
          page_lists << "obj-#{$1}-#{$2}"
        end
      end
      
      # run through page lists and do a little housekeeping
      page_lists.each do |key|
        # optimize source lists: tags
        if @page_objects["#{key}-sources-tag-count"].to_i > 0
          tags = []
          @page_objects["#{key}-sources-tag-count"].to_i.times do |i|
            logger.debug "Adding tag: #{@page_objects["#{key}-sources-tag#{i}"]}"
            tags << @page_objects["#{key}-sources-tag#{i}"]
          end
          tags.reject! { |tag| tag.blank? }
          @page_objects["#{key}-sources-tag-count"] = tags.size
          tags.each_with_index do |tag, i|
            @page_objects["#{key}-sources-tag#{i}"] = tag
          end
        end
        
        # optimize source lists: folders
        if @page_objects["#{key}-sources-folder-count"].to_i > 0
          folders = []
          @page_objects["#{key}-sources-folder-count"].to_i.times do |i|
            logger.debug "Adding folder: #{@page_objects["#{key}-sources-folder#{i}"]}"
            folders << @page_objects["#{key}-sources-folder#{i}"]
          end
          folders.reject! { |folder| folder.blank? }
          @page_objects["#{key}-sources-folder-count"] = folders.size
          folders.each_with_index do |folder, i|
            @page_objects["#{key}-sources-folder#{i}"] = folder
          end
        end
        
        # consolidate date picker fields
        if @page_objects["#{key}-date-range-custom-start_year"]
          @page_objects["#{key}-date-range-custom-start"] = 
            Time.utc(@page_objects.delete("#{key}-date-range-custom-start_year"),
                        @page_objects.delete("#{key}-date-range-custom-start_month"),
                        @page_objects.delete("#{key}-date-range-custom-start_day"))
        end
        if @page_objects["#{key}-date-range-custom-end_year"]
          @page_objects["#{key}-date-range-custom-end"] = 
            Time.utc(@page_objects.delete("#{key}-date-range-custom-end_year"),
                        @page_objects.delete("#{key}-date-range-custom-end_month"),
                        @page_objects.delete("#{key}-date-range-custom-end_day"))
        end
      end
      
      @page_objects.to_h.each do |key,val|
        key =~ /^obj-(\w+?)-(.+?)$/
        obj = @pg.objects.build(name: $2, obj_type: $1)
        
        # do a little bit of "censorship" to fix up Word pastes and strange things from the editor
        if val.is_a?(String)
          # all meta and link tags
          val.gsub!(/(<\/?)(meta|link)(.*?)>/m, '')
          
          # the dreaded MsoNormal
          val.gsub!(' class="MsoNormal"', '')
          
          # remove all font-family/font-size css styles, as well as font tags
          val.gsub!(/font-(?:family|size):.*?(;|")/, '\3')
          val.gsub!(/<font.*?>(.*?)<\/font>/, '\1')
          
          # strange conditional IE stuff
          val.gsub!(/<!--\[if(.*?)<!(--)?\[endif\]-->/m, '')
          
          # not even sure what these are supposed to be
          val.gsub!(/<xml>(.*?)<\/xml>/m, '')
          
          # images pointing to the local drive??
          val.gsub!(/<img src="file:(.*?)>/, '')
          
          # miscellany
          val.gsub!('<!--StartFragment-->', '')
          val.gsub!('<!--EndFragment-->', '')
          val.gsub!(/<span style="(?:;*)">(.*?)<\/span>/m, '\1')
          val.gsub!(' style="(?:;*)"', '')
          val.gsub!('<b></b>', '')
          
          # we could try to catch all strange ms tags...
          #val.gsub!(/(<\/?)(?:o|u1):p>/, '\1p>')
          #val.gsub!(/(<\/?)(?:st1):(.*?)>/, '')
          
          # but it's easier just remove all tags with colons in them
          val.gsub!(/(<\/?)[\w\d]+:[\w\d]+(.*?)>/, '')
          
          
          ### other non-ms word specific stuff ###
          
          # pirate styles not welcome
          val.gsub!(/<style(?:.*?)>(.*?)<\/style>/m, '')
          
          # fix strange <br>s from the editor
          val.gsub!(/<br>(<\/h\d>|<\/p>)/, '\1')
        end
        
        obj.content = val.to_s.force_encoding("UTF-8")
        obj.save!
      end
      
      old_objs.each do |obj|
        unless @pg.objects.where(name: obj.name, cms_page_version: @pg.version)
          obj = @pg.objects.build(name: obj.name, obj_type: obj.type, content: obj.content)
          obj.save!
        end
      end
      
      # update index for searching
      @pg.update_index
      @pg.save_without_revision
    end
    
    redirect_to "/#{@pg.path}#{@pg.path == '' ? '' : '/'}version/#{@pg.version}"
  end
end


1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'app/controllers/manage/cms_pages_controller.rb', line 1008

def gallery_management
  @pg = CmsPage.find_by_id(params[:id])
  galleries_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  @galleries = Dir.glob("#{galleries_dir}/gallery_*")
  gallery_dir = File.join(galleries_dir, params[:gallery_id].to_s)
  
  @images = Dir.glob("#{gallery_dir}/*.{jpg,jpeg,png,gif}").reject { |img| img.include?('thumb') }.map { |img| File.basename(img).split('.').first.to_i }.sort
  
  create_preview_images
  
  if params[:gallery_id]
    @gallery = load_gallery_settings_from_file(params[:gallery_id])
  end
  
  render :layout => false
end


927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# File 'app/controllers/manage/cms_pages_controller.rb', line 927

def gallery_setup
  @pg = CmsPage.find_by_id(params[:id])
  target_dir = File.join('assets', 'content', @pg.path)
  @dirname = File.join(target_dir, File.basename(params[:dirname]), 'temp')
  Dir.chdir(File.join(Rails.root, 'public'))
  @images = Dir.glob("#{@dirname}/*.{jpg,jpeg,png,gif}").sort
  Dir.chdir(Rails.root)
  @thumbs = []
  
  @images.each do |img|
    next if img.include?('-thumb')
    
    thumbfile = File.join(Rails.root, 'public', @dirname, File.basename(img, File.extname(img))) + '-thumb.jpg'
    @thumbs << File.join(@dirname, File.basename(img, File.extname(img))) + '-thumb.jpg'
    
    next if File.exist?(thumbfile)
    
    im = MiniMagick::Image.open(File.join(Rails.root, 'public', img))
    im.resize "80x80" # hardcoded!
    im.write(thumbfile)
    File.chmod(0644, thumbfile)
  end
  
  @thumbs.sort! { |a,b| File.basename(a, File.extname(a)).to_i <=> File.basename(b, File.extname(b)).to_i }
  session[:gallery_thumbs_ordered] = @thumbs.map { |thumb| File.basename(thumb, File.extname(thumb)) }
  
  render :partial => 'gallery_setup'
end

#image_detailsObject



1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
# File 'app/controllers/manage/cms_pages_controller.rb', line 1104

def image_details
  @pg = CmsPage.find_by_id(params[:id])
  
  # create blank captions.yml if it doesn't already exist
  create_captions_file(@pg.id)
  
  gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, params[:gallery_id])
  captions = YAML.load(File.open(File.join(gallery_dir, 'captions.yml')).read)
  image_id = params[:image].split('.').first.to_i
  @caption = captions[image_id]
  
  render partial: 'image_details'
end

#indexObject



15
16
17
18
19
20
# File 'app/controllers/manage/cms_pages_controller.rb', line 15

def index
  @page_levels = [ '' ].concat((params[:path] || session[:cms_pages_path] || '').split('/').reject { |l| l.blank? })
  @page_levels << ''
  @path = ''
  @page = nil
end

#insert_object(name, type = :text, options = {}, html_options = {}) ⇒ Object

helpers



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 459

def insert_object(name, type = :text, options = {}, html_options = {})
  extend ActionView::Helpers::FormHelper
  extend ActionView::Helpers::JavaScriptHelper
  extend ActionView::Helpers::PrototypeHelper
  extend ActionView::Helpers::TagHelper
  extend ActionView::Helpers::TextHelper
  
  key = "obj-#{type.to_s}-#{name.gsub(/[^\w]/, '_')}"
  @page_objects[key] ||= ''
  
  case type.to_sym
  when :string
    @page_objects[key] = options[:content] if @page_objects[key].blank?
    text_field(:page_objects, key, options)
  when :text
    @page_objects[key] = options[:content] if @page_objects[key].blank?
    focusOnLoad = !defined?(@cms_text_editor_placed)
    @cms_text_editor_placed = true
    content = ''.html_safe
    content << text_area(:page_objects, key,
                         { dojoType: 'Editor2', toolbarGroup: 'main', isToolbarGroupLeader: 'false',
                           focusOnLoad: focusOnLoad.to_s, style: 'border: 2px dashed gray; padding: 5px',
                           minHeight: '100px' }.update(html_options))
    content << (:div, '', id: "page_object_config_#{key}")
    script_tag = <<-EOT
      <script type="text/javascript">
        window.addEventListener('load', (event) => {
          setInterval(function() {
            scanForPageObjects(#{@pg.id}, '#{key}', #{@pg.version});
          }, 1000);
        });
      </script>
      EOT
    content << script_tag.html_safe
    content
  when :page_list
    # set defaults unless values are present in template
    @page_objects["#{key}-min-item-count"] ||= 3 unless options[:item_min_count]
    @page_objects["#{key}-max-item-count"] ||= 5 unless options[:item_count]
    @page_objects["#{key}-sort-first-field"] ||= options[:primary_sort_key]
    @page_objects["#{key}-sort-first-direction"] ||= options[:primary_sort_direction]
    @page_objects["#{key}-sort-second-field"] ||= options[:secondary_sort_key]
    @page_objects["#{key}-sort-second-direction"] ||= options[:secondary_sort_direction]
    
    render_to_string(partial: 'page_list', locals: { name: name, key: key, options: options }).html_safe
  when :snippet
    @snippet = CmsSnippet.find_by_name(name)
    if @snippet
      erb_render(substitute_placeholders(@snippet.content, @pg))
    else
      'Could not find snippet "' + name + '" in the database.'
    end
  else
    "Unknown object type: #{type.to_s}"
  end
end

#insert_page_object_configObject



383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'app/controllers/manage/cms_pages_controller.rb', line 383

def insert_page_object_config
  @pg = CmsPage.find(params[:id])
  
  load_page_objects
  @pg.revert_to(params[:version]) if params[:version]
  @pg.objects.where(cms_page_version: @pg.version).each do |obj|
    key = "obj-#{obj.obj_type.to_s}-#{obj.name}"
    @page_objects[key] = obj.content
  end
  
  name = params[:name]
  render :nothing => true and return unless name
  
  parent_key = params[:parent_key]
  type = params[:type]
  render :nothing => true and return unless type == 'page_list'
  
  key = "obj-#{type}-#{name.gsub(/[^\w]/, '_')}"
  
  render :update do |page|
    page.insert_html :bottom, "page_object_config_#{parent_key}", :partial => 'page_list',
                                                                  :locals => { :name => name, :key => key }
  end
end

#list_pagesObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/controllers/manage/cms_pages_controller.rb', line 29

def list_pages
  @page_level = params[:level].to_i
  @parent = CmsPage.find_by_id(params[:parent_id])
  
  if @page_level == 0
    render :partial => 'list_page', :locals => { :list_page => CmsPage.find(1) } and return
  else
    if @parent
      @pages = @parent.children
      session[:cms_pages_path] = @parent.path
    else
      @pages = nil
    end
  end
  
  render :partial => 'list_pages'
end

#list_pages_selectObject



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'app/controllers/manage/cms_pages_controller.rb', line 178

def list_pages_select
  @page_level = params[:level].to_i
  @parent = CmsPage.find_by_id(params[:parent_id])
  
  if @page_level == 0
    render :partial => 'list_page_select', :locals => { :list_page_select => CmsPage.find(1) } and return
  else
    if @parent
      @pages = @parent.children
      session[:cms_pages_path] = @parent.path
    else
      @pages = nil
    end
  end
  
  render :partial => 'list_pages_select'
end

#newObject



22
23
24
25
26
27
# File 'app/controllers/manage/cms_pages_controller.rb', line 22

def new
  validate_user_access or return
  @pg ||= CmsPage.new

  edit_page
end

#page_attributeObject



206
207
208
209
210
211
# File 'app/controllers/manage/cms_pages_controller.rb', line 206

def page_attribute
  render :nothing => true and return unless params[:name]
  
  @page_objects = OpenStruct.new({ params[:name] => params[:value] })
  render :partial => 'page_attribute', :locals => { :name => params[:name] }
end

#page_list(name, options = {}, html_options = {}) ⇒ Object Also known as: pagelist



524
525
526
# File 'app/controllers/manage/cms_pages_controller.rb', line 524

def page_list(name, options = {}, html_options = {})
  insert_object(name, :page_list, options, html_options)
end

#page_list_add_folderObject



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

def page_list_add_folder
  render :partial => 'page_list_source_folder', :locals => { :i => params[:i], :key => params[:key] }
end

#page_list_add_tagObject



408
409
410
# File 'app/controllers/manage/cms_pages_controller.rb', line 408

def page_list_add_tag
  render :partial => 'page_list_source_tag', :locals => { :i => params[:i], :key => params[:key] }
end

#receive_fileObject



675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'app/controllers/manage/cms_pages_controller.rb', line 675

def receive_file
  @pg = CmsPage.find_by_id(params[:id])
  
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  FileUtils.mkdir_p target_dir
  
  data = params[:file][:data]
  original_filename = data.original_filename.strip.gsub(/[\?\s\/\:\\]+/, '-').gsub(/^-/, '').gsub(/-$/, '')
  localfile = File.join(target_dir, original_filename)
  FileUtils.cp(data.tempfile, localfile)
  File.chmod(0644, localfile)
  
  finish_upload_status "'#{File.basename(localfile)}'"
end


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
# File 'app/controllers/manage/cms_pages_controller.rb', line 877

def receive_gallery
  @pg = CmsPage.find_by_id(params[:id])
  
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  FileUtils.mkdir_p target_dir
  
  count = 1
  localdir = File.join(target_dir, 'gallery_1')
  while File.exist?(localdir) && count < 100
    count += 1
    localdir = File.join(target_dir, "gallery_#{count}")
  end
  FileUtils.mkdir_p File.join(localdir, 'temp')
  
  data = params[:gallery_file][:data]
  # read zip file
  
  entries = []
  Zip::File.foreach(data.path) do |zipentry|
    next if ![ '.jpg', '.jpeg', '.png', '.gif' ].include?(File.extname(zipentry.name).downcase) || zipentry.size < 1000
    next if File.basename(zipentry.name) =~ /^\._/
    
    entries << zipentry
  end
  entries.sort! { |a,b| File.basename(a.name).downcase <=> File.basename(b.name).downcase }
  
  Zip::File.open(data.path) do |zipfile|
    entries.each_with_index do |zipentry, index|
      upload_progress.message = "Extracting #{File.basename(zipentry.name)}"
      ext = File.extname(zipentry.name)
      localfile = File.join(localdir, 'temp', (index+1).to_s + ext.downcase)
      jpgfile = File.join(localdir, 'temp', (index+1).to_s + '.jpg')
      
      begin
        zipentry.extract(localfile)
        
        im = MiniMagick::Image.open(localfile)
        im.write(jpgfile)
        
        File.unlink(localfile) if localfile != jpgfile
        
      rescue StandardError => e
        logger.error(e)
      end
    end
  end

  render json: { filename: File.basename(localdir) }.to_json
end

#receive_imageObject



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'app/controllers/manage/cms_pages_controller.rb', line 568

def receive_image
  @pg = CmsPage.find_by_id(params[:id])
  
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  FileUtils.mkdir_p target_dir
  
  data = params[:file][:data]
  original_filename = data.original_filename.strip.gsub(/[\?\s\/\:\\]+/, '-').gsub(/^-/, '').gsub(/-$/, '')
  localfile = File.join(target_dir, original_filename)
  
  im = MiniMagick::Image.open(data.path())
  if im['dimensions'][0] > CmsImageMaxWidth || im['dimensions'][1] > CmsImageMaxHeight
    im.resize "#{CmsImageMaxWidth}x#{CmsImageMaxHeight}"
    im.write(localfile)
  else
    FileUtils.cp(data.path(), localfile)
  end
  
  render json: { filename: File.basename(localfile) }.to_json
end

#request_reviewObject



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'app/controllers/manage/cms_pages_controller.rb', line 430

def request_review
  @pg = CmsPage.find(params[:id])
  @version = params[:version].to_i
  
  # send email to request administrative review
  emails = []
  
  User.find_each do |u|
    next unless u.active? && valid_email_address?(u.email_address)              # must be active and have valid email address
    next unless u.can_manage_cms_publishing? && u.cms_allowed_sections.blank?   # and have permission to publish
    emails << ImagineCmsMailer.request_review(url_for(controller: '/cms/content', action: 'show', content_path: @pg.path.split('/')), @pg.title, @version, u, @user, params[:change_description].to_s)
  end
  
  # email delivery could may fail, catch exceptions here
  emails.each do |email|
    begin
      email.deliver_now
    rescue StandardError => e
      logger.error(e)
    end
  end

  render plain: 'success'
end

#save_cropObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 622

def save_crop
  @pg = CmsPage.find_by_id(params[:id])
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(params[:filename]))
  localfile = testfile.split(/-croptest/).join('')
  
  # need to scale up requested position/dimensions based on how big test image
  # is relative to original image
  orig_im = MiniMagick::Image.open(localfile)
  test_im = MiniMagick::Image.open(testfile)
  scale = orig_im[:width].to_f / test_im[:width]
  
  x1 = params[:image][:x1].to_i * scale
  y1 = params[:image][:y1].to_i * scale
  width = params[:image][:width].to_i * scale
  height = params[:image][:height].to_i * scale
  
  max_width = params[:image][:max_width].to_i
  max_height = params[:image][:max_height].to_i
  dirty = false
  
  # crop if user selected something
  if params[:image][:width].to_i > 0
    logger.debug "cropping @ (#{x1}, #{y1}) to size #{width} x #{height}"
    orig_im.crop "#{width}x#{height}+#{x1}+#{y1}"
    dirty = true
  end
  
  # resize if the resultant image is bigger than max dims
  if max_width > 0 && max_height > 0
    if orig_im[:width] > max_width || orig_im[:height] > max_height
      logger.debug "resizing to max dims #{max_width} x #{max_height}"
      orig_im.resize "#{max_width}x#{max_height}"
      dirty = true
    end
  end
  
  orig_im.write(localfile) if dirty
  File.chmod(0644, localfile)
  
  @image_file = localfile + "?#{File.mtime(localfile).to_i}"
  File.unlink testfile
  upload_to_s3(localfile, @pg)
  
  render :partial => 'crop_results'
end

#save_crop_feature_imageObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 829

def save_crop_feature_image
  @pg = CmsPage.find_by_id(params[:id])
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(params[:filename]))
  localfile = testfile.split(/-croptest/).join('')
  
  # need to scale up requested position/dimensions based on how big test image
  # is relative to original image
  orig_im = MiniMagick::Image.open(localfile)
  test_im = MiniMagick::Image.open(testfile)
  scale = orig_im[:width].to_f / test_im[:width]
  
  x1 = params[:image][:x1].to_i * scale
  y1 = params[:image][:y1].to_i * scale
  width = params[:image][:width].to_i * scale
  height = params[:image][:height].to_i * scale
  
  max_width = params[:image][:max_width].to_i
  max_height = params[:image][:max_height].to_i
  dirty = false
  
  # crop if user selected something
  if params[:image][:width].to_i > 0
    logger.debug "cropping @ (#{x1}, #{y1}) to size #{width} x #{height}"
    orig_im.crop("#{width}x#{height}+#{x1}+#{y1}")
    dirty = true
  end
  
  # resize if the resultant image is bigger than max dims
  if max_width > 0 && max_height > 0
    if orig_im[:width] > max_width || orig_im[:height] > max_height
      logger.debug "resizing to max dims #{max_width} x #{max_height}"
      orig_im.resize("#{max_width}x#{max_height}>")
      dirty = true
    end
  end
  
  orig_im.write(localfile) if dirty
  File.chmod(0644, localfile)
  
  @image_file = localfile + "?#{File.mtime(localfile).to_i}"
  File.unlink testfile
  upload_to_s3(localfile, @pg)
  
  render :partial => 'crop_results_feature_image'
end

#save_crop_thumbObject



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
# File 'app/controllers/manage/cms_pages_controller.rb', line 743

def save_crop_thumb
  @pg = CmsPage.find_by_id(params[:id])
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  testfile = File.join(target_dir, File.basename(params[:filename]))
  localfile = testfile.split(/-croptest/).join('')
  
  # need to scale up requested position/dimensions based on how big test image
  # is relative to original image
  orig_im = MiniMagick::Image.open(localfile)
  test_im = MiniMagick::Image.open(testfile)
  scale = orig_im[:width].to_f / test_im[:width]
  
  x1 = params[:image][:x1].to_i * scale
  y1 = params[:image][:y1].to_i * scale
  width = params[:image][:width].to_i * scale
  height = params[:image][:height].to_i * scale
  
  max_width = params[:image][:max_width].to_i
  max_height = params[:image][:max_height].to_i
  dirty = false
  
  # crop if user selected something
  if params[:image][:width].to_i > 0
    logger.debug "cropping @ (#{x1}, #{y1}) to size #{width} x #{height}"
    orig_im.crop("#{width}x#{height}+#{x1}+#{y1}")
    dirty = true
  end
  
  # resize if the resultant image is bigger than max dims
  if max_width > 0 && max_height > 0
    if orig_im[:width] > max_width || orig_im[:height] > max_height
      logger.debug "resizing to max dims #{max_width} x #{max_height}"
      orig_im.resize("#{max_width}x#{max_height}>")
      dirty = true
    end
  end
  
  orig_im.write(localfile) if dirty
  File.chmod(0644, localfile)
  
  @image_file = localfile + "?#{File.mtime(localfile).to_i}"
  File.unlink testfile
  upload_to_s3(localfile, @pg)
  
  render :partial => 'crop_results_thumb'
end


1048
1049
1050
1051
1052
1053
1054
1055
# File 'app/controllers/manage/cms_pages_controller.rb', line 1048

def save_gallery_settings
  if request.post?
    @pg = CmsPage.find_by_id(params[:id])
    save_gallery_settings_to_file(params[:gallery_id], params[:gallery])
    
    render :nothing => true
  end
end


1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
# File 'app/controllers/manage/cms_pages_controller.rb', line 1030

def select_gallery
  @pg = CmsPage.find_by_id(params[:id])
  @target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  @galleries = Dir.glob("#{@target_dir}/gallery_*")
  
  create_preview_images
  
  if request.post?
    unless params[:gallery_id].downcase == "new"
      redirect_to :action => 'gallery_management', :id => @pg, :gallery_id => params[:gallery_id]
    else
      render :partial => 'upload_image'
    end
  else
    render :partial => 'select_gallery'
  end
end

#select_pageObject



169
170
171
172
173
174
175
176
# File 'app/controllers/manage/cms_pages_controller.rb', line 169

def select_page
  @page_levels = [ '' ].concat((params[:path].blank? ? session[:cms_pages_path] : params[:path]).to_s.split('/').reject { |l| l.blank? })
  @page_levels << ''
  @path = ''
  @page = nil
  
  render :layout => false
end


1025
1026
1027
1028
# File 'app/controllers/manage/cms_pages_controller.rb', line 1025

def set_gallery_order
  session[:gallery_thumbs_ordered] = params[:image_sorter]
  render :nothing => true
end

#set_page_versionObject



416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'app/controllers/manage/cms_pages_controller.rb', line 416

def set_page_version
  if (UseCmsAccessLevels && user_has_permission?(:manage_cms_publishing) || user_has_permission?(:manage_cms_full_access)) || user_has_permission?(:manage_cms)
    if params[:id] && params[:pg]
      @pg = CmsPage.find(params[:id])
      validate_user_access or return
      @pg.published_version = params[:pg][:published_version]
      @pg.update_index
      @pg.save_without_revision
    end
  end
  
  render plain: 'success'
end

#show_template_optionsObject



196
197
198
199
200
201
202
203
204
# File 'app/controllers/manage/cms_pages_controller.rb', line 196

def show_template_options
  @pg = CmsPage.find_by_id(params[:id]) || CmsPage.new
  @pg.cms_template_id = params[:template_id]
  
  load_page_objects
  load_template_options
  
  render partial: 'template_options'
end

#snippet(name, options = {}, html_options = {}) ⇒ Object



530
531
532
# File 'app/controllers/manage/cms_pages_controller.rb', line 530

def snippet(name, options = {}, html_options = {})
  insert_object(name, :snippet, options, html_options)
end

#sort_imagesObject



1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'app/controllers/manage/cms_pages_controller.rb', line 1057

def sort_images
  @pg = CmsPage.find_by_id(params[:id])
  gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, params[:gallery_id])
  
  @images = Dir.glob("#{gallery_dir}/*.{jpg,jpeg,png,gif}").reject { |img| img.include?('thumb') }.map { |img| File.basename(img).split('.').first.to_i }.sort
  
  if params[:images]
    session[:gallery_images_sorted] = params[:images]
    render :nothing => true
  else    
    render :partial => 'sort_images'
  end
end

#sort_images_saveObject



1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'app/controllers/manage/cms_pages_controller.rb', line 1071

def sort_images_save
  @pg = CmsPage.find_by_id(params[:id])
  gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, params[:gallery_id])
  temp_dir = File.join(gallery_dir, 'temp')
  sorted_images = session[:gallery_images_sorted] || []
  
  if sorted_images == []
    redirect_to :action => 'gallery_management', :id => @pg, :gallery_id => params[:gallery_id]
    return
  end
  
  # create blank captions.yml if it doesn't already exist
  create_captions_file(@pg.id)
  
  original_captions = YAML.load_file(File.join(gallery_dir, 'captions.yml')).to_a
  new_captions = [ original_captions[0] ]
  
  Dir.glob("#{gallery_dir}/**/*.jpg").each { |img| FileUtils.touch(img); FileUtils.mv(img, img + '.tmp') }
  
  sorted_images.each_with_index do |img, i|
    FileUtils.mv(File.join(gallery_dir, "#{img.to_i}.jpg.tmp"), File.join(gallery_dir, "#{i+1}.jpg"))
    FileUtils.mv(File.join(gallery_dir, "#{img.to_i}-thumb.jpg.tmp"), File.join(gallery_dir, "#{i+1}-thumb.jpg"))
    FileUtils.mv(File.join(gallery_dir, 'management', "#{img.to_i}.jpg.tmp"), File.join(gallery_dir, 'management', "#{i+1}.jpg"))
    new_captions << original_captions[img.to_i] || ''
  end
  
  yaml = YAML.dump(new_captions)
  File.open(File.join(gallery_dir, 'captions.yml'), 'w') { |f| f << yaml }
  session[:gallery_images_sorted] = nil
  
  redirect_to :action => 'gallery_management', :id => @pg, :gallery_id => params[:gallery_id]
end

#text_editor(name, options = {}, html_options = {}) ⇒ Object Also known as: texteditor

shortcuts



518
519
520
# File 'app/controllers/manage/cms_pages_controller.rb', line 518

def text_editor(name, options = {}, html_options = {})
  insert_object(name, :text, options, html_options)
end

#toolbar_editObject

cms toolbars



543
544
545
546
# File 'app/controllers/manage/cms_pages_controller.rb', line 543

def toolbar_edit
  @pg = CmsPage.find_by_id(params[:id])
  render :layout => false
end

#toolbar_previewObject



548
549
550
551
# File 'app/controllers/manage/cms_pages_controller.rb', line 548

def toolbar_preview
  @pg = CmsPage.find_by_id(params[:id])
  render :layout => false
end

#update_captionObject



1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# File 'app/controllers/manage/cms_pages_controller.rb', line 1118

def update_caption
  if request.post?
    @pg = CmsPage.find_by_id(params[:id])
    
    # create blank captions.yml if it doesn't already exist
    create_captions_file(@pg.id)
    
    gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path, params[:gallery_id])
    captions = YAML.load_file(File.join(gallery_dir, 'captions.yml')).to_a
    image_id = params[:image].split('.').first.to_i
    captions[image_id] = params[:caption]
    
    yaml = YAML.dump(captions)
    File.open(File.join(gallery_dir, 'captions.yml'), "w") { |f| f << yaml }
  end
  
  redirect_to action: 'gallery_management', id: params[:id], gallery_id: params[:gallery_id]
end

#upload_feature_imageObject



790
791
792
793
# File 'app/controllers/manage/cms_pages_controller.rb', line 790

def upload_feature_image
  @pg = CmsPage.find_by_id(params[:id])
  render :partial => 'upload_feature_image'
end

#upload_fileObject



670
671
672
673
# File 'app/controllers/manage/cms_pages_controller.rb', line 670

def upload_file
  @pg = CmsPage.find_by_id(params[:id])
  render :partial => 'upload_file'
end

#upload_imageObject

image upload



557
558
559
560
561
562
563
564
565
566
# File 'app/controllers/manage/cms_pages_controller.rb', line 557

def upload_image
  @pg = CmsPage.find_by_id(params[:id])
  target_dir = File.join(Rails.root, 'public', 'assets', 'content', @pg.path)
  
  if File.exist?(target_dir)
    redirect_to action: 'select_gallery', id: @pg, gallery_id: params[:gallery_id]
  else
    render partial: 'upload_image'
  end
end

#upload_thumbObject



703
704
705
706
# File 'app/controllers/manage/cms_pages_controller.rb', line 703

def upload_thumb
  @pg = CmsPage.find_by_id(params[:id])
  render :partial => 'upload_thumb'
end