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