]> git.openstreetmap.org Git - rails.git/blob - app/models/way.rb
Ensure IE/Edge compatibility for routing drag&drop
[rails.git] / app / models / way.rb
1 class Way < ActiveRecord::Base
2   require "xml/libxml"
3
4   include ConsistencyValidations
5   include NotRedactable
6   include ObjectMetadata
7
8   self.table_name = "current_ways"
9
10   belongs_to :changeset
11
12   has_many :old_ways, -> { order(:version) }
13
14   has_many :way_nodes, -> { order(:sequence_id) }
15   has_many :nodes, :through => :way_nodes
16
17   has_many :way_tags
18
19   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
20   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
21
22   validates :id, :uniqueness => true, :presence => { :on => :update },
23                  :numericality => { :on => :update, :integer_only => true }
24   validates :version, :presence => true,
25                       :numericality => { :integer_only => true }
26   validates :changeset_id, :presence => true,
27                            :numericality => { :integer_only => true }
28   validates :timestamp, :presence => true
29   validates :changeset, :associated => true
30   validates :visible, :inclusion => [true, false]
31
32   scope :visible, -> { where(:visible => true) }
33   scope :invisible, -> { where(:visible => false) }
34
35   # Read in xml as text and return it's Way object representation
36   def self.from_xml(xml, create = false)
37     p = XML::Parser.string(xml)
38     doc = p.parse
39
40     doc.find("//osm/way").each do |pt|
41       return Way.from_xml_node(pt, create)
42     end
43     raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
44   rescue LibXML::XML::Error, ArgumentError => ex
45     raise OSM::APIBadXMLError.new("way", xml, ex.message)
46   end
47
48   def self.from_xml_node(pt, create = false)
49     way = Way.new
50
51     raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt["version"].nil?
52     way.version = pt["version"]
53     raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt["changeset"].nil?
54     way.changeset_id = pt["changeset"]
55
56     unless create
57       raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt["id"].nil?
58       way.id = pt["id"].to_i
59       # .to_i will return 0 if there is no number that can be parsed.
60       # We want to make sure that there is no id with zero anyway
61       raise OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0
62     end
63
64     # We don't care about the timestamp nor the visibility as these are either
65     # set explicitly or implicit in the action. The visibility is set to true,
66     # and manually set to false before the actual delete.
67     way.visible = true
68
69     # Start with no tags
70     way.tags = {}
71
72     # Add in any tags from the XML
73     pt.find("tag").each do |tag|
74       raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag["k"].nil?
75       raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag["v"].nil?
76       way.add_tag_keyval(tag["k"], tag["v"])
77     end
78
79     pt.find("nd").each do |nd|
80       way.add_nd_num(nd["ref"])
81     end
82
83     way
84   end
85
86   # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
87   def to_xml
88     doc = OSM::API.new.get_xml_doc
89     doc.root << to_xml_node
90     doc
91   end
92
93   def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
94     el = XML::Node.new "way"
95     el["id"] = id.to_s
96
97     add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
98
99     # make sure nodes are output in sequence_id order
100     ordered_nodes = []
101     way_nodes.each do |nd|
102       if visible_nodes
103         # if there is a list of visible nodes then use that to weed out deleted nodes
104         if visible_nodes[nd.node_id]
105           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
106         end
107       else
108         # otherwise, manually go to the db to check things
109         if nd.node && nd.node.visible?
110           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
111         end
112       end
113     end
114
115     ordered_nodes.each do |nd_id|
116       next unless nd_id && nd_id != "0"
117
118       node_el = XML::Node.new "nd"
119       node_el["ref"] = nd_id
120       el << node_el
121     end
122
123     add_tags_to_xml_node(el, way_tags)
124
125     el
126   end
127
128   def nds
129     @nds ||= way_nodes.collect(&:node_id)
130   end
131
132   def tags
133     @tags ||= Hash[way_tags.collect { |t| [t.k, t.v] }]
134   end
135
136   attr_writer :nds
137
138   attr_writer :tags
139
140   def add_nd_num(n)
141     @nds = [] unless @nds
142     @nds << n.to_i
143   end
144
145   def add_tag_keyval(k, v)
146     @tags = {} unless @tags
147
148     # duplicate tags are now forbidden, so we can't allow values
149     # in the hash to be overwritten.
150     raise OSM::APIDuplicateTagsError.new("way", id, k) if @tags.include? k
151
152     @tags[k] = v
153   end
154
155   ##
156   # the integer coords (i.e: unscaled) bounding box of the way, assuming
157   # straight line segments.
158   def bbox
159     lons = nodes.collect(&:longitude)
160     lats = nodes.collect(&:latitude)
161     BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
162   end
163
164   def update_from(new_way, user)
165     Way.transaction do
166       lock!
167       check_consistency(self, new_way, user)
168       unless new_way.preconditions_ok?(nds)
169         raise OSM::APIPreconditionFailedError.new("Cannot update way #{id}: data is invalid.")
170       end
171
172       self.changeset_id = new_way.changeset_id
173       self.changeset = new_way.changeset
174       self.tags = new_way.tags
175       self.nds = new_way.nds
176       self.visible = true
177       save_with_history!
178     end
179   end
180
181   def create_with_history(user)
182     check_create_consistency(self, user)
183     unless preconditions_ok?
184       raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
185     end
186     self.version = 0
187     self.visible = true
188     save_with_history!
189   end
190
191   def preconditions_ok?(old_nodes = [])
192     return false if nds.empty?
193     if nds.length > MAX_NUMBER_OF_WAY_NODES
194       raise OSM::APITooManyWayNodesError.new(id, nds.length, MAX_NUMBER_OF_WAY_NODES)
195     end
196
197     # check only the new nodes, for efficiency - old nodes having been checked last time and can't
198     # be deleted when they're in-use.
199     new_nds = (nds - old_nodes).sort.uniq
200
201     unless new_nds.empty?
202       # NOTE: nodes are locked here to ensure they can't be deleted before
203       # the current transaction commits.
204       db_nds = Node.where(:id => new_nds, :visible => true).lock("for share")
205
206       if db_nds.length < new_nds.length
207         missing = new_nds - db_nds.collect(&:id)
208         raise OSM::APIPreconditionFailedError.new("Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.")
209       end
210     end
211
212     true
213   end
214
215   def delete_with_history!(new_way, user)
216     raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible
217
218     # need to start the transaction here, so that the database can
219     # provide repeatable reads for the used-by checks. this means it
220     # shouldn't be possible to get race conditions.
221     Way.transaction do
222       lock!
223       check_consistency(self, new_way, user)
224       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
225       raise OSM::APIPreconditionFailedError.new("Way #{id} is still used by relations #{rels.collect(&:id).join(",")}.") unless rels.empty?
226
227       self.changeset_id = new_way.changeset_id
228       self.changeset = new_way.changeset
229
230       self.tags = []
231       self.nds = []
232       self.visible = false
233       save_with_history!
234     end
235   end
236
237   ##
238   # if any referenced nodes are placeholder IDs (i.e: are negative) then
239   # this calling this method will fix them using the map from placeholders
240   # to IDs +id_map+.
241   def fix_placeholders!(id_map, placeholder_id = nil)
242     nds.map! do |node_id|
243       if node_id < 0
244         new_id = id_map[:node][node_id]
245         raise OSM::APIBadUserInput.new("Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}") if new_id.nil?
246         new_id
247       else
248         node_id
249       end
250     end
251   end
252
253   private
254
255   def save_with_history!
256     t = Time.now.getutc
257
258     # update the bounding box, note that this has to be done both before
259     # and after the save, so that nodes from both versions are included in the
260     # bbox. we use a copy of the changeset so that it isn't reloaded
261     # later in the save.
262     cs = changeset
263     cs.update_bbox!(bbox) unless nodes.empty?
264
265     Way.transaction do
266       self.version += 1
267       self.timestamp = t
268       save!
269
270       tags = self.tags
271       WayTag.delete_all(:way_id => id)
272       tags.each do |k, v|
273         tag = WayTag.new
274         tag.way_id = id
275         tag.k = k
276         tag.v = v
277         tag.save!
278       end
279
280       nds = self.nds
281       WayNode.delete_all(:way_id => id)
282       sequence = 1
283       nds.each do |n|
284         nd = WayNode.new
285         nd.id = [id, sequence]
286         nd.node_id = n
287         nd.save!
288         sequence += 1
289       end
290
291       old_way = OldWay.from_way(self)
292       old_way.timestamp = t
293       old_way.save_with_dependencies!
294
295       # reload the way so that the nodes array points to the correct
296       # new set of nodes.
297       reload
298
299       # update and commit the bounding box, now that way nodes
300       # have been updated and we're in a transaction.
301       cs.update_bbox!(bbox) unless nodes.empty?
302
303       # tell the changeset we updated one element only
304       cs.add_changes! 1
305
306       cs.save!
307     end
308   end
309 end