]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Merge 12304:14009 from trunk.
[rails.git] / app / controllers / changeset_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 class ChangesetController < ApplicationController
4   layout 'site'
5   require 'xml/libxml'
6
7   session :off, :except => [:list]
8   before_filter :authorize_web, :only => [:list]
9   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
10   before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
11   before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
12   after_filter :compress_output
13
14   # Help methods for checking boundary sanity and area size
15   include MapBoundary
16
17   # Helper methods for checking consistency
18   include ConsistencyValidations
19
20   # Create a changeset from XML.
21   def create
22     if request.put?
23       cs = Changeset.from_xml(request.raw_post, true)
24
25       if cs
26         cs.user_id = @user.id
27         cs.save_with_tags!
28         render :text => cs.id.to_s, :content_type => "text/plain"
29       else
30         render :nothing => true, :status => :bad_request
31       end
32     else
33       render :nothing => true, :status => :method_not_allowed
34     end
35   end
36
37   ##
38   # Return XML giving the basic info about the changeset. Does not 
39   # return anything about the nodes, ways and relations in the changeset.
40   def read
41     begin
42       changeset = Changeset.find(params[:id])
43       render :text => changeset.to_xml.to_s, :content_type => "text/xml"
44     rescue ActiveRecord::RecordNotFound
45       render :nothing => true, :status => :not_found
46     end
47   end
48   
49   ##
50   # marks a changeset as closed. this may be called multiple times
51   # on the same changeset, so is idempotent.
52   def close 
53     unless request.put?
54       render :nothing => true, :status => :method_not_allowed
55       return
56     end
57     
58     changeset = Changeset.find(params[:id])    
59     check_changeset_consistency(changeset, @user)
60
61     # to close the changeset, we'll just set its closed_at time to
62     # now. this might not be enough if there are concurrency issues, 
63     # but we'll have to wait and see.
64     changeset.set_closed_time_now
65
66     changeset.save!
67     render :nothing => true
68   rescue ActiveRecord::RecordNotFound
69     render :nothing => true, :status => :not_found
70   rescue OSM::APIError => ex
71     render ex.render_opts
72   end
73
74   ##
75   # insert a (set of) points into a changeset bounding box. this can only
76   # increase the size of the bounding box. this is a hint that clients can
77   # set either before uploading a large number of changes, or changes that
78   # the client (but not the server) knows will affect areas further away.
79   def expand_bbox
80     # only allow POST requests, because although this method is
81     # idempotent, there is no "document" to PUT really...
82     if request.post?
83       cs = Changeset.find(params[:id])
84       check_changeset_consistency(cs, @user)
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     check_changeset_consistency(changeset, @user)
147     
148     diff_reader = DiffReader.new(request.raw_post, changeset)
149     Changeset.transaction do
150       result = diff_reader.commit
151       render :text => result.to_s, :content_type => "text/xml"
152     end
153     
154   rescue ActiveRecord::RecordNotFound
155     render :nothing => true, :status => :not_found
156   rescue OSM::APIError => ex
157     render ex.render_opts
158   end
159
160   ##
161   # download the changeset as an osmChange document.
162   #
163   # to make it easier to revert diffs it would be better if the osmChange
164   # format were reversible, i.e: contained both old and new versions of 
165   # modified elements. but it doesn't at the moment...
166   #
167   # this method cannot order the database changes fully (i.e: timestamp and
168   # version number may be too coarse) so the resulting diff may not apply
169   # to a different database. however since changesets are not atomic this 
170   # behaviour cannot be guaranteed anyway and is the result of a design
171   # choice.
172   def download
173     changeset = Changeset.find(params[:id])
174     
175     # get all the elements in the changeset and stick them in a big array.
176     elements = [changeset.old_nodes, 
177                 changeset.old_ways, 
178                 changeset.old_relations].flatten
179     
180     # sort the elements by timestamp and version number, as this is the 
181     # almost sensible ordering available. this would be much nicer if 
182     # global (SVN-style) versioning were used - then that would be 
183     # unambiguous.
184     elements.sort! do |a, b| 
185       if (a.timestamp == b.timestamp)
186         a.version <=> b.version
187       else
188         a.timestamp <=> b.timestamp 
189       end
190     end
191     
192     # create an osmChange document for the output
193     result = OSM::API.new.get_xml_doc
194     result.root.name = "osmChange"
195
196     # generate an output element for each operation. note: we avoid looking
197     # at the history because it is simpler - but it would be more correct to 
198     # check these assertions.
199     elements.each do |elt|
200       result.root <<
201         if (elt.version == 1) 
202           # first version, so it must be newly-created.
203           created = XML::Node.new "create"
204           created << elt.to_xml_node
205         else
206           # get the previous version from the element history
207           prev_elt = elt.class.find(:first, :conditions => 
208                                     ['id = ? and version = ?',
209                                      elt.id, elt.version])
210           unless elt.visible
211             # if the element isn't visible then it must have been deleted, so
212             # output the *previous* XML
213             deleted = XML::Node.new "delete"
214             deleted << prev_elt.to_xml_node
215           else
216             # must be a modify, for which we don't need the previous version
217             # yet...
218             modified = XML::Node.new "modify"
219             modified << elt.to_xml_node
220           end
221         end
222     end
223
224     render :text => result.to_s, :content_type => "text/xml"
225             
226   rescue ActiveRecord::RecordNotFound
227     render :nothing => true, :status => :not_found
228   rescue OSM::APIError => ex
229     render ex.render_opts
230   end
231
232   ##
233   # query changesets by bounding box, time, user or open/closed status.
234   def query
235     # create the conditions that the user asked for. some or all of
236     # these may be nil.
237     conditions = conditions_bbox(params['bbox'])
238     conditions = cond_merge conditions, conditions_user(params['user'])
239     conditions = cond_merge conditions, conditions_time(params['time'])
240     conditions = cond_merge conditions, conditions_open(params['open'])
241
242     # create the results document
243     results = OSM::API.new.get_xml_doc
244
245     # add all matching changesets to the XML results document
246     Changeset.find(:all, 
247                    :conditions => conditions, 
248                    :limit => 100,
249                    :order => 'created_at desc').each do |cs|
250       results.root << cs.to_xml_node
251     end
252
253     render :text => results.to_s, :content_type => "text/xml"
254
255   rescue ActiveRecord::RecordNotFound
256     render :nothing => true, :status => :not_found
257   rescue OSM::APIError => ex
258     render ex.render_opts
259   end
260   
261   ##
262   # updates a changeset's tags. none of the changeset's attributes are
263   # user-modifiable, so they will be ignored.
264   #
265   # changesets are not (yet?) versioned, so we don't have to deal with
266   # history tables here. changesets are locked to a single user, however.
267   #
268   # after succesful update, returns the XML of the changeset.
269   def update
270     # request *must* be a PUT.
271     unless request.put?
272       render :nothing => true, :status => :method_not_allowed
273       return
274     end
275     
276     changeset = Changeset.find(params[:id])
277     new_changeset = Changeset.from_xml(request.raw_post)
278
279     unless new_changeset.nil?
280       check_changeset_consistency(changeset, @user)
281       changeset.update_from(new_changeset, @user)
282       render :text => changeset.to_xml, :mime_type => "text/xml"
283     else
284       
285       render :nothing => true, :status => :bad_request
286     end
287       
288   rescue ActiveRecord::RecordNotFound
289     render :nothing => true, :status => :not_found
290   rescue OSM::APIError => ex
291     render ex.render_opts
292   end
293
294   ##
295   # list edits belonging to a user
296   def list
297     user = User.find(:first, :conditions => [ "visible = ? and display_name = ?", true, params[:display_name]])
298     @edit_pages, @edits = paginate(:changesets,
299                                    :include => [:user, :changeset_tags],
300                                    :conditions => ["changesets.user_id = ? AND min_lat IS NOT NULL", user.id],
301                                    :order => "changesets.created_at DESC",
302                                    :per_page => 20)
303     
304     @action = 'list'
305     @display_name = user.display_name
306     # FIXME needs rescues in here
307   end
308
309 private
310   #------------------------------------------------------------
311   # utility functions below.
312   #------------------------------------------------------------  
313
314   ##
315   # merge two conditions
316   def cond_merge(a, b)
317     if a and b
318       a_str = a.shift
319       b_str = b.shift
320       return [ a_str + " and " + b_str ] + a + b
321     elsif a 
322       return a
323     else b
324       return b
325     end
326   end
327
328   ##
329   # if a bounding box was specified then parse it and do some sanity 
330   # checks. this is mostly the same as the map call, but without the 
331   # area restriction.
332   def conditions_bbox(bbox)
333     unless bbox.nil?
334       raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
335       bbox = sanitise_boundaries(bbox.split(/,/))
336       raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
337       raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
338       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
339               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
340     else
341       return nil
342     end
343   end
344
345   ##
346   # restrict changesets to those by a particular user
347   def conditions_user(user)
348     unless user.nil?
349       # user input checking, we don't have any UIDs < 1
350       raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
351
352       u = User.find(user.to_i)
353       # should be able to get changesets of public users only, or 
354       # our own changesets regardless of public-ness.
355       unless u.data_public?
356         # get optional user auth stuff so that users can see their own
357         # changesets if they're non-public
358         setup_user_auth
359         
360         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
361       end
362       return ['user_id = ?', u.id]
363     else
364       return nil
365     end
366   end
367
368   ##
369   # restrict changes to those during a particular time period
370   def conditions_time(time) 
371     unless time.nil?
372       # if there is a range, i.e: comma separated, then the first is 
373       # low, second is high - same as with bounding boxes.
374       if time.count(',') == 1
375         # check that we actually have 2 elements in the array
376         times = time.split(/,/)
377         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
378
379         from, to = times.collect { |t| DateTime.parse(t) }
380         return ['closed_at >= ? and created_at <= ?', from, to]
381       else
382         # if there is no comma, assume its a lower limit on time
383         return ['closed_at >= ?', DateTime.parse(time)]
384       end
385     else
386       return nil
387     end
388     # stupid DateTime seems to throw both of these for bad parsing, so
389     # we have to catch both and ensure the correct code path is taken.
390   rescue ArgumentError => ex
391     raise OSM::APIBadUserInput.new(ex.message.to_s)
392   rescue RuntimeError => ex
393     raise OSM::APIBadUserInput.new(ex.message.to_s)
394   end
395
396   ##
397   # restrict changes to those which are open
398   #
399   # at the moment this code assumes we're only interested in open
400   # changesets and gives no facility to query closed changesets. this
401   # would be reasonably simple to implement if anyone actually wants
402   # it?
403   def conditions_open(open)
404     return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?', 
405                               DateTime.now, Changeset::MAX_ELEMENTS]
406   end
407
408 end