]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
775f1fd3b22b6ba86d282c72ae5741339b96db6f
[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     begin
87       node.lat = Float(pt['lat'])
88     rescue
89       raise OSM::APIBadXMLError.new("node", pt, "lat not a number")
90     end
91     begin
92       node.lon = Float(pt['lon'])
93     rescue
94       raise OSM::APIBadXMLError.new("node", pt, "lon not a number")
95     end
96     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
97     node.changeset_id = pt['changeset'].to_i
98
99     raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
100
101     # version must be present unless creating
102     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
103     node.version = create ? 0 : pt['version'].to_i
104
105     unless create
106       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
107       node.id = pt['id'].to_i
108       # .to_i will return 0 if there is no number that can be parsed. 
109       # We want to make sure that there is no id with zero anyway
110       raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
111     end
112
113     # We don't care about the time, as it is explicitly set on create/update/delete
114     # We don't care about the visibility as it is implicit based on the action
115     # and set manually before the actual delete
116     node.visible = true
117
118     # Start with no tags
119     node.tags = Hash.new
120
121     # Add in any tags from the XML
122     pt.find('tag').each do |tag|
123       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
124       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
125       node.add_tag_key_val(tag['k'],tag['v'])
126     end
127
128     return node
129   end
130
131   ##
132   # the bounding box around a node, which is used for determining the changeset's
133   # bounding box
134   def bbox
135     BoundingBox.new(longitude, latitude, longitude, latitude)
136   end
137
138   # Should probably be renamed delete_from to come in line with update
139   def delete_with_history!(new_node, user)
140     unless self.visible
141       raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
142     end
143
144     # need to start the transaction here, so that the database can 
145     # provide repeatable reads for the used-by checks. this means it
146     # shouldn't be possible to get race conditions.
147     Node.transaction do
148       self.lock!
149       check_consistency(self, new_node, user)
150       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
151       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
152       
153       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
154       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
155
156       self.changeset_id = new_node.changeset_id
157       self.tags = {}
158       self.visible = false
159       
160       # update the changeset with the deleted position
161       changeset.update_bbox!(bbox)
162       
163       save_with_history!
164     end
165   end
166
167   def update_from(new_node, user)
168     Node.transaction do
169       self.lock!
170       check_consistency(self, new_node, user)
171       
172       # update changeset first
173       self.changeset_id = new_node.changeset_id
174       self.changeset = new_node.changeset
175       
176       # update changeset bbox with *old* position first
177       changeset.update_bbox!(bbox);
178       
179       # FIXME logic needs to be double checked
180       self.latitude = new_node.latitude 
181       self.longitude = new_node.longitude
182       self.tags = new_node.tags
183       self.visible = true
184       
185       # update changeset bbox with *new* position
186       changeset.update_bbox!(bbox);
187       
188       save_with_history!
189     end
190   end
191   
192   def create_with_history(user)
193     check_create_consistency(self, user)
194     self.version = 0
195     self.visible = true
196
197     # update the changeset to include the new location
198     changeset.update_bbox!(bbox)
199
200     save_with_history!
201   end
202
203   def to_xml
204     doc = OSM::API.new.get_xml_doc
205     doc.root << to_xml_node()
206     return doc
207   end
208
209   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
210     el1 = XML::Node.new 'node'
211     el1['id'] = self.id.to_s
212     el1['version'] = self.version.to_s
213     el1['changeset'] = self.changeset_id.to_s
214
215     if self.visible?
216       el1['lat'] = self.lat.to_s
217       el1['lon'] = self.lon.to_s
218     end
219
220     if changeset_cache.key?(self.changeset_id)
221       # use the cache if available
222     else
223       changeset_cache[self.changeset_id] = self.changeset.user_id
224     end
225
226     user_id = changeset_cache[self.changeset_id]
227
228     if user_display_name_cache.key?(user_id)
229       # use the cache if available
230     elsif self.changeset.user.data_public?
231       user_display_name_cache[user_id] = self.changeset.user.display_name
232     else
233       user_display_name_cache[user_id] = nil
234     end
235
236     if not user_display_name_cache[user_id].nil?
237       el1['user'] = user_display_name_cache[user_id]
238       el1['uid'] = user_id.to_s
239     end
240
241     self.tags.each do |k,v|
242       el2 = XML::Node.new('tag')
243       el2['k'] = k.to_s
244       el2['v'] = v.to_s
245       el1 << el2
246     end
247
248     el1['visible'] = self.visible.to_s
249     el1['timestamp'] = self.timestamp.xmlschema
250     return el1
251   end
252
253   def tags_as_hash
254     return tags
255   end
256
257   def tags
258     unless @tags
259       @tags = {}
260       self.node_tags.each do |tag|
261         @tags[tag.k] = tag.v
262       end
263     end
264     @tags
265   end
266
267   def tags=(t)
268     @tags = t 
269   end 
270
271   def add_tag_key_val(k,v)
272     @tags = Hash.new unless @tags
273
274     # duplicate tags are now forbidden, so we can't allow values
275     # in the hash to be overwritten.
276     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
277
278     @tags[k] = v
279   end
280
281   ##
282   # are the preconditions OK? this is mainly here to keep the duck
283   # typing interface the same between nodes, ways and relations.
284   def preconditions_ok?
285     in_world?
286   end
287
288   ##
289   # dummy method to make the interfaces of node, way and relation
290   # more consistent.
291   def fix_placeholders!(id_map, placeholder_id = nil)
292     # nodes don't refer to anything, so there is nothing to do here
293   end
294   
295   private
296
297   def save_with_history!
298     t = Time.now.getutc
299     Node.transaction do
300       self.version += 1
301       self.timestamp = t
302       self.save!
303
304       # Create a NodeTag
305       tags = self.tags
306       NodeTag.delete_all(:node_id => self.id)
307       tags.each do |k,v|
308         tag = NodeTag.new
309         tag.node_id = self.id
310         tag.k = k 
311         tag.v = v 
312         tag.save!
313       end 
314
315       # Create an OldNode
316       old_node = OldNode.from_node(self)
317       old_node.timestamp = t
318       old_node.save_with_dependencies!
319
320       # tell the changeset we updated one element only
321       changeset.add_changes! 1
322
323       # save the changeset in case of bounding box updates
324       changeset.save!
325     end
326   end
327   
328 end