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