Class: Management::CmsController

Inherits:
ApplicationController
  • Object
show all
Defined in:
app/controllers/management/cms_controller.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details



1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
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
# File 'app/controllers/management/cms_controller.rb', line 1013

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.from_file(localfile)
    small.crop_resized(GalleryThumbWidth, GalleryThumbHeight)
    small.write(thumbfile)
    
    File.chmod(0644, localfile, thumbfile)
    
    create_preview_images(:force => 1)
    
  elsif ext == '.zip'
    begin
      Zip::ZipFile.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 Exception => e
          log_error(e)
        end
      end
    rescue Exception => e
      logger.debug params.inspect
      log_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.from_file(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, 1) }
  end
  
  File.delete(data_dest)
  
  upload_progress.message = "File received successfully."
  finish_upload_status "'#{File.basename(data_dest)}'" and return
end

#block_basic_usersObject



38
39
40
41
42
43
44
# File 'app/controllers/management/cms_controller.rb', line 38

def block_basic_users
  return true unless UseCmsAccessLevels
  unless user_has_permission?(:manage_cms_full_access) && @user.cms_allowed_sections.to_s.strip.blank?
    render '/imagine_cms/errors/permission_denied'
    return false
  end
end

#check_permissionsObject



31
32
33
34
35
36
# File 'app/controllers/management/cms_controller.rb', line 31

def check_permissions
  if !user_has_permission?(:manage_cms)
    render '/imagine_cms/errors/permission_denied'
    return false
  end
end


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
875
876
877
878
879
880
881
882
883
884
885
# File 'app/controllers/management/cms_controller.rb', line 836

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.from_file(tempfile)
    if im[:width] > max_width || im[:height] > max_height
      im.resize("#{max_width}x#{max_height}")
    end
    im.write(localfile)
    
    small = MiniMagick::Image.from_file(tempfile)
    small.crop_resized(GalleryThumbWidth, GalleryThumbHeight)
    small.write(thumbfile)
    
    File.chmod(0644, localfile, thumbfile)
    
    begin
      File.unlink(tempfile)
      File.unlink(tempthumbfile)
    rescue Exception => e
      # not that big a deal if we can't delete
    end
  end
  
  begin
    Dir.rmdir(File.join(Rails.root, 'public', @dirname, 'temp'))
  rescue Exception => e
    # not that big a deal if we can't delete
  end
  
  create_preview_images
  
  render :partial => 'complete_gallery'
end


1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
# File 'app/controllers/management/cms_controller.rb', line 1176

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]))
  
  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)
  
  @filename = localfile.split('/').map { |s| CGI::escape(s) }.join('/') + "?#{File.mtime(localfile).to_i}"
  
  render :partial => 'create_file_link'
end

#crop_feature_imageObject



1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
# File 'app/controllers/management/cms_controller.rb', line 1279

