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