]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Use the right keyword this time...
[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 LibXML::XML::Error, ArgumentError => ex
118     raise OSM::APIBadXMLError.new("osm", xml, ex.message)
119   rescue ActiveRecord::RecordNotFound
120     render :nothing => true, :status => :not_found
121   rescue OSM::APIError => ex
122     render ex.render_opts
123   end
124
125   ##
126   # Upload a diff in a single transaction.
127   #
128   # This means that each change within the diff must succeed, i.e: that
129   # each version number mentioned is still current. Otherwise the entire
130   # transaction *must* be rolled back.
131   #
132   # Furthermore, each element in the diff can only reference the current
133   # changeset.
134   #
135   # Returns: a diffResult document, as described in 
136   # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
137   def upload
138     # only allow POST requests, as the upload method is most definitely
139     # not idempotent, as several uploads with placeholder IDs will have
140     # different side-effects.
141     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
142     unless request.post?
143       render :nothing => true, :status => :method_not_allowed
144       return
145     end
146
147     changeset = Changeset.find(params[:id])
148     check_changeset_consistency(changeset, @user)
149     
150     diff_reader = DiffReader.new(request.raw_post, changeset)
151     Changeset.transaction do
152       result = diff_reader.commit
153       render :text => result.to_s, :content_type => "text/xml"
154     end
155     
156   rescue ActiveRecord::RecordNotFound
157     render :nothing => true, :status => :not_found
158   rescue OSM::APIError => ex
159     render ex.render_opts
160   end
161
162   ##
163   # download the changeset as an osmChange document.
164   #
165   # to make it easier to revert diffs it would be better if the osmChange
166   # format were reversible, i.e: contained both old and new versions of 
167   # modified elements. but it doesn't at the moment...
168   #
169   # this method cannot order the database changes fully (i.e: timestamp and
170   # version number may be too coarse) so the resulting diff may not apply
171   # to a different database. however since changesets are not atomic this 
172   # behaviour cannot be guaranteed anyway and is the result of a design
173   # choice.
174   def download
175     changeset = Changeset.find(params[:id])
176     
177     # get all the elements in the changeset and stick them in a big array.
178     elements = [changeset.old_nodes, 
179                 changeset.old_ways, 
180                 changeset.old_relations].flatten
181     
182     # sort the elements by timestamp and version number, as this is the 
183     # almost sensible ordering available. this would be much nicer if 
184     # global (SVN-style) versioning were used - then that would be 
185     # unambiguous.
186     elements.sort! do |a, b| 
187       if (a.timestamp == b.timestamp)
188         a.version <=> b.version
189       else
190         a.timestamp <=> b.timestamp 
191       end
192     end
193     
194     # create an osmChange document for the output
195     result = OSM::API.new.get_xml_doc
196     result.root.name = "osmChange"
197
198     # generate an output element for each operation. note: we avoid looking
199     # at the history because it is simpler - but it would be more correct to 
200     # check these assertions.
201     elements.each do |elt|
202       result.root <<
203         if (elt.version == 1) 
204           # first version, so it must be newly-created.
205           created = XML::Node.new "create"
206           created << elt.to_xml_node
207         else
208           # get the previous version from the element history
209           prev_elt = elt.class.find(:first, :conditions => 
210                                     ['id = ? and version = ?',
211                                      elt.id, elt.version])
212           unless elt.visible
213             # if the element isn't visible then it must have been deleted, so
214             # output the *previous* XML
215             deleted = XML::Node.new "delete"
216             deleted << prev_elt.to_xml_node
217           else
218             # must be a modify, for which we don't need the previous version
219             # yet...
220             modified = XML::Node.new "modify"
221             modified << elt.to_xml_node
222           end
223         end
224     end
225
226     render :text => result.to_s, :content_type => "text/xml"
227             
228   rescue ActiveRecord::RecordNotFound
229     render :nothing => true, :status => :not_found
230   rescue OSM::APIError => ex
231     render ex.render_opts
232   end
233
234   ##
235   # query changesets by bounding box, time, user or open/closed status.
236   def query
237     # create the conditions that the user asked for. some or all of
238     # these may be nil.
239     conditions = conditions_bbox(params['bbox'])
240     conditions = cond_merge conditions, conditions_user(params['user'])
241     conditions = cond_merge conditions, conditions_time(params['time'])
242     conditions = cond_merge conditions, conditions_open(params['open'])
243     conditions = cond_merge conditions, conditions_closed(params['closed'])
244
245     # create the results document
246     results = OSM::API.new.get_xml_doc
247
248     # add all matching changesets to the XML results document
249     Changeset.find(:all, 
250                    :conditions => conditions, 
251                    :limit => 100,
252                    :order => 'created_at desc').each do |cs|
253       results.root << cs.to_xml_node
254     end
255
256     render :text => results.to_s, :content_type => "text/xml"
257
258   rescue ActiveRecord::RecordNotFound
259     render :nothing => true, :status => :not_found
260   rescue OSM::APIError => ex
261     render ex.render_opts
262   end
263   
264   ##
265   # updates a changeset's tags. none of the changeset's attributes are
266   # user-modifiable, so they will be ignored.
267   #
268   # changesets are not (yet?) versioned, so we don't have to deal with
269   # history tables here. changesets are locked to a single user, however.
270   #
271   # after succesful update, returns the XML of the changeset.
272   def update
273     # request *must* be a PUT.
274     unless request.put?
275       render :nothing => true, :status => :method_not_allowed
276       return
277     end
278     
279     changeset = Changeset.find(params[:id])
280     new_changeset = Changeset.from_xml(request.raw_post)
281
282     unless new_changeset.nil?
283       check_changeset_consistency(changeset, @user)
284       changeset.update_from(new_changeset, @user)
285       render :text => changeset.to_xml, :mime_type => "text/xml"
286     else
287       
288       render :nothing => true, :status => :bad_request
289     end
290       
291   rescue ActiveRecord::RecordNotFound
292     render :nothing => true, :status => :not_found
293   rescue OSM::APIError => ex
294     render ex.render_opts
295   end
296
297   
298   
299   ##
300   # list edits (open changesets) in reverse chronological order
301   def list
302     conditions = conditions_nonempty
303     
304     
305    # @changesets = Changeset.find(:all, :order => "closed_at DESC", :conditions => ['closed_at < ?', DateTime.now], :limit=> 20)
306    
307    
308    #@edit_pages, @edits = paginate(:changesets,
309    #                                :include => [:user, :changeset_tags],
310    #                                :conditions => conditions,
311    #                                :order => "changesets.created_at DESC",
312    #                                :per_page => 20)
313    #
314     
315    @edits =  Changeset.find(:all,
316                                    :order => "changesets.created_at DESC",
317                                    :conditions => conditions,
318                                    :limit => 20)
319     
320   end
321   
322   ##
323   # list edits (changesets) belonging to a user
324   def list_user
325     user = User.find_by_display_name(params[:display_name], :conditions => {:visible => true})
326     
327     if user
328       @display_name = user.display_name
329       if not user.data_public? and @user != user
330         @edits = nil
331         render
332       else
333         conditions = cond_merge conditions, ['user_id = ?', user.id]
334         conditions = cond_merge conditions, conditions_nonempty
335         @edit_pages, @edits = paginate(:changesets,
336                                         :include => [:user, :changeset_tags],
337                                         :conditions => conditions,
338                                         :order => "changesets.created_at DESC",
339                                         :per_page => 20)
340       end
341     else
342       @not_found_user = params[:display_name]
343       render :template => 'user/no_such_user', :status => :not_found
344     end
345   end
346   
347   ##
348   # list changesets in a bbox
349   def list_bbox
350     # support 'bbox' param or alternatively 'minlon', 'minlat' etc        
351     if params['bbox']
352        bbox = params['bbox']
353     elsif params['minlon'] and params['minlat'] and params['maxlon'] and params['maxlat']
354        bbox = h(params['minlon']) + ',' + h(params['minlat']) + ',' + h(params['maxlon']) + ',' + h(params['maxlat'])
355     else
356       #TODO: fix bugs in location determination for history tab (and other tabs) then uncomment this redirect
357       #redirect_to :action => 'list'
358     end
359        
360     conditions = conditions_bbox(bbox);
361     conditions = cond_merge conditions, conditions_nonempty
362     
363     @edit_pages, @edits = paginate(:changesets,
364                                    :include => [:user, :changeset_tags],
365                                    :conditions => conditions,
366                                    :order => "changesets.created_at DESC",
367                                    :per_page => 20)
368                                    
369     @bbox = sanitise_boundaries(bbox.split(/,/)) unless bbox==nil
370   end
371   
372 private
373   #------------------------------------------------------------
374   # utility functions below.
375   #------------------------------------------------------------  
376
377   ##
378   # merge two conditions
379   def cond_merge(a, b)
380     if a and b
381       a_str = a.shift
382       b_str = b.shift
383       return [ a_str + " AND " + b_str ] + a + b
384     elsif a 
385       return a
386     else b
387       return b
388     end
389   end
390
391   ##
392   # if a bounding box was specified then parse it and do some sanity 
393   # checks. this is mostly the same as the map call, but without the 
394   # area restriction.
395   def conditions_bbox(bbox)
396     unless bbox.nil?
397       raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
398       bbox = sanitise_boundaries(bbox.split(/,/))
399       raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
400       raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
401       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
402               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
403     else
404       return nil
405     end
406   end
407
408   ##
409   # restrict changesets to those by a particular user
410   def conditions_user(user)
411     unless user.nil?
412       # user input checking, we don't have any UIDs < 1
413       raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
414
415       u = User.find(user.to_i)
416       # should be able to get changesets of public users only, or 
417       # our own changesets regardless of public-ness.
418       unless u.data_public?
419         # get optional user auth stuff so that users can see their own
420         # changesets if they're non-public
421         setup_user_auth
422         
423         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
424       end
425       return ['user_id = ?', u.id]
426     else
427       return nil
428     end
429   end
430
431   ##
432   # restrict changes to those closed during a particular time period
433   def conditions_time(time) 
434     unless time.nil?
435       # if there is a range, i.e: comma separated, then the first is 
436       # low, second is high - same as with bounding boxes.
437       if time.count(',') == 1
438         # check that we actually have 2 elements in the array
439         times = time.split(/,/)
440         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
441
442         from, to = times.collect { |t| DateTime.parse(t) }
443         return ['closed_at >= ? and created_at <= ?', from, to]
444       else
445         # if there is no comma, assume its a lower limit on time
446         return ['closed_at >= ?', DateTime.parse(time)]
447       end
448     else
449       return nil
450     end
451     # stupid DateTime seems to throw both of these for bad parsing, so
452     # we have to catch both and ensure the correct code path is taken.
453   rescue ArgumentError => ex
454     raise OSM::APIBadUserInput.new(ex.message.to_s)
455   rescue RuntimeError => ex
456     raise OSM::APIBadUserInput.new(ex.message.to_s)
457   end
458
459   ##
460   # return changesets which are open (haven't been closed yet)
461   # we do this by seeing if the 'closed at' time is in the future. Also if we've
462   # hit the maximum number of changes then it counts as no longer open.
463   # if parameter 'open' is nill then open and closed changsets are returned
464   def conditions_open(open)
465     return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?', 
466                               Time.now.getutc, Changeset::MAX_ELEMENTS]
467   end
468   
469   ##
470   # query changesets which are closed
471   # ('closed at' time has passed or changes limit is hit)
472   def conditions_closed(closed)
473     return closed.nil? ? nil : ['closed_at < ? and num_changes > ?', 
474                                 Time.now.getutc, Changeset::MAX_ELEMENTS]
475   end
476
477   ##
478   # eliminate empty changesets (where the bbox has not been set)
479   # this should be applied to all changeset list displays
480   def conditions_nonempty()
481     return ['min_lat IS NOT NULL']
482   end
483   
484 end