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