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