]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Add glow to search box
[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 = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number")
87     node.lon = OSM.parse_float(pt['lon'], OSM::APIBadXMLError, "node", pt, "lon not a number")
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['version'] = self.version.to_s
205     el1['changeset'] = self.changeset_id.to_s
206
207     if self.visible?
208       el1['lat'] = self.lat.to_s
209       el1['lon'] = self.lon.to_s
210     end
211
212     if changeset_cache.key?(self.changeset_id)
213       # use the cache if available
214     else
215       changeset_cache[self.changeset_id] = self.changeset.user_id
216     end
217
218     user_id = changeset_cache[self.changeset_id]
219
220     if user_display_name_cache.key?(user_id)
221       # use the cache if available
222     elsif self.changeset.user.data_public?
223       user_display_name_cache[user_id] = self.changeset.user.display_name
224     else
225       user_display_name_cache[user_id] = nil
226     end
227
228     if not user_display_name_cache[user_id].nil?
229       el1['user'] = user_display_name_cache[user_id]
230       el1['uid'] = user_id.to_s
231     end
232
233     self.tags.each do |k,v|
234       el2 = XML::Node.new('tag')
235       el2['k'] = k.to_s
236       el2['v'] = v.to_s
237       el1 << el2
238     end
239
240     el1['visible'] = self.visible.to_s
241     el1['timestamp'] = self.timestamp.xmlschema
242     return el1
243   end
244
245   def tags_as_hash
246     return tags
247   end
248
249   def tags
250     unless @tags
251       @tags = {}
252       self.node_tags.each do |tag|
253         @tags[tag.k] = tag.v
254       end
255     end
256     @tags
257   end
258
259   def tags=(t)
260     @tags = t 
261   end 
262
263   def add_tag_key_val(k,v)
264     @tags = Hash.new unless @tags
265
266     # duplicate tags are now forbidden, so we can't allow values
267     # in the hash to be overwritten.
268     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
269
270     @tags[k] = v
271   end
272
273   ##
274   # are the preconditions OK? this is mainly here to keep the duck
275   # typing interface the same between nodes, ways and relations.
276   def preconditions_ok?
277     in_world?
278   end
279
280   ##
281   # dummy method to make the interfaces of node, way and relation
282   # more consistent.
283   def fix_placeholders!(id_map, placeholder_id = nil)
284     # nodes don't refer to anything, so there is nothing to do here
285   end
286   
287   private
288
289   def save_with_history!
290     t = Time.now.getutc
291     Node.transaction do
292       self.version += 1
293       self.timestamp = t
294       self.save!
295
296       # Create a NodeTag
297       tags = self.tags
298       NodeTag.delete_all(:node_id => self.id)
299       tags.each do |k,v|
300         tag = NodeTag.new
301         tag.node_id = self.id
302         tag.k = k 
303         tag.v = v 
304         tag.save!
305       end 
306
307       # Create an OldNode
308       old_node = OldNode.from_node(self)
309       old_node.timestamp = t
310       old_node.save_with_dependencies!
311
312       # tell the changeset we updated one element only
313       changeset.add_changes! 1
314
315       # save the changeset in case of bounding box updates
316       changeset.save!
317     end
318   end
319   
320 end