Class: PrintController

Inherits:
ApplicationController show all
Defined in:
app/controllers/print_controller.rb

Overview

Mapfish print controller with access control and servlet call

Defined Under Namespace

Classes: JavaError, MapfishError

Constant Summary collapse

TMP_PREFIX =
"#{PRINT_TMP_PATH}/mfPrintTempFile"
TMP_SUFFIX =
".pdf"
TMP_PURGE_SECONDS =
600
OUTPUT_FORMATS =
["pdf", "png", "jpg", "tif", "gif"]
MAPFISH_PRINT_OUTPUT_FORMATS =
["pdf", "png", "tif", "gif", "bmp"]

Instance Method Summary collapse

Constructor Details

#initializePrintController

Returns a new instance of PrintController.



27
28
29
# File 'app/controllers/print_controller.rb', line 27

def initialize
  @configFile = "#{Rails.root}/print/config.yaml"
end

Instance Method Details

#add_filter(topic_name, layer) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
# File 'app/controllers/print_controller.rb', line 265

def add_filter(topic_name, layer)
  filters = Wms.access_filters(current_ability, current_user, topic_name, layer["layers"])
  if filters.any?
    filters.each do |key, value|
      # remove existing filter
      layer["customParams"].delete(key)
      # add serverside filter
      layer["customParams"][key] = value
    end
  end
end

#add_sld_body(topic, layer) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'app/controllers/print_controller.rb', line 244

def add_sld_body(topic, layer)
  # add SLD for selection
  unless layer["customParams"]["SELECTION[LAYER]"].blank?
    sellayer = topic.layers.find_by_name(layer["customParams"]["SELECTION[LAYER]"])
    if sellayer.nil?
      logger.info "Selection layer '#{layer["customParams"]["SELECTION[LAYER]"]}' not found in topic '#{topic.name}'"
      return
    end
    sld_body = Wms.sld_selection(sellayer,
      layer["customParams"]["SELECTION[PROPERTY]"],
      layer["customParams"]["SELECTION[VALUES]"].split(',')
    )
    layer["customParams"]["SLD_BODY"] = sld_body

    # remove non-WMS params
    layer["customParams"].delete("SELECTION[LAYER]")
    layer["customParams"].delete("SELECTION[PROPERTY]")
    layer["customParams"].delete("SELECTION[VALUES]")
  end
end

#createObject



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'app/controllers/print_controller.rb', line 93

