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