]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Closes #1350 through updating amf_controller to use the newer closed_at method of...
[rails.git] / app / controllers / changeset_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 class ChangesetController < ApplicationController
4   require 'xml/libxml'
5   require 'diff_reader'
6
7   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
8   before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
9   before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
10   after_filter :compress_output
11
12   # Help methods for checking boundary sanity and area size
13   include MapBoundary
14
15   # Create a changeset from XML.
16   def create
17     if request.put?
18       cs = Changeset.from_xml(request.raw_post, true)
19
20       if cs
21         cs.user_id = @user.id
22         cs.save_with_tags!
23         render :text => cs.id.to_s, :content_type => "text/plain"
24       else
25         render :nothing => true, :status => :bad_request
26       end
27     else
28       render :nothing => true, :status => :method_not_allowed
29     end
30   end
31
32   def read
33     begin
34       changeset = Changeset.find(params[:id])
35       render :text => changeset.to_xml.to_s, :content_type => "text/xml"
36     rescue ActiveRecord::RecordNotFound
37       render :nothing => true, :status => :not_found
38     end
39   end
40   
41   ##
42   # marks a changeset as closed. this may be called multiple times
43   # on the same changeset, so is idempotent.
44   def close 
45     unless request.put?
46       render :nothing => true, :status => :method_not_allowed
47       return
48     end
49     
50     changeset = Changeset.find(params[:id])
51     
52     unless @user.id == changeset.user_id 
53       raise OSM::APIUserChangesetMismatchError 
54     end
55     
56     # to close the changeset, we'll just set its closed_at time to
57     # now. this might not be enough if there are concurrency issues, 
58     # but we'll have to wait and see.
59     changeset.set_closed_time_now
60
61     changeset.save!
62     render :nothing => true
63   rescue ActiveRecord::RecordNotFound
64     render :nothing => true, :status => :not_found
65   rescue OSM::APIError => ex
66     render ex.render_opts
67   end
68
69   ##
70   # insert a (set of) points into a changeset bounding box. this can only
71   # increase the size of the bounding box. this is a hint that clients can
72   # set either before uploading a large number of changes, or changes that
73   # the client (but not the server) knows will affect areas further away.
74   def include
75     # only allow POST requests, because although this method is
76     # idempotent, there is no "document" to PUT really...
77     if request.post?
78       cs = Changeset.find(params[:id])
79
80       # check user credentials - only the user who opened a changeset
81       # may alter it.
82       unless @user.id == cs.user_id 
83         raise OSM::APIUserChangesetMismatchError 
84       end
85
86       # keep an array of lons and lats
87       lon = Array.new
88       lat = Array.new
89
90       # the request is in pseudo-osm format... this is kind-of an
91       # abuse, maybe should change to some other format?
92       doc = XML::Parser.string(request.raw_post).parse
93       doc.find("//osm/node").each do |n|
94         lon << n['lon'].to_f * GeoRecord::SCALE
95         lat << n['lat'].to_f * GeoRecord::SCALE
96       end
97
98       # add the existing bounding box to the lon-lat array
99       lon << cs.min_lon unless cs.min_lon.nil?
100       lat << cs.min_lat unless cs.min_lat.nil?
101       lon << cs.max_lon unless cs.max_lon.nil?
102       lat << cs.max_lat unless cs.max_lat.nil?
103
104       # collapse the arrays to minimum and maximum
105       cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat = 
106         lon.min, lat.min, lon.max, lat.max
107
108       # save the larger bounding box and return the changeset, which
109       # will include the bigger bounding box.
110       cs.save!
111       render :text => cs.to_xml.to_s, :content_type => "text/xml"
112
113     else
114       render :nothing => true, :status => :method_not_allowed
115     end
116
117   rescue ActiveRecord::RecordNotFound
118     render :nothing => true, :status => :not_found
119   rescue OSM::APIError => ex
120     render ex.render_opts
121   end
122
123   ##
124   # Upload a diff in a single transaction.
125   #
126   # This means that each change within the diff must succeed, i.e: that
127   # each version number mentioned is still current. Otherwise the entire
128   # transaction *must* be rolled back.
129   #
130   # Furthermore, each element in the diff can only reference the current
131   # changeset.
132   #
133   # Returns: a diffResult document, as described in 
134   # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
135   def upload
136     # only allow POST requests, as the upload method is most definitely
137     # not idempotent, as several uploads with placeholder IDs will have
138     # different side-effects.
139     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
140     unless request.post?
141       render :nothing => true, :status => :method_not_allowed
142       return
143     end
144
145     changeset = Changeset.find(params[:id])
146
147     # access control - only the user who created a changeset may
148     # upload to it.
149     unless @user.id == changeset.user_id 
150       raise OSM::APIUserChangesetMismatchError 
151     end
152     
153     diff_reader = DiffReader.new(request.raw_post, changeset)
154     Changeset.transaction do
155       result = diff_reader.commit
156       render :text => result.to_s, :content_type => "text/xml"
157     end
158     
159   rescue ActiveRecord::RecordNotFound
160     render :nothing => true, :status => :not_found
161   rescue OSM::APIError => ex
162     render ex.render_opts
163   end
164
165   ##
166   # download the changeset as an osmChange document.
167   #
168   # to make it easier to revert diffs it would be better if the osmChange
169   # format were reversible, i.e: contained both old and new versions of 
170   # modified elements. but it doesn't at the moment...
171   #
172   # this method cannot order the database changes fully (i.e: timestamp and
173   # version number may be too coarse) so the resulting diff may not apply
174   # to a different database. however since changesets are not atomic this 
175   # behaviour cannot be guaranteed anyway and is the result of a design
176   # choice.
177   def download
178     changeset = Changeset.find(params[:id])
179     
180     # get all the elements in the changeset and stick them in a big array.
181     elements = [changeset.old_nodes, 
182                 changeset.old_ways, 
183                 changeset.old_relations].flatten
184     
185     # sort the elements by timestamp and version number, as this is the 
186     # almost sensible ordering available. this would be much nicer if 
187     # global (SVN-style) versioning were used - then that would be 
188     # unambiguous.
189     elements.sort! do |a, b| 
190       if (a.timestamp == b.timestamp)
191         a.version <=> b.version
192       else
193         a.timestamp <=> b.timestamp 
194       end
195     end
196     
197     # create an osmChange document for the output
198     result = OSM::API.new.get_xml_doc
199     result.root.name = "osmChange"
200
201     # generate an output element for each operation. note: we avoid looking
202     # at the history because it is simpler - but it would be more correct to 
203     # check these assertions.
204     elements.each do |elt|
205       result.root <<
206         if (elt.version == 1) 
207           # first version, so it must be newly-created.
208           created = XML::Node.new "create"
209           created << elt.to_xml_node
210         else
211           # get the previous version from the element history
212           prev_elt = elt.class.find(:first, :conditions => 
213                                     ['id = ? and version = ?',
214                                      elt.id, elt.version])
215           unless elt.visible
216             # if the element isn't visible then it must have been deleted, so
217             # output the *previous* XML
218             deleted = XML::Node.new "delete"
219             deleted << prev_elt.to_xml_node
220           else
221             # must be a modify, for which we don't need the previous version
222             # yet...
223             modified = XML::Node.new "modify"
224             modified << elt.to_xml_node
225           end
226         end
227     end
228
229     render :text => result.to_s, :content_type => "text/xml"
230             
231   rescue ActiveRecord::RecordNotFound
232     render :nothing => true, :status => :not_found
233   rescue OSM::APIError => ex
234     render ex.render_opts
235   end
236
237   ##
238   # query changesets by bounding box, time, user or open/closed status.
239   def query
240     # create the conditions that the user asked for. some or all of
241     # these may be nil.
242     conditions = conditions_bbox(params['bbox'])
243     conditions = cond_merge conditions, conditions_user(params['user'])
244     conditions = cond_merge conditions, conditions_time(params['time'])
245     conditions = cond_merge conditions, conditions_open(params['open'])
246
247     # create the results document
248     results = OSM::API.new.get_xml_doc
249
250     # add all matching changesets to the XML results document
251     Changeset.find(:all, 
252                    :conditions => conditions, 
253                    :limit => 100,
254                    :order => 'created_at desc').each do |cs|
255       results.root << cs.to_xml_node
256     end
257
258     render :text => results.to_s, :content_type => "text/xml"
259
260   rescue ActiveRecord::RecordNotFound
261     render :nothing => true, :status => :not_found
262   rescue OSM::APIError => ex
263     render ex.render_opts
264   end
265   
266   ##
267   # updates a changeset's tags. none of the changeset's attributes are
268   # user-modifiable, so they will be ignored.
269   #
270   # changesets are not (yet?) versioned, so we don't have to deal with
271   # history tables here. changesets are locked to a single user, however.
272   #
273   # after succesful update, returns the XML of the changeset.
274   def update
275     # request *must* be a PUT.
276     unless request.put?
277       render :nothing => true, :status => :method_not_allowed
278       return
279     end
280     
281     changeset = Changeset.find(params[:id])
282     new_changeset = Changeset.from_xml(request.raw_post)
283
284     unless new_changeset.nil?
285       changeset.update_from(new_changeset, @user)
286       render :text => changeset.to_xml, :mime_type => "text/xml"
287     else
288       
289       render :nothing => true, :status => :bad_request
290     end
291       
292   rescue ActiveRecord::RecordNotFound
293     render :nothing => true, :status => :not_found
294   rescue OSM::APIError => ex
295     render ex.render_opts
296   end
297
298   #------------------------------------------------------------
299   # utility functions below.
300   #------------------------------------------------------------  
301
302   ##
303   # merge two conditions
304   def cond_merge(a, b)
305     if a and b
306       a_str = a.shift
307       b_str = b.shift
308       return [ a_str + " and " + b_str ] + a + b
309     elsif a 
310       return a
311     else b
312       return b
313     end
314   end
315
316   ##
317   # if a bounding box was specified then parse it and do some sanity 
318   # checks. this is mostly the same as the map call, but without the 
319   # area restriction.
320   def conditions_bbox(bbox)
321     unless bbox.nil?
322       raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
323       bbox = sanitise_boundaries(bbox.split(/,/))
324       raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
325       raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
326       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
327               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
328     else
329       return nil
330     end
331   end
332
333   ##
334   # restrict changesets to those by a particular user
335   def conditions_user(user)
336     unless user.nil?
337       # user input checking, we don't have any UIDs < 1
338       raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
339
340       u = User.find(user.to_i)
341       # should be able to get changesets of public users only, or 
342       # our own changesets regardless of public-ness.
343       unless u.data_public?
344         # get optional user auth stuff so that users can see their own
345         # changesets if they're non-public
346         setup_user_auth
347         
348         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
349       end
350       return ['user_id = ?', u.id]
351     else
352       return nil
353     end
354   end
355
356   ##
357   # restrict changes to those during a particular time period
358   def conditions_time(time) 
359     unless time.nil?
360       # if there is a range, i.e: comma separated, then the first is 
361       # low, second is high - same as with bounding boxes.
362       if time.count(',') == 1
363         # check that we actually have 2 elements in the array
364         times = time.split(/,/)
365         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
366
367         from, to = times.collect { |t| DateTime.parse(t) }
368         return ['closed_at >= ? and created_at <= ?', from, to]
369       else
370         # if there is no comma, assume its a lower limit on time
371         return ['closed_at >= ?', DateTime.parse(time)]
372       end
373     else
374       return nil
375     end
376     # stupid DateTime seems to throw both of these for bad parsing, so
377     # we have to catch both and ensure the correct code path is taken.
378   rescue ArgumentError => ex
379     raise OSM::APIBadUserInput.new(ex.message.to_s)
380   rescue RuntimeError => ex
381     raise OSM::APIBadUserInput.new(ex.message.to_s)
382   end
383
384   ##
385   # restrict changes to those which are open
386   def conditions_open(open)
387     return open.nil? ? nil : ['closed_at >= ?', DateTime.now]
388   end
389
390 end