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