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