]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Fix for correct boolean handling in query.
[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, :list_user, :list_bbox]
8   before_filter :authorize_web, :only => [:list, :list_user, :list_bbox]
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     conditions = cond_merge conditions, conditions_closed(params['closed'])
242
243     # create the results document
244     results = OSM::API.new.get_xml_doc
245
246     # add all matching changesets to the XML results document
247     Changeset.find(:all, 
248                    :conditions => conditions, 
249                    :limit => 100,
250                    :order => 'created_at desc').each do |cs|
251       results.root << cs.to_xml_node
252     end
253
254     render :text => results.to_s, :content_type => "text/xml"
255
256   rescue ActiveRecord::RecordNotFound
257     render :nothing => true, :status => :not_found
258   rescue OSM::APIError => ex
259     render ex.render_opts
260   end
261   
262   ##
263   # updates a changeset's tags. none of the changeset's attributes are
264   # user-modifiable, so they will be ignored.
265   #
266   # changesets are not (yet?) versioned, so we don't have to deal with
267   # history tables here. changesets are locked to a single user, however.
268   #
269   # after succesful update, returns the XML of the changeset.
270   def update
271     # request *must* be a PUT.
272     unless request.put?
273       render :nothing => true, :status => :method_not_allowed
274       return
275     end
276     
277     changeset = Changeset.find(params[:id])
278     new_changeset = Changeset.from_xml(request.raw_post)
279
280     unless new_changeset.nil?
281       check_changeset_consistency(changeset, @user)
282       changeset.update_from(new_changeset, @user)
283       render :text => changeset.to_xml, :mime_type => "text/xml"
284     else
285       
286       render :nothing => true, :status => :bad_request
287     end
288       
289   rescue ActiveRecord::RecordNotFound
290     render :nothing => true, :status => :not_found
291   rescue OSM::APIError => ex
292     render ex.render_opts
293   end
294
295   
296   
297   ##
298   # list edits (open changesets) in reverse chronological order
299   def list
300     conditions = conditions_nonempty
301     
302     
303    # @changesets = Changeset.find(:all, :order => "closed_at DESC", :conditions => ['closed_at < ?', DateTime.now], :limit=> 20)
304    
305    
306    #@edit_pages, @edits = paginate(:changesets,
307    #                                :include => [:user, :changeset_tags],
308    #                                :conditions => conditions,
309    #                                :order => "changesets.created_at DESC",
310    #                                :per_page => 20)
311    #
312     
313    @edits =  Changeset.find(:all,
314                                    :order => "changesets.created_at DESC",
315                                    :conditions => conditions,
316                                    :limit => 20)
317     
318   end
319   
320   ##
321   # list edits (changesets) belonging to a user
322   def list_user
323     user = User.find_by_display_name(params[:display_name], :conditions => {:visible => true})
324     
325     if user
326       @display_name = user.display_name
327       if not user.data_public? and @user != user
328         @edits = nil
329         render
330       else
331         conditions = cond_merge conditions, ['user_id = ?', user.id]
332         conditions = cond_merge conditions, conditions_nonempty
333         @edit_pages, @edits = paginate(:changesets,
334                                         :include => [:user, :changeset_tags],
335                                         :conditions => conditions,
336                                         :order => "changesets.created_at DESC",
337                                         :per_page => 20)
338       end
339     else
340       @not_found_user = params[:display_name]
341       render :template => 'user/no_such_user', :status => :not_found
342     end
343   end
344   
345   ##
346   # list changesets in a bbox
347   def list_bbox
348     # support 'bbox' param or alternatively 'minlon', 'minlat' etc        
349     if params['bbox']
350        bbox = params['bbox']
351     elsif params['minlon'] and params['minlat'] and params['maxlon'] and params['maxlat']
352        bbox = h(params['minlon']) + ',' + h(params['minlat']) + ',' + h(params['maxlon']) + ',' + h(params['maxlat'])
353     else
354       #TODO: fix bugs in location determination for history tab (and other tabs) then uncomment this redirect
355       #redirect_to :action => 'list'
356     end
357        
358     conditions = conditions_bbox(bbox);
359     conditions = cond_merge conditions, conditions_nonempty
360     
361     @edit_pages, @edits = paginate(:changesets,
362                                    :include => [:user, :changeset_tags],
363                                    :conditions => conditions,
364                                    :order => "changesets.created_at DESC",
365                                    :per_page => 20)
366                                    
367     @bbox = sanitise_boundaries(bbox.split(/,/)) unless bbox==nil
368   end
369   
370 private
371   #------------------------------------------------------------
372   # utility functions below.
373   #------------------------------------------------------------  
374
375   ##
376   # merge two conditions
377   def cond_merge(a, b)
378     if a and b
379       a_str = a.shift
380       b_str = b.shift
381       return [ a_str + " AND " + b_str ] + a + b
382     elsif a 
383       return a
384     else b
385       return b
386     end
387   end
388
389   ##
390   # if a bounding box was specified then parse it and do some sanity 
391   # checks. this is mostly the same as the map call, but without the 
392   # area restriction.
393   def conditions_bbox(bbox)
394     unless bbox.nil?
395       raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
396       bbox = sanitise_boundaries(bbox.split(/,/))
397       raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
398       raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
399       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
400               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
401     else
402       return nil
403     end
404   end
405
406   ##
407   # restrict changesets to those by a particular user
408   def conditions_user(user)
409     unless user.nil?
410       # user input checking, we don't have any UIDs < 1
411       raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
412
413       u = User.find(user.to_i)
414       # should be able to get changesets of public users only, or 
415       # our own changesets regardless of public-ness.
416       unless u.data_public?
417         # get optional user auth stuff so that users can see their own
418         # changesets if they're non-public
419         setup_user_auth
420         
421         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
422       end
423       return ['user_id = ?', u.id]
424     else
425       return nil
426     end
427   end
428
429   ##
430   # restrict changes to those closed during a particular time period
431   def conditions_time(time) 
432     unless time.nil?
433       # if there is a range, i.e: comma separated, then the first is 
434       # low, second is high - same as with bounding boxes.
435       if time.count(',') == 1
436         # check that we actually have 2 elements in the array
437         times = time.split(/,/)
438         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
439
440         from, to = times.collect { |t| DateTime.parse(t) }
441         return ['closed_at >= ? and created_at <= ?', from, to]
442       else
443         # if there is no comma, assume its a lower limit on time
444         return ['closed_at >= ?', DateTime.parse(time)]
445       end
446     else
447       return nil
448     end
449     # stupid DateTime seems to throw both of these for bad parsing, so
450     # we have to catch both and ensure the correct code path is taken.
451   rescue ArgumentError => ex
452     raise OSM::APIBadUserInput.new(ex.message.to_s)
453   rescue RuntimeError => ex
454     raise OSM::APIBadUserInput.new(ex.message.to_s)
455   end
456
457   ##
458   # return changesets which are open (haven't been closed yet)
459   # we do this by seeing if the 'closed at' time is in the future. Also if we've
460   # hit the maximum number of changes then it counts as no longer open.
461   # if parameter 'open' is nill then open and closed changsets are returned
462   def conditions_open(open)
463     return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?', 
464                               DateTime.now, Changeset::MAX_ELEMENTS]
465   end
466   
467   ##
468   # query changesets which are closed
469   # ('closed at' time has passed or changes limit is hit)
470   def conditions_closed(closed)
471     return closed.nil? ? nil : ['closed_at < ? and num_changes > ?', 
472                               DateTime.now, Changeset::MAX_ELEMENTS]
473   end
474
475   ##
476   # eliminate empty changesets (where the bbox has not been set)
477   # this should be applied to all changeset list displays
478   def conditions_nonempty()
479     return ['min_lat IS NOT NULL']
480   end
481   
482 end