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