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