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