def crop_feature_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_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.from_file(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



676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'app/controllers/management/cms_controller.rb', line 676

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.from_file(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



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
1225
# File 'app/controllers/management/cms_controller.rb', line 1195

def crop_thumb
  @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_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.from_file(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


1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'app/controllers/management/cms_controller.rb', line 1145

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



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'app/controllers/management/cms_controller.rb', line 274

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 => 'pages'
end

#delete_photoObject



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
# File 'app/controllers/management/cms_controller.rb', line 1102

def delete_photo
  if request.post?
    gallery_dir = File.join(Rails.root, 'public', 'assets', 'content', params[:path].to_s, params[:gallery_id])
    
    image_id = params[:image].split('.')[0].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') and File.basename(img).split('.')[0].to_i > image_id }
    
    image_names = []
    images.each_with_index { |img, index| image_names << File.basename(img).split('.')[0].to_i }
    image_names.sort!
    
    # create blank captions.yml if it doesn't already exist
    create_captions_file(params[:id])
    captions = YAML.load(File.open(File.join(gallery_dir, 'captions.yml')).read).to_a
    
    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
    
    File.open(File.join(gallery_dir, 'captions.yml'), "w") { |f| f.write(YAML.dump(new_captions)) }
  end
  
  redirect_to :action => 'gallery_management', :id => params[:id], :gallery_id => params[:gallery_id]
end

#disable_cachingObject



630
# File 'app/controllers/management/cms_controller.rb', line 630

def disable_caching ; end

#edit_pageObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'app/controllers/management/cms_controller.rb', line 165

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').uniq.pluck(:name).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(params[:pg])
    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]
    
    save_function = @pg.new_record? ? 'save' : 'save_without_revision'
    
    if @pg.send(save_function)
      # now try to save tags
      # begin
        existing_tags = @pg.tags.map(&:name)
        tags_to_delete = @pg.tags.all
        params[:tags].split(',').map(&:strip).reject(&:blank?).each do |t|
          if existing_tags.include?(t)
            # still in use, don't 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 }
      # rescue Exception => e
      #   logger.debug e
      # end
      
      # now try to save page objects (just attributes in this case)
      # begin
        objects_to_delete = @pg.objects.where("obj_type = 'attribute' or obj_type = 'option'").all
        
        (params[:page_objects] || {}).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
        
        objects_to_delete.each { |t| t.destroy }
      # rescue Exception => e
      #   logger.debug e
      # end
      
      render :update do |page|
        case params[:return_to]
        when 'preview'
          page.redirect_to "#{@pg.path.blank? ? '' : '/' + @pg.path}/version/#{@pg.published_version > 0 ? @pg.published_version : @pg.version}"
        else
          flash[:notice] = 'Page saved.'
          session[:cms_pages_path] = @pg.path
          page.redirect_to :action => 'pages'
        end
      end
      
    else
      # save failed, display errors
      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



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
# File 'app/controllers/management/cms_controller.rb', line 336

def edit_page_content
  @pg = CmsPage.find(params[:id])
  validate_user_access or return
  
  @page_objects = HashObject.new(params[:page_objects] || {})
  
  if request.get?
    @pg.revert_to(params[:version]) if params[:version]
    @pg.objects.find(:all, :conditions => [ '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 ||= ''
    @cms_head << "<script type=\"text/javascript\" src=\"#{url_for(:action => 'page_tags_for_lookup')}\"></script>"
    
    @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).all
      
      @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
      
      # 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.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
        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, '')
          
          # pirate styles not welcome
          val.gsub!(/<style>(.*?)<\/style>/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]+(.*?)>/, '')
        end
        
        obj.content = val
        obj.save
      end
      
      old_objs.each do |obj|
        unless @pg.objects.find(:all, :conditions => [ 'name = ? and cms_page_version = ?', obj.name, @pg.version])
          obj = @pg.objects.build(:name => obj.name, :obj_type => obj.type, :content => obj.content)
        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

#edit_snippetObject



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
# File 'app/controllers/management/cms_controller.rb', line 114

def edit_snippet
  @snip = CmsSnippet.find_by_id(params[:id]) || CmsSnippet.new
  
  if request.post?
    @snip.assign_attributes(params[:snip])
    
    begin
      @pg = CmsPage.new
      @page_objects = HashObject.new
      render_to_string :inline => @snip.content
    rescue Exception => e
      message = e.message
      flash.now[:error] = "<pre>#{ERB::Util.html_escape(message)}</pre>".html_safe
      logger.debug e
      return
    end
    
    if !@snip.save
      @error = @snip.errors.full_messages.join('<br/>')
    else
      flash[:notice] = 'Snippet saved.'
      redirect_to :action => 'edit_snippet', :id => @snip.id and return
    end
  end
end

#edit_templateObject



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
# File 'app/controllers/management/cms_controller.rb', line 80

def edit_template
  @temp = CmsTemplate.find_by_id(params[:id]) || CmsTemplate.new
  
  if request.post?
    @temp.assign_attributes(params[:temp])
    
    begin
      @pg = CmsPage.new
      @page_objects = HashObject.new
      render_to_string :inline => @temp.content
    rescue Exception => e
      message = e.message
      flash.now[:error] = "<pre>#{ERB::Util.html_escape(message)}</pre>".html_safe
      logger.debug e
      return
    end
    
    # this must come after the render_to_string so that we capture template
    # options embedded in snippets
    @temp.options = @template_options
    
    if !@temp.save
      flash.now[:error] = @temp.errors.full_messages.join('<br/>')
    else
      flash[:notice] = 'Template saved.'
      redirect_to :action => 'edit_template', :id => @temp.id and return
    end
  end
end


887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# File 'app/controllers/management/cms_controller.rb', line 887

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


806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
# File 'app/controllers/management/cms_controller.rb', line 806

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.exists?(thumbfile)
    
    im = MiniMagick::Image.from_file(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



982
983
984
985
986
987
988
989
990
991
992
993
# File 'app/controllers/management/cms_controller.rb', line 982

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

#indexObject



73
74
# File 'app/controllers/management/cms_controller.rb', line 73

def index
end

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

helpers



581
582
583
584
585
586
587
588
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
621
622
623
624
625
626
627
# File 'app/controllers/management/cms_controller.rb', line 581

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, ''.html_safe, :id => "page_object_config_#{key}")
    content << javascript_tag("addLoadEvent(function () { scanForPageObjects(#{@pg.id}, '#{key}', #{@pg.version}); });")
    content << observe_field("page_objects_#{key}", :function => "scanForPageObjects(#{@pg.id}, '#{key}', #{@pg.version});", :frequency => 2)
    content
  when :page_list
    @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}-item-offset"] ||= 0 unless options[:item_offset]
    @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 }).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



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'app/controllers/management/cms_controller.rb', line 499

