]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Fixing review comments
[rails.git] / app / models / node.rb
1 class Node < ActiveRecord::Base
2   require 'xml/libxml'
3
4   include GeoRecord
5   include ConsistencyValidations
6   include NotRedactable
7
8   self.table_name = "current_nodes"
9
10   belongs_to :changeset
11
12   has_many :old_nodes, :order => :version
13
14   has_many :way_nodes
15   has_many :ways, :through => :way_nodes
16
17   has_many :node_tags
18   
19   has_many :old_way_nodes
20   has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
21
22   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
23   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
24
25   validates_presence_of :id, :on => :update
26   validates_presence_of :timestamp,:version,  :changeset_id
27   validates_uniqueness_of :id
28   validates_inclusion_of :visible, :in => [ true, false ]
29   validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
30   validates_numericality_of :id, :on => :update, :integer_only => true
31   validate :validate_position
32   validates_associated :changeset
33
34   scope :visible, where(:visible => true)
35   scope :invisible, where(:visible => false)
36
37   # Sanity check the latitude and longitude and add an error if it's broken
38   def validate_position
39     errors.add(:base, "Node is not in the world") unless in_world?
40   end
41
42   #
43   # Search for nodes matching tags within bounding_box
44   #
45   # Also adheres to limitations such as within max_number_of_nodes
46   #
47   def self.search(bounding_box, tags = {})
48     # @fixme a bit of a hack to search for only visible nodes
49     # couldn't think of another to add to tags condition
50     #conditions_hash = tags.merge({ 'visible' => 1 })
51   
52     # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
53     #keys = []
54     #values = {}
55
56     #conditions_hash.each do |key,value|
57     #  keys <<  "#{key} = :#{key}"
58     #  values[key.to_sym] = value
59     #end 
60     #conditions = keys.join(' AND ')
61  
62     find_by_area(bounding_box, :conditions => {:visible => true},
63                        :limit => MAX_NUMBER_OF_NODES+1)
64   end
65
66   # Read in xml as text and return it's Node object representation
67   def self.from_xml(xml, create=false)
68     begin
69       p = XML::Parser.string(xml)
70       doc = p.parse
71
72       doc.find('//osm/node').each do |pt|
73         return Node.from_xml_node(pt, create)
74       end
75       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
76     rescue LibXML::XML::Error, ArgumentError => ex
77       raise OSM::APIBadXMLError.new("node", xml, ex.message)
78     end
79   end
80
81   def self.from_xml_node(pt, create=false)
82     node = Node.new
83     
84     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
85     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
86     node.lat = pt['lat'].to_f
87     node.lon = pt['lon'].to_f
88     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
89     node.changeset_id = pt['changeset'].to_i
90
91     raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
92
93     # version must be present unless creating
94     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
95     node.version = create ? 0 : pt['version'].to_i
96
97     unless create
98       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
99       node.id = pt['id'].to_i
100       # .to_i will return 0 if there is no number that can be parsed. 
101       # We want to make sure that there is no id with zero anyway
102       raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
103     end
104
105     # We don't care about the time, as it is explicitly set on create/update/delete
106     # We don't care about the visibility as it is implicit based on the action
107     # and set manually before the actual delete
108     node.visible = true
109
110     # Start with no tags
111     node.tags = Hash.new
112
113     # Add in any tags from the XML
114     pt.find('tag').each do |tag|
115       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
116       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
117       node.add_tag_key_val(tag['k'],tag['v'])
118     end
119
120     return node
121   end
122
123   ##
124   # the bounding box around a node, which is used for determining the changeset's
125   # bounding box
126   def bbox
127     BoundingBox.new(longitude, latitude, longitude, latitude)
128   end
129
130   # Should probably be renamed delete_from to come in line with update
131   def delete_with_history!(new_node, user)
132     unless self.visible
133       raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
134     end
135
136     # need to start the transaction here, so that the database can 
137     # provide repeatable reads for the used-by checks. this means it
138     # shouldn't be possible to get race conditions.
139     Node.transaction do
140       self.lock!
141       check_consistency(self, new_node, user)
142       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
143       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
144       
145       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
146       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
147
148       self.changeset_id = new_node.changeset_id
149       self.tags = {}
150       self.visible = false
151       
152       # update the changeset with the deleted position
153       changeset.update_bbox!(bbox)
154       
155       save_with_history!
156     end
157   end
158
159   def update_from(new_node, user)
160     Node.transaction do
161       self.lock!
162       check_consistency(self, new_node, user)
163       
164       # update changeset first
165       self.changeset_id = new_node.changeset_id
166       self.changeset = new_node.changeset
167       
168       # update changeset bbox with *old* position first
169       changeset.update_bbox!(bbox);
170       
171       # FIXME logic needs to be double checked
172       self.latitude = new_node.latitude 
173       self.longitude = new_node.longitude
174       self.tags = new_node.tags
175       self.visible = true
176       
177       # update changeset bbox with *new* position
178       changeset.update_bbox!(bbox);
179       
180       save_with_history!
181     end
182   end
183   
184   def create_with_history(user)
185     check_create_consistency(self, user)
186     self.version = 0
187     self.visible = true
188
189     # update the changeset to include the new location
190     changeset.update_bbox!(bbox)
191
192     save_with_history!
193   end
194
195   def to_xml
196     doc = OSM::API.new.get_xml_doc
197     doc.root << to_xml_node()
198     return doc
199   end
200
201   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
202     el1 = XML::Node.new 'node'
203     el1['id'] = self.id.to_s
204     el1['lat'] = self.lat.to_s
205     el1['lon'] = self.lon.to_s
206     el1['version'] = self.version.to_s
207     el1['changeset'] = self.changeset_id.to_s
208
209     if changeset_cache.key?(self.changeset_id)
210       # use the cache if available
211     else
212       changeset_cache[self.changeset_id] = self.changeset.user_id
213     end
214
215     user_id = changeset_cache[self.changeset_id]
216
217     if user_display_name_cache.key?(user_id)
218       # use the cache if available
219     elsif self.changeset.user.data_public?
220       user_display_name_cache[user_id] = self.changeset.user.display_name
221     else
222       user_display_name_cache[user_id] = nil
223     end
224
225     if not user_display_name_cache[user_id].nil?
226       el1['user'] = user_display_name_cache[user_id]
227       el1['uid'] = user_id.to_s
228     end
229
230     self.tags.each do |k,v|
231       el2 = XML::Node.new('tag')
232       el2['k'] = k.to_s
233       el2['v'] = v.to_s
234       el1 << el2
235     end
236
237     el1['visible'] = self.visible.to_s
238     el1['timestamp'] = self.timestamp.xmlschema
239     return el1
240   end
241
242   def tags_as_hash
243     return tags
244   end
245
246   def tags
247     unless @tags
248       @tags = {}
249       self.node_tags.each do |tag|
250         @tags[tag.k] = tag.v
251       end
252     end
253     @tags
254   end
255
256   def tags=(t)
257     @tags = t 
258   end 
259
260   def add_tag_key_val(k,v)
261     @tags = Hash.new unless @tags
262
263     # duplicate tags are now forbidden, so we can't allow values
264     # in the hash to be overwritten.
265     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
266
267     @tags[k] = v
268   end
269
270   ##
271   # are the preconditions OK? this is mainly here to keep the duck
272   # typing interface the same between nodes, ways and relations.
273   def preconditions_ok?
274     in_world?
275   end
276
277   ##
278   # dummy method to make the interfaces of node, way and relation
279   # more consistent.
280   def fix_placeholders!(id_map, placeholder_id = nil)
281     # nodes don't refer to anything, so there is nothing to do here
282   end
283   
284   private
285
286   def save_with_history!
287     t = Time.now.getutc
288     Node.transaction do
289       self.version += 1
290       self.timestamp = t
291       self.save!
292
293       # Create a NodeTag
294       tags = self.tags
295       NodeTag.delete_all(:node_id => self.id)
296       tags.each do |k,v|
297         tag = NodeTag.new
298         tag.node_id = self.id
299         tag.k = k 
300         tag.v = v 
301         tag.save!
302       end 
303
304       # Create an OldNode
305       old_node = OldNode.from_node(self)
306       old_node.timestamp = t
307       old_node.save_with_dependencies!
308
309       # tell the changeset we updated one element only
310       changeset.add_changes! 1
311
312       # save the changeset in case of bounding box updates
313       changeset.save!
314     end
315   end
316   
317 end