def create
  unless check_permissions
    head :forbidden
    return
  end

  cleanupTempFiles

  # remove Rails params
  controller = request.parameters.delete('controller')
  request.parameters.delete('action')
  request.parameters.delete('format')
  request.parameters.delete(controller) unless controller.nil?

  accessible_topics = Topic.accessible_by(current_ability).collect{ |topic| topic.name }
  layers_to_delete = []
  request.parameters["layers"].each do |layer|
    if layer["baseURL"] # WMS layers
      topic_name = File.basename(URI.parse(layer["baseURL"]).path)
      if accessible_topics.include?(topic_name)
        # rewrite URL for local WMS, use CGI if layer filter is used
        use_cgi = !layer["customParams"].nil? && layer["customParams"].any? { |param, value| param =~ LAYER_FILTER_REGEX }
        layer["baseURL"] = rewrite_wms_uri(layer["baseURL"], use_cgi)
        if layer["customParams"] #Set map_resolution for mapserver (MapFish print bug?)
          layer["customParams"].delete("DPI")
          layer["customParams"]["map_resolution"] = request.parameters["dpi"]
        end

        topic = Topic.find_by_name(topic_name)
        add_sld_body(topic, layer)
        add_filter(topic_name, layer)

        # For permission check in WMS controller: pass session as WMS request parameter
        #layer["customParams"]["session"] =
      else
        # collect inaccessible layers for later removal
        layers_to_delete << layer
      end
    end

    if layer["baseURL"].nil? && layer["styles"] #Vector layers
      layer["styles"].each_value do |style| #NoMethodError (undefined method `each_value' for [""]:Array):
        if style["externalGraphic"]
          style["externalGraphic"].gsub!(LOCAL_GRAPHICS_HOST, '127.0.0.1')
          style["externalGraphic"].gsub!(/^https:/, 'http:')
          style["externalGraphic"].gsub!(/^\//, 'http://127.0.0.1/')
        end
      end
    end
  end
  # remove inaccessible layers
  request.parameters["layers"] -= layers_to_delete

  request.parameters["pages"].each do |page|
    # round center coordinates
    page["center"].collect! {|coord| (coord * 100.0).round / 100.0  }
    # round extent coordinates
    page["extent"].collect! {|coord| (coord * 100.0).round / 100.0  } unless page["extent"].nil?
    # add blank user strings if missing
    page["user_title"] = " " if page["user_title"].blank?
    page["user_comment"] = " " if page["user_comment"].blank?
    # base url
    page["base_url"] = "#{request.protocol}#{request.host}"
    # disclaimer
    topic = Topic.accessible_by(current_ability).where(:name => page["topic"]).first
    page["disclaimer"] = topic.nil? ? Topic.default_print_disclaimer : topic.print_disclaimer
  end

  report = request.parameters["layout"]
  if print_templates.include?(report)
    # Mapfish
    print_params = convert_mapfish_v2_params(request.parameters)
    output_format = print_params["outputFormat"]

    # add any custom params
    set_custom_print_params(report, print_params)

    # create report
    temp, temp_id = mapfish_print(print_params)

    # send link to print result
    respond_to do |format|
      format.json do
        render :json => { 'getURL' => url_for(:action => 'show', :id => temp_id) + ".#{output_format}" }
      end
    end
  else
    # JasperReport
    call_report(request.parameters["report"], request)
  end
end

#infoObject



38
39
40
41
42
43
44
45
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/controllers/print_controller.rb', line 38

def info
  # return v2 print info format for GbPrintPanel
  info = {}
  info['createURL'] = url_for(:protocol => request.protocol, :action=>'create') + '.json'

  # add output formats
  info['outputFormats'] = []
  OUTPUT_FORMATS.each do |output_format|
    info['outputFormats'] << {:name => output_format}
  end

  # add scales
  info['scales'] = print_scales.collect do |scale|
    {:name => "1:#{scale}", :value => scale}
  end

  # add dpis
  info['dpis'] = print_dpis.collect do |dpi|
    {:name => "#{dpi}", :value => dpi}
  end

  # NOTE: load templates directly from YAML instead of parsing the Mapfish Print capabilities
  mapfish_config = YAML.load(File.read(@configFile))

  # parse layouts
  info['layouts'] = []
  mapfish_config['templates'].each do |name, template|
    # skip custom templates
    next if template['attributes'].has_key?('gb_custom_template')

    map = template['attributes']['map']
    # skip if no map
    next if map.nil?

    info['layouts'] << {
      :name => name,
      :map => {
        :width => map['width'],
        :height => map['height'],
      },
      :rotation => true
    }
  end

  respond_to do |format|
    format.json do
      if params[:var]
        render :text => "var #{params[:var]} = #{info.to_json};"
      else
        render :json => info
      end
    end
  end
end

#showObject



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

def show
  unless check_permissions
    head :forbidden
    return
  end

  output_format = params[:format]
  type = nil
  if OUTPUT_FORMATS.include?(output_format)
    case output_format
    when "pdf"
      type = 'application/x-pdf'
    when "png"
      type = 'image/png'
    when "jpg"
      type = 'image/jpeg'
    when "tif"
      type = 'image/tiff'
    when "gif"
      type = 'image/gif'
    end
  else
    # invalid format
    head :bad_request
    return
  end
  is_mapfish_print_id = (params[:id] =~ /^[0-9]+$/)
  if is_mapfish_print_id
    # deliver document generated previously by create()
    temp = TMP_PREFIX + params[:id] + ".#{output_format}"
    send_file temp, :type => type, :disposition => 'attachment', :filename => params[:id] + ".#{output_format}"
  else
    # create document
    report = params[:id]
    if custom_print_templates.include?(report)
      # Mapfish custom report

      # minimal Mapfish print params
      print_params = params.reject {|p| ['id', 'controller', 'action', 'format'].include?(p) }
      print_params['layout'] = report
      print_params['outputFormat'] = output_format
      print_params['attributes'] = {}
      print_params['dpi'] = print_params['dpi'] || print_dpis.first

      # add any custom params
      set_custom_print_params(report, print_params)

      # create report
      temp, temp_id = mapfish_print(print_params)

      default_filename = "#{report}.#{output_format}"
      send_custom_report(report, print_params, temp, type, default_filename)
    else
      # JasperReport
      create_and_send_jasper_report(report, request, type, "#{report}.pdf")
    end
  end
end