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