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