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