1 # The ChangesetController is the RESTful interface to Changeset objects
 
   3 class ChangesetController < ApplicationController
 
   7   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
 
   8   before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
 
   9   before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
 
  10   after_filter :compress_output
 
  12   # Help methods for checking boundary sanity and area size
 
  15   # Create a changeset from XML.
 
  18       cs = Changeset.from_xml(request.raw_post, true)
 
  23         render :text => cs.id.to_s, :content_type => "text/plain"
 
  25         render :nothing => true, :status => :bad_request
 
  28       render :nothing => true, :status => :method_not_allowed
 
  34       changeset = Changeset.find(params[:id])
 
  35       render :text => changeset.to_xml.to_s, :content_type => "text/xml"
 
  36     rescue ActiveRecord::RecordNotFound
 
  37       render :nothing => true, :status => :not_found
 
  42   # marks a changeset as closed. this may be called multiple times
 
  43   # on the same changeset, so is idempotent.
 
  46       render :nothing => true, :status => :method_not_allowed
 
  50     changeset = Changeset.find(params[:id])
 
  52     unless @user.id == changeset.user_id 
 
  53       raise OSM::APIUserChangesetMismatchError 
 
  56     changeset.open = false
 
  58     render :nothing => true
 
  59   rescue ActiveRecord::RecordNotFound
 
  60     render :nothing => true, :status => :not_found
 
  61   rescue OSM::APIError => ex
 
  66   # insert a (set of) points into a changeset bounding box. this can only
 
  67   # increase the size of the bounding box. this is a hint that clients can
 
  68   # set either before uploading a large number of changes, or changes that
 
  69   # the client (but not the server) knows will affect areas further away.
 
  71     # only allow POST requests, because although this method is
 
  72     # idempotent, there is no "document" to PUT really...
 
  74       cs = Changeset.find(params[:id])
 
  76       # check user credentials - only the user who opened a changeset
 
  78       unless @user.id == cs.user_id 
 
  79         raise OSM::APIUserChangesetMismatchError 
 
  82       # keep an array of lons and lats
 
  86       # the request is in pseudo-osm format... this is kind-of an
 
  87       # abuse, maybe should change to some other format?
 
  88       doc = XML::Parser.string(request.raw_post).parse
 
  89       doc.find("//osm/node").each do |n|
 
  90         lon << n['lon'].to_f * GeoRecord::SCALE
 
  91         lat << n['lat'].to_f * GeoRecord::SCALE
 
  94       # add the existing bounding box to the lon-lat array
 
  95       lon << cs.min_lon unless cs.min_lon.nil?
 
  96       lat << cs.min_lat unless cs.min_lat.nil?
 
  97       lon << cs.max_lon unless cs.max_lon.nil?
 
  98       lat << cs.max_lat unless cs.max_lat.nil?
 
 100       # collapse the arrays to minimum and maximum
 
 101       cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat = 
 
 102         lon.min, lat.min, lon.max, lat.max
 
 104       # save the larger bounding box and return the changeset, which
 
 105       # will include the bigger bounding box.
 
 107       render :text => cs.to_xml.to_s, :content_type => "text/xml"
 
 110       render :nothing => true, :status => :method_not_allowed
 
 113   rescue ActiveRecord::RecordNotFound
 
 114     render :nothing => true, :status => :not_found
 
 115   rescue OSM::APIError => ex
 
 116     render ex.render_opts
 
 120   # Upload a diff in a single transaction.
 
 122   # This means that each change within the diff must succeed, i.e: that
 
 123   # each version number mentioned is still current. Otherwise the entire
 
 124   # transaction *must* be rolled back.
 
 126   # Furthermore, each element in the diff can only reference the current
 
 129   # Returns: a diffResult document, as described in 
 
 130   # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
 
 132     # only allow POST requests, as the upload method is most definitely
 
 133     # not idempotent, as several uploads with placeholder IDs will have
 
 134     # different side-effects.
 
 135     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
 
 137       render :nothing => true, :status => :method_not_allowed
 
 141     changeset = Changeset.find(params[:id])
 
 143     # access control - only the user who created a changeset may
 
 145     unless @user.id == changeset.user_id 
 
 146       raise OSM::APIUserChangesetMismatchError 
 
 149     diff_reader = DiffReader.new(request.raw_post, changeset)
 
 150     Changeset.transaction do
 
 151       result = diff_reader.commit
 
 152       render :text => result.to_s, :content_type => "text/xml"
 
 155   rescue ActiveRecord::RecordNotFound
 
 156     render :nothing => true, :status => :not_found
 
 157   rescue OSM::APIError => ex
 
 158     render ex.render_opts
 
 162   # download the changeset as an osmChange document.
 
 164   # to make it easier to revert diffs it would be better if the osmChange
 
 165   # format were reversible, i.e: contained both old and new versions of 
 
 166   # modified elements. but it doesn't at the moment...
 
 168   # this method cannot order the database changes fully (i.e: timestamp and
 
 169   # version number may be too coarse) so the resulting diff may not apply
 
 170   # to a different database. however since changesets are not atomic this 
 
 171   # behaviour cannot be guaranteed anyway and is the result of a design
 
 174     changeset = Changeset.find(params[:id])
 
 176     # get all the elements in the changeset and stick them in a big array.
 
 177     elements = [changeset.old_nodes, 
 
 179                 changeset.old_relations].flatten
 
 181     # sort the elements by timestamp and version number, as this is the 
 
 182     # almost sensible ordering available. this would be much nicer if 
 
 183     # global (SVN-style) versioning were used - then that would be 
 
 185     elements.sort! do |a, b| 
 
 186       if (a.timestamp == b.timestamp)
 
 187         a.version <=> b.version
 
 189         a.timestamp <=> b.timestamp 
 
 193     # create an osmChange document for the output
 
 194     result = OSM::API.new.get_xml_doc
 
 195     result.root.name = "osmChange"
 
 197     # generate an output element for each operation. note: we avoid looking
 
 198     # at the history because it is simpler - but it would be more correct to 
 
 199     # check these assertions.
 
 200     elements.each do |elt|
 
 202         if (elt.version == 1) 
 
 203           # first version, so it must be newly-created.
 
 204           created = XML::Node.new "create"
 
 205           created << elt.to_xml_node
 
 207           # get the previous version from the element history
 
 208           prev_elt = elt.class.find(:first, :conditions => 
 
 209                                     ['id = ? and version = ?',
 
 210                                      elt.id, elt.version])
 
 212             # if the element isn't visible then it must have been deleted, so
 
 213             # output the *previous* XML
 
 214             deleted = XML::Node.new "delete"
 
 215             deleted << prev_elt.to_xml_node
 
 217             # must be a modify, for which we don't need the previous version
 
 219             modified = XML::Node.new "modify"
 
 220             modified << elt.to_xml_node
 
 225     render :text => result.to_s, :content_type => "text/xml"
 
 227   rescue ActiveRecord::RecordNotFound
 
 228     render :nothing => true, :status => :not_found
 
 229   rescue OSM::APIError => ex
 
 230     render ex.render_opts
 
 234   # query changesets by bounding box, time, user or open/closed status.
 
 236     # create the conditions that the user asked for. some or all of
 
 238     conditions = conditions_bbox(params['bbox'])
 
 239     cond_merge conditions, conditions_user(params['user'])
 
 240     cond_merge conditions, conditions_time(params['time'])
 
 241     cond_merge conditions, conditions_open(params['open'])
 
 243     # create the results document
 
 244     results = OSM::API.new.get_xml_doc
 
 246     # add all matching changesets to the XML results document
 
 248                    :conditions => conditions, 
 
 250                    :order => 'created_at desc').each do |cs|
 
 251       results.root << cs.to_xml_node
 
 254     render :text => results.to_s, :content_type => "text/xml"
 
 256   rescue ActiveRecord::RecordNotFound
 
 257     render :nothing => true, :status => :not_found
 
 258   rescue OSM::APIError => ex
 
 259     render ex.render_opts
 
 261     render :text => s, :content_type => "text/plain", :status => :bad_request
 
 265   # updates a changeset's tags. none of the changeset's attributes are
 
 266   # user-modifiable, so they will be ignored.
 
 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.
 
 271   # after succesful update, returns the XML of the changeset.
 
 273     # request *must* be a PUT.
 
 275       render :nothing => true, :status => :method_not_allowed
 
 279     changeset = Changeset.find(params[:id])
 
 280     new_changeset = Changeset.from_xml(request.raw_post)
 
 282     unless new_changeset.nil?
 
 283       changeset.update_from(new_changeset, @user)
 
 284       render :text => changeset.to_xml, :mime_type => "text/xml"
 
 287       render :nothing => true, :status => :bad_request
 
 290   rescue ActiveRecord::RecordNotFound
 
 291     render :nothing => true, :status => :not_found
 
 292   rescue OSM::APIError => ex
 
 293     render ex.render_opts
 
 296   #------------------------------------------------------------
 
 297   # utility functions below.
 
 298   #------------------------------------------------------------  
 
 301   # merge two conditions
 
 306       return [ a_str + " and " + b_str ] + a + b
 
 315   # if a bounding box was specified then parse it and do some sanity 
 
 316   # checks. this is mostly the same as the map call, but without the 
 
 318   def conditions_bbox(bbox)
 
 320       raise "Bounding box should be min_lon,min_lat,max_lon,max_lat" unless bbox.count(',') == 3
 
 321       bbox = sanitise_boundaries(bbox.split(/,/))
 
 322       raise "Minimum longitude should be less than maximum." unless bbox[0] <= bbox[2]
 
 323       raise "Minimum latitude should be less than maximum." unless bbox[1] <= bbox[3]
 
 324       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
 
 325               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
 
 332   # restrict changesets to those by a particular user
 
 333   def conditions_user(user)
 
 335       u = User.find(user.to_i)
 
 336       raise OSM::APINotFoundError unless u.data_public?
 
 337       return ['user_id = ?', u.id]
 
 344   # restrict changes to those during a particular time period
 
 345   def conditions_time(time) 
 
 347       # if there is a range, i.e: comma separated, then the first is 
 
 348       # low, second is high - same as with bounding boxes.
 
 349       if time.count(',') == 1
 
 350         from, to = time.split(/,/).collect { |t| Date.parse(t) }
 
 351         return ['created_at > ? and created_at < ?', from, to]
 
 353         # if there is no comma, assume its a lower limit on time
 
 354         return ['created_at > ?', Date.parse(time)]
 
 359   rescue ArgumentError => ex
 
 360     raise ex.message.to_s
 
 364   # restrict changes to those which are open
 
 365   def conditions_open(open)
 
 366     return open.nil? ? nil : ['open = ?', true]