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