]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Escape fragment identifiers in wikipedia URLs
[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   include ObjectMetadata
8
9   self.table_name = "current_nodes"
10
11   belongs_to :changeset
12
13   has_many :old_nodes, -> { order(:version) }
14
15   has_many :way_nodes
16   has_many :ways, :through => :way_nodes
17
18   has_many :node_tags
19
20   has_many :old_way_nodes
21   has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
22
23   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
24   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
25
26   validates :id, :uniqueness => true, :presence => { :on => :update },
27                  :numericality => { :on => :update, :integer_only => true }
28   validates :version, :presence => true,
29                       :numericality => { :integer_only => true }
30   validates :changeset_id, :presence => true,
31                            :numericality => { :integer_only => true }
32   validates :latitude, :presence => true,
33                        :numericality => { :integer_only => true }
34   validates :longitude, :presence => true,
35                         :numericality => { :integer_only => true }
36   validates :timestamp, :presence => true
37   validates :changeset, :associated => true
38   validates :visible, :inclusion => [true, false]
39
40   validate :validate_position
41
42   scope :visible, -> { where(:visible => true) }
43   scope :invisible, -> { where(:visible => false) }
44
45   # Sanity check the latitude and longitude and add an error if it's broken
46   def validate_position
47     errors.add(:base, "Node is not in the world") unless in_world?
48   end
49
50   # Read in xml as text and return it's Node object representation
51   def self.from_xml(xml, create = false)
52     p = XML::Parser.string(xml)
53     doc = p.parse
54
55     doc.find("//osm/node").each do |pt|
56       return Node.from_xml_node(pt, create)
57     end
58     fail OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
59   rescue LibXML::XML::Error, ArgumentError => ex
60     raise OSM::APIBadXMLError.new("node", xml, ex.message)
61   end
62
63   def self.from_xml_node(pt, create = false)
64     node = Node.new
65
66     fail OSM::APIBadXMLError.new("node", pt, "lat missing") if pt["lat"].nil?
67     fail OSM::APIBadXMLError.new("node", pt, "lon missing") if pt["lon"].nil?
68     node.lat = OSM.parse_float(pt["lat"], OSM::APIBadXMLError, "node", pt, "lat not a number")
69     node.lon = OSM.parse_float(pt["lon"], OSM::APIBadXMLError, "node", pt, "lon not a number")
70     fail OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt["changeset"].nil?
71     node.changeset_id = pt["changeset"].to_i
72
73     fail OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
74
75     # version must be present unless creating
76     fail OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
77     node.version = create ? 0 : pt["version"].to_i
78
79     unless create
80       fail OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
81       node.id = pt["id"].to_i
82       # .to_i will return 0 if there is no number that can be parsed.
83       # We want to make sure that there is no id with zero anyway
84       fail OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
85     end
86
87     # We don't care about the time, as it is explicitly set on create/update/delete
88     # We don't care about the visibility as it is implicit based on the action
89     # and set manually before the actual delete
90     node.visible = true
91
92     # Start with no tags
93     node.tags = {}
94
95     # Add in any tags from the XML
96     pt.find("tag").each do |tag|
97       fail OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag["k"].nil?
98       fail OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag["v"].nil?
99       node.add_tag_key_val(tag["k"], tag["v"])
100     end
101
102     node
103   end
104
105   ##
106   # the bounding box around a node, which is used for determining the changeset's
107   # bounding box
108   def bbox
109     BoundingBox.new(longitude, latitude, longitude, latitude)
110   end
111
112   # Should probably be renamed delete_from to come in line with update
113   def delete_with_history!(new_node, user)
114     fail OSM::APIAlreadyDeletedError.new("node", new_node.id) unless visible
115
116     # need to start the transaction here, so that the database can
117     # provide repeatable reads for the used-by checks. this means it
118     # shouldn't be possible to get race conditions.
119     Node.transaction do
120       self.lock!
121       check_consistency(self, new_node, user)
122       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
123       fail OSM::APIPreconditionFailedError.new("Node #{id} is still used by ways #{ways.collect(&:id).join(",")}.") unless ways.empty?
124
125       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
126       fail OSM::APIPreconditionFailedError.new("Node #{id} is still used by relations #{rels.collect(&:id).join(",")}.") unless rels.empty?
127
128       self.changeset_id = new_node.changeset_id
129       self.tags = {}
130       self.visible = false
131
132       # update the changeset with the deleted position
133       changeset.update_bbox!(bbox)
134
135       save_with_history!
136     end
137   end
138
139   def update_from(new_node, user)
140     Node.transaction do
141       self.lock!
142       check_consistency(self, new_node, user)
143
144       # update changeset first
145       self.changeset_id = new_node.changeset_id
146       self.changeset = new_node.changeset
147
148       # update changeset bbox with *old* position first
149       changeset.update_bbox!(bbox)
150
151       # FIXME: logic needs to be double checked
152       self.latitude = new_node.latitude
153       self.longitude = new_node.longitude
154       self.tags = new_node.tags
155       self.visible = true
156
157       # update changeset bbox with *new* position
158       changeset.update_bbox!(bbox)
159
160       save_with_history!
161     end
162   end
163
164   def create_with_history(user)
165     check_create_consistency(self, user)
166     self.version = 0
167     self.visible = true
168
169     # update the changeset to include the new location
170     changeset.update_bbox!(bbox)
171
172     save_with_history!
173   end
174
175   def to_xml
176     doc = OSM::API.new.get_xml_doc
177     doc.root << to_xml_node
178     doc
179   end
180
181   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
182     el = XML::Node.new "node"
183     el["id"] = id.to_s
184
185     add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
186
187     if self.visible?
188       el["lat"] = lat.to_s
189       el["lon"] = lon.to_s
190     end
191
192     add_tags_to_xml_node(el, node_tags)
193
194     el
195   end
196
197   def tags_as_hash
198     tags
199   end
200
201   def tags
202     @tags ||= Hash[node_tags.collect { |t| [t.k, t.v] }]
203   end
204
205   attr_writer :tags
206
207   def add_tag_key_val(k, v)
208     @tags = {} unless @tags
209
210     # duplicate tags are now forbidden, so we can't allow values
211     # in the hash to be overwritten.
212     fail OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
213
214     @tags[k] = v
215   end
216
217   ##
218   # are the preconditions OK? this is mainly here to keep the duck
219   # typing interface the same between nodes, ways and relations.
220   def preconditions_ok?
221     in_world?
222   end
223
224   ##
225   # dummy method to make the interfaces of node, way and relation
226   # more consistent.
227   def fix_placeholders!(_id_map, _placeholder_id = nil)
228     # nodes don't refer to anything, so there is nothing to do here
229   end
230
231   private
232
233   def save_with_history!
234     t = Time.now.getutc
235     Node.transaction do
236       self.version += 1
237       self.timestamp = t
238       self.save!
239
240       # Create a NodeTag
241       tags = self.tags
242       NodeTag.delete_all(:node_id => id)
243       tags.each do |k, v|
244         tag = NodeTag.new
245         tag.node_id = id
246         tag.k = k
247         tag.v = v
248         tag.save!
249       end
250
251       # Create an OldNode
252       old_node = OldNode.from_node(self)
253       old_node.timestamp = t
254       old_node.save_with_dependencies!
255
256       # tell the changeset we updated one element only
257       changeset.add_changes! 1
258
259       # save the changeset in case of bounding box updates
260       changeset.save!
261     end
262   end
263 end