def insert_page_object_config
  @pg = CmsPage.find(params[:id])
  
  load_page_objects
  @pg.revert_to(params[:version]) if params[:version]
  @pg.objects.find(:all, :conditions => [ '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



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'app/controllers/management/cms_controller.rb', line 147

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



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'app/controllers/management/cms_controller.rb', line 301

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

#page_attributeObject



329
330
331
332
333
334
# File 'app/controllers/management/cms_controller.rb', line 329

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

#page_attributes_for_lookupObject



530
531
532
533
534
# File 'app/controllers/management/cms_controller.rb', line 530

def page_attributes_for_lookup
  @attrs = CmsPageObject.where(:obj_type => 'attribute').uniq.pluck(:name).sort
  headers['content-type'] = 'text/javascript'
  render :layout => false
end

#page_list_add_folderObject



540
541
542
# File 'app/controllers/management/cms_controller.rb', line 540

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

#page_list_add_tagObject



536
537
538
# File 'app/controllers/management/cms_controller.rb', line 536

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

#page_tags_for_lookupObject



524
525
526
527
528
# File 'app/controllers/management/cms_controller.rb', line 524

def page_tags_for_lookup
  @tags = CmsPageTag.find(:all, :order => 'name').map { |tag| tag.name }.uniq
  headers['content-type'] = 'text/javascript'
  render :layout => false
end

#pagesObject



140
141
142
143
144
145
# File 'app/controllers/management/cms_controller.rb', line 140

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

#receive_fileObject



1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
# File 'app/controllers/management/cms_controller.rb', line 1161

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


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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'app/controllers/management/cms_controller.rb', line 756

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.exists?(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::ZipFile.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::ZipFile.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.from_file(localfile)
        im.write(jpgfile)
        
        File.unlink(localfile) if localfile != jpgfile
        
      rescue Exception => e
        log_error(e)
      end
    end
  end
  
  finish_upload_status "'#{File.basename(localdir)}'"
end

#receive_imageObject



662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'app/controllers/management/cms_controller.rb', line 662

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)
  FileUtils.cp(data.tempfile, localfile)
  
  finish_upload_status "'#{File.basename(localfile)}'"
end

#request_reviewObject



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'app/controllers/management/cms_controller.rb', line 559

def request_review
  @pg = CmsPage.find(params[:id])
  @version = params[:version].to_i
  
  # send email to request administrative review
  # find all users with email address set
  User.find(:all).reject { |u| !u.active? || !u.can_manage_cms_publishing? || !u.cms_allowed_sections.blank? }.each do |u|
    next unless valid_email_address?(u.email_address)
    begin
      Mailer.deliver_cms_request_review(url_for(:controller => '/cms/content', :action => 'show', :content_path => []) + @pg.path, @pg.title, @version, u, @user, params[:change_description].to_s)
    rescue Exception => e
      log_error(e)
    end
  end
  
  render :nothing => true
end

#save_cropObject



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
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'app/controllers/management/cms_controller.rb', line 709

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.from_file(localfile)
  test_im = MiniMagick::Image.from_file(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



1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'app/controllers/management/cms_controller.rb', line 1311

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.from_file(localfile)
  test_im = MiniMagick::Image::from_file(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



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
1271
1272
# File 'app/controllers/management/cms_controller.rb', line 1227

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.from_file(localfile)
  test_im = MiniMagick::Image::from_file(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


927
928
929
930
931
932
933
934
# File 'app/controllers/management/cms_controller.rb', line 927

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


909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'app/controllers/management/cms_controller.rb', line 909

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



292
293
294
295
296
297
298
299
# File 'app/controllers/management/cms_controller.rb', line 292

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


904
905
906
907
# File 'app/controllers/management/cms_controller.rb', line 904

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

#set_page_versionObject



544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'app/controllers/management/cms_controller.rb', line 544

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
      logger.debug @pg.errors.full_messages.inspect
    end
  end
  
  render :nothing => true
end

#show_template_optionsObject



319
320
321
322
323
324
325
326
327
# File 'app/controllers/management/cms_controller.rb', line 319

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

#snippetsObject



110
111
112
# File 'app/controllers/management/cms_controller.rb', line 110

def snippets
  @snippets = CmsSnippet.find(:all, :order => 'name')
end

#sort_imagesObject



936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'app/controllers/management/cms_controller.rb', line 936

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



950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
# File 'app/controllers/management/cms_controller.rb', line 950

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
  
  File.open(File.join(gallery_dir, 'captions.yml'), 'w') { |f| YAML.dump(new_captions, f) }
  session[:gallery_images_sorted] = nil
  
  redirect_to :action => 'gallery_management', :id => @pg, :gallery_id => params[:gallery_id]
end

#templatesObject



76
77
78
# File 'app/controllers/management/cms_controller.rb', line 76

def templates
  @temps = CmsTemplate.find(:all, :order => 'name')
end

#toolbar_editObject

cms toolbars



637
638
639
640
# File 'app/controllers/management/cms_controller.rb', line 637

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

#toolbar_previewObject



642
643
644
645
# File 'app/controllers/management/cms_controller.rb', line 642

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

#update_captionObject



995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'app/controllers/management/cms_controller.rb', line 995

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

#upload_feature_imageObject



1274
1275
1276
1277
# File 'app/controllers/management/cms_controller.rb', line 1274

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

#upload_fileObject



1156
1157
1158
1159
# File 'app/controllers/management/cms_controller.rb', line 1156

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

#upload_imageObject

image upload



651
652
653
654
655
656
657
658
659
660
# File 'app/controllers/management/cms_controller.rb', line 651

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

#upload_thumbObject



1190
1191
1192
1193
# File 'app/controllers/management/cms_controller.rb', line 1190

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

#validate_user_accessObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'app/controllers/management/cms_controller.rb', line 46

def validate_user_access
  unless @user.cms_allowed_sections.to_s.strip.blank?
    allowed_sections = @user.cms_allowed_sections.split(',').map { |s| s.strip }.reject { |s| s.blank? }
    if @pg
      path = '/' + @pg.path
    else
      parent = CmsPage.find_by_id(params[:parent_id] || params[:pg][:parent_id]) rescue nil
      return false if !parent
      path = '/' + parent.path
    end
    
    allowed = false
    allowed_sections.each { |s| allowed ||= (path =~ /^#{s}/) }
    
    if !allowed
      respond_to do |wants|
        wants.js    { render :text => "Sorry, you don't have permission to edit this page."         }
        wants.html  { redirect_to "/#{@pg.path}#{@pg.path == '' ? '' : '/'}version/#{@pg.version}"  }
      end
      return false
    end
  end
  
  return true
end