]> git.openstreetmap.org Git - rails.git/blob - app/models/way.rb
2b6f562be6c2fbbc95c290a70a4728d701dc2c5e
[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, user_display_name_cache = nil)
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     user_display_name_cache = {} if user_display_name_cache.nil?
101
102     if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
103       # use the cache if available
104     elsif self.changeset.user.data_public?
105       user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
106     else
107       user_display_name_cache[self.changeset.user_id] = nil
108     end
109
110     if not user_display_name_cache[self.changeset.user_id].nil?
111       el1['user'] = user_display_name_cache[self.changeset.user_id]
112       el1['uid'] = self.changeset.user_id.to_s
113     end
114
115     # make sure nodes are output in sequence_id order
116     ordered_nodes = []
117     self.way_nodes.each do |nd|
118       if visible_nodes
119         # if there is a list of visible nodes then use that to weed out deleted nodes
120         if visible_nodes[nd.node_id]
121           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
122         end
123       else
124         # otherwise, manually go to the db to check things
125         if nd.node and nd.node.visible?
126           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
127         end
128       end
129     end
130
131     ordered_nodes.each do |nd_id|
132       if nd_id and nd_id != '0'
133         e = XML::Node.new 'nd'
134         e['ref'] = nd_id
135         el1 << e
136       end
137     end
138
139     self.way_tags.each do |tag|
140       e = XML::Node.new 'tag'
141       e['k'] = tag.k
142       e['v'] = tag.v
143       el1 << e
144     end
145     return el1
146   end 
147
148   def nds
149     unless @nds
150       @nds = Array.new
151       self.way_nodes.each do |nd|
152         @nds += [nd.node_id]
153       end
154     end
155     @nds
156   end
157
158   def tags
159     unless @tags
160       @tags = {}
161       self.way_tags.each do |tag|
162         @tags[tag.k] = tag.v
163       end
164     end
165     @tags
166   end
167
168   def nds=(s)
169     @nds = s
170   end
171
172   def tags=(t)
173     @tags = t
174   end
175
176   def add_nd_num(n)
177     @nds = Array.new unless @nds
178     @nds << n.to_i
179   end
180
181   def add_tag_keyval(k, v)
182     @tags = Hash.new unless @tags
183
184     # duplicate tags are now forbidden, so we can't allow values
185     # in the hash to be overwritten.
186     raise OSM::APIDuplicateTagsError.new("way", self.id, k) if @tags.include? k
187
188     @tags[k] = v
189   end
190
191   ##
192   # the integer coords (i.e: unscaled) bounding box of the way, assuming
193   # straight line segments.
194   def bbox
195     lons = nodes.collect { |n| n.longitude }
196     lats = nodes.collect { |n| n.latitude }
197     [ lons.min, lats.min, lons.max, lats.max ]
198   end
199
200   def update_from(new_way, user)
201     check_consistency(self, new_way, user)
202     unless new_way.preconditions_ok?
203       raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.")
204     end
205
206     self.changeset_id = new_way.changeset_id
207     self.changeset = new_way.changeset
208     self.tags = new_way.tags
209     self.nds = new_way.nds
210     self.visible = true
211     save_with_history!
212   end
213
214   def create_with_history(user)
215     check_create_consistency(self, user)
216     unless self.preconditions_ok?
217       raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
218     end
219     self.version = 0
220     self.visible = true
221     save_with_history!
222   end
223
224   def preconditions_ok?
225     return false if self.nds.empty?
226     if self.nds.length > APP_CONFIG['max_number_of_way_nodes']
227       raise OSM::APITooManyWayNodesError.new(self.nds.length, APP_CONFIG['max_number_of_way_nodes'])
228     end
229     self.nds.each do |n|
230       node = Node.find(:first, :conditions => ["id = ?", n])
231       unless node and node.visible
232         raise OSM::APIPreconditionFailedError.new("The node with id #{n} either does not exist, or is not visible")
233       end
234     end
235     return true
236   end
237
238   def delete_with_history!(new_way, user)
239     unless self.visible
240       raise OSM::APIAlreadyDeletedError.new("way", new_way.id)
241     end
242     
243     # need to start the transaction here, so that the database can 
244     # provide repeatable reads for the used-by checks. this means it
245     # shouldn't be possible to get race conditions.
246     Way.transaction do
247       check_consistency(self, new_way, user)
248       if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id",
249                              :conditions => [ "visible = ? AND member_type='Way' and member_id=? ", true, self.id])
250         raise OSM::APIPreconditionFailedError.new("You need to make sure that this way is not a member of a relation.")
251       else
252         self.changeset_id = new_way.changeset_id
253         self.changeset = new_way.changeset
254
255         self.tags = []
256         self.nds = []
257         self.visible = false
258         save_with_history!
259       end
260     end
261   end
262
263   # Find nodes that belong to this way only
264   def unshared_node_ids
265     node_ids = self.nodes.collect { |node| node.id }
266
267     unless node_ids.empty?
268       way_nodes = WayNode.find(:all, :conditions => "node_id in (#{node_ids.join(',')}) and id != #{self.id}")
269       node_ids = node_ids - way_nodes.collect { |way_node| way_node.node_id }
270     end
271
272     return node_ids
273   end
274
275   # Temporary method to match interface to nodes
276   def tags_as_hash
277     return self.tags
278   end
279
280   ##
281   # if any referenced nodes are placeholder IDs (i.e: are negative) then
282   # this calling this method will fix them using the map from placeholders 
283   # to IDs +id_map+. 
284   def fix_placeholders!(id_map)
285     self.nds.map! do |node_id|
286       if node_id < 0
287         new_id = id_map[:node][node_id]
288         raise "invalid placeholder for #{node_id.inspect}: #{new_id.inspect}" if new_id.nil?
289         new_id
290       else
291         node_id
292       end
293     end
294   end
295
296   private
297   
298   def save_with_history!
299     t = Time.now.getutc
300
301     # update the bounding box, note that this has to be done both before 
302     # and after the save, so that nodes from both versions are included in the 
303     # bbox. we use a copy of the changeset so that it isn't reloaded
304     # later in the save.
305     cs = self.changeset
306     cs.update_bbox!(bbox) unless nodes.empty?
307
308     Way.transaction do
309       self.version += 1
310       self.timestamp = t
311       self.save!
312
313       tags = self.tags
314       WayTag.delete_all(['id = ?', self.id])
315       tags.each do |k,v|
316         tag = WayTag.new
317         tag.k = k
318         tag.v = v
319         tag.id = self.id
320         tag.save!
321       end
322
323       nds = self.nds
324       WayNode.delete_all(['id = ?', self.id])
325       sequence = 1
326       nds.each do |n|
327         nd = WayNode.new
328         nd.id = [self.id, sequence]
329         nd.node_id = n
330         nd.save!
331         sequence += 1
332       end
333
334       old_way = OldWay.from_way(self)
335       old_way.timestamp = t
336       old_way.save_with_dependencies!
337
338       # reload the way so that the nodes array points to the correct
339       # new set of nodes.
340       self.reload
341
342       # update and commit the bounding box, now that way nodes 
343       # have been updated and we're in a transaction.
344       cs.update_bbox!(bbox) unless nodes.empty?
345
346       # tell the changeset we updated one element only
347       cs.add_changes! 1
348
349       cs.save!
350     end
351   end
352
353 end