1 # AMF Controller is a semi-standalone API for Flash clients, particularly Potlatch.
2 # All interaction between Potlatch (as a .SWF application) and the
3 # OSM database takes place using this controller. Messages are
4 # encoded in the Actionscript Message Format (AMF).
6 # See Also Potlatch::Potlatch and Potlatch::AMF
9 # editions Systeme D / Richard Fairhurst 2004-2008
11 # All in/out parameters are floats unless explicitly stated.
13 # to trap errors (getway_old,putway,putpoi,deleteway only):
14 # return(-1,"message") <-- just puts up a dialogue
15 # return(-2,"message") <-- also asks the user to e-mail me
17 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
18 class AmfController < ApplicationController
24 before_filter :check_write_availability
26 # Main AMF handler. Tha talk method takes in AMF, figures out what to do and dispatched to the appropriate private method
28 req=StringIO.new(request.raw_post+0.chr) # Get POST data as request
29 # (cf http://www.ruby-forum.com/topic/122163)
30 req.read(2) # Skip version indicator and client ID
31 results={} # Results of each body
32 renumberednodes={} # Shared across repeated putways
33 renumberedways={} # Shared across repeated putways
38 headers=AMF.getint(req) # Read number of headers
40 headers.times do # Read each header
41 name=AMF.getstring(req) # |
42 req.getc # | skip boolean
43 value=AMF.getvalue(req) # |
44 header["name"]=value # |
47 bodies=AMF.getint(req) # Read number of bodies
48 bodies.times do # Read each body
49 message=AMF.getstring(req) # | get message name
50 index=AMF.getstring(req) # | get index in response sequence
51 bytes=AMF.getlong(req) # | get total size in bytes
52 args=AMF.getvalue(req) # | get response (probably an array)
55 when 'getpresets'; results[index]=AMF.putdata(index,getpresets)
56 when 'whichways'; results[index]=AMF.putdata(index,whichways(args))
57 when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(args))
58 when 'getway'; results[index]=AMF.putdata(index,getway(args))
59 when 'getrelation'; results[index]=AMF.putdata(index,getrelation(args))
60 when 'getway_old'; results[index]=AMF.putdata(index,getway_old(args))
61 when 'getway_history'; results[index]=AMF.putdata(index,getway_history(args))
62 when 'putway'; r=putway(args,renumberednodes)
65 renumberedways[r[1]] = r[2]
67 results[index]=AMF.putdata(index,r)
68 when 'putrelation'; results[index]=AMF.putdata(index,putrelation(args, renumberednodes, renumberedways))
69 when 'deleteway'; results[index]=AMF.putdata(index,deleteway(args))
70 when 'putpoi'; results[index]=AMF.putdata(index,putpoi(args))
71 when 'getpoi'; results[index]=AMF.putdata(index,getpoi(args))
78 RAILS_DEFAULT_LOGGER.info(" Response: start")
79 a,b=results.length.divmod(256)
80 render :content_type => "application/x-amf", :text => proc { |response, output|
81 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
86 RAILS_DEFAULT_LOGGER.info(" Response: end")
91 # Return presets (default tags and crap) to potlatch.
92 # Uses POTLATCH_PRESETS global, set up in OSM::Potlatch
94 return POTLATCH_PRESETS
98 # Find all the way ids and nodes (including tags and projected lat/lng) which aren't part of those ways in an are
100 # The argument is an array containing the following, in order:
101 # 0. minimum longitude
102 # 1. minimum latitude
103 # 2. maximum longitude
104 # 3. maximum latitude
105 # 4. baselong, 5. basey, 6. masterscale as above
106 def whichways(args) #:doc:
107 xmin = args[0].to_f-0.01
108 ymin = args[1].to_f-0.01
109 xmax = args[2].to_f+0.01
110 ymax = args[3].to_f+0.01
113 masterscale = args[6]
115 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
117 # find the way ids in an area
118 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => "current_nodes.visible = 1", :include => :ways)
119 way_ids = nodes_in_area.collect { |node| node.way_ids }.flatten.uniq
121 # find the node ids in an area that aren't part of ways
122 nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
123 points = nodes_not_used_in_area.collect { |n| [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash] }
125 # find the relations used by those nodes and ways
126 relations = nodes_in_area.collect { |node| node.containing_relations.visible }.flatten +
127 way_ids.collect { |id| Way.find(id).containing_relations.visible }.flatten
128 relation_ids = relations.collect { |relation| relation.id }.uniq
130 [way_ids,points,relation_ids]
133 # ----- whichways_deleted
134 # return array of deleted ways in current bounding box
136 # does: finds all deleted ways with a deleted node in bounding box
137 # out: [0] array of way ids
138 def whichways_deleted(args) #:doc:
139 xmin = args[0].to_f-0.01
140 ymin = args[1].to_f-0.01
141 xmax = args[2].to_f+0.01
142 ymax = args[3].to_f+0.01
145 masterscale = args[6]
148 SELECT DISTINCT current_ways.id
149 FROM current_nodes,way_nodes,current_ways
150 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
151 AND way_nodes.node_id=current_nodes.id
152 AND way_nodes.id=current_ways.id
153 AND current_nodes.visible=0
154 AND current_ways.visible=0
156 waylist = ActiveRecord::Base.connection.select_all(sql)
157 ways = waylist.collect {|a| a['id'].to_i }
162 # Get a way with all of it's nodes and tags
163 # The input is an array with the following components, in order:
164 # 0. wayid - the ID of the way to get
165 # 1. baselong - origin of SWF map (longitude)
166 # 2. basey - origin of SWF map (latitude)
167 # 3. masterscale - SWF map scale
169 # The output is an array which contains all the nodes (with projected
170 # latitude and longitude) and tags for a way (and all the nodes tags).
171 # It also has the way's unprojected (WGS84) bbox.
173 # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
174 # FIXME: the argument splitting should be done in the 'talk' method, not here
175 def getway(args) #:doc:
176 wayid,baselong,basey,masterscale = args
179 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
181 # Ideally we would do ":include => :nodes" here but if we do that
182 # then rails only seems to return the first copy of a node when a
183 # way includes a node more than once
184 way = Way.find(wayid)
190 way.nodes.each do |node|
191 projected_longitude = node.lon_potlatch(baselong,masterscale) # do projection for potlatch
192 projected_latitude = node.lat_potlatch(basey,masterscale)
194 tags_hash = node.tags_as_hash
196 points << [projected_longitude, projected_latitude, id, nil, tags_hash]
197 long_array << projected_longitude
198 lat_array << projected_latitude
201 [wayid,points,way.tags,long_array.min,long_array.max,lat_array.min,lat_array.max]
205 # returns old version of way
207 # [1] way version to get (or -1 for "last deleted version")
208 # [2] baselong, [3] basey, [4] masterscale
209 # does: gets old version of way and all constituent nodes
210 # for undelete, always uses the most recent version of each node
211 # (even if it's moved)
212 # for revert, uses the historic version of each node, but if that node is
213 # still visible and has been changed since, generates a new node id
214 # out: [0] 0 (code for success), [1] SWF object name,
215 # [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
216 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
218 def getway_old(args) #:doc:
219 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
220 # if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
222 wayid,version,baselong,basey,masterscale=args
224 version = version.to_i
226 xmax = ymax = -999999
230 version=getlastversion(wayid,version)
234 readwayquery_old(wayid,version,historic).each { |row|
235 points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,row['visible'].to_i,tag2array(row['tags'].to_s)]
236 xmin=[xmin,row['longitude'].to_f].min
237 xmax=[xmax,row['longitude'].to_f].max
238 ymin=[ymin,row['latitude' ].to_f].min
239 ymax=[ymax,row['latitude' ].to_f].max
242 # get tags from this version
244 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
245 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
246 attributes['history']="Retrieved from v"+version.to_s
248 [0,wayid,points,attributes,xmin,xmax,ymin,ymax,version]
251 # ----- getway_history
252 # find history of a way
254 # does: finds history of a way
255 # out: [0] array of previous versions (where each is
256 # [0] version, [1] db timestamp (string),
257 # [2] visible 0 or 1,
258 # [3] username or 'anonymous' (string))
259 def getway_history(args) #:doc:
263 SELECT version,timestamp,visible,display_name,data_public
265 WHERE ways.id=#{wayid}
266 AND ways.user_id=users.id
268 ORDER BY version DESC
270 histlist=ActiveRecord::Base.connection.select_all(sql)
271 histlist.each { |row|
272 if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
273 history<<[row['version'],row['timestamp'],row['visible'],user]
279 # Get a relation with all of it's tags, and member IDs
280 # The input is an array with the following components, in order:
281 # 0. relid - the ID of the relation to get
283 # The output is an array which contains:
284 # [0] relation id, [1] hash of tags, [2] list of members
285 def getrelation(args) #:doc:
289 RAILS_DEFAULT_LOGGER.info(" Message: getrel, id=#{relid}")
291 rel = Relation.find(relid)
293 [relid,rel.tags,rel.members]#nodes,ways]
297 # save relation to the database
298 # in: [0] user token (string),
299 # [1] original relation id (may be negative),
300 # [2] hash of tags, [3] list of members,
302 # out: [0] 0 (success), [1] original relation id (unchanged),
303 # [2] new relation id
304 def putrelation(args, renumberednodes, renumberedways) #:doc:
305 usertoken,relid,tags,members,visible=args
306 uid=getuserid(usertoken)
307 if !uid then return -1,"You are not logged in, so the point could not be saved." end
310 visible = visible.to_i
312 # create a new relation, or find the existing one
316 rel = Relation.find(relid)
319 # check the members are all positive, and correctly type
324 mid = renumberednodes[mid] if m[0] == 'node'
325 mid = renumberedways[mid] if m[0] == 'way'
327 return -2, "Negative ID unresolved"
330 typedmembers << [m[0], mid, m[2]]
333 # assign new contents
334 rel.members = typedmembers
336 rel.visible = visible
339 # check it then save it
340 # BUG: the following is commented out because it always fails on my
341 # install. I think it's a Rails bug.
343 #if !rel.preconditions_ok?
344 # return -2, "Relation preconditions failed"
346 rel.save_with_history!
353 # saves a way to the database
354 # in: [0] user token (string),
355 # [1] original way id (may be negative),
356 # [2] array of points (as getway/getway_old),
357 # [3] hash of way tags,
358 # [4] original way version (0 if not a reverted/undeleted way),
359 # [5] baselong, [6] basey, [7] masterscale
360 # does: saves way to the database
361 # all constituent nodes are created/updated as necessary
362 # (or deleted if they were in the old version and are otherwise unused)
363 # out: [0] 0 (code for success), [1] original way id (unchanged),
364 # [2] new way id, [3] hash of renumbered nodes (old id=>new id),
365 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
366 def putway(args,renumberednodes) #:doc:
367 RAILS_DEFAULT_LOGGER.info(" putway started")
368 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
369 uid=getuserid(usertoken)
370 if !uid then return -1,"You are not logged in, so the way could not be saved." end
372 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
373 db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
374 db_now='@now'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
375 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
376 originalway=originalway.to_i
377 oldversion=oldversion.to_i
379 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
381 # -- Check for null IDs, short ways or lats=90
384 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
385 if coord2lat(a[1],masterscale,basey)==90 then return -2,"Server error - node with lat -90 found in way #{originalway}." end
388 if points.length<2 then return -2,"Server error - way is only #{points.length} points long." end
390 # -- 3. read original way into memory
392 xc={}; yc={}; tagc={}; vc={}
395 if oldversion==0 then r=readwayquery(way,false)
396 else r=readwayquery_old(way,oldversion,true) end
400 xc[id]=row['longitude'].to_f
401 yc[id]=row['latitude' ].to_f
403 vc[id]=row['visible'].to_i
406 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
408 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
411 # -- 4. get version by inserting new row into ways
413 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
415 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
422 points.each_index do |i|
423 xs=coord2long(points[i][0],masterscale,baselong)
424 ys=coord2lat(points[i][1],masterscale,basey)
425 xmin=[xs,xmin].min; xmax=[xs,xmax].max
426 ymin=[ys,ymin].min; ymax=[ys,ymax].max
427 node=points[i][2].to_i
428 tagstr=array2tag(points[i][4])
429 tagsql="'"+sqlescape(tagstr)+"'"
430 lat=(ys * 10000000).round
431 long=(xs * 10000000).round
432 tile=QuadTile.tile_for_point(ys, xs)
437 if renumberednodes[node.to_s].nil?
438 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes ( latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES ( #{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
439 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newnode},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
441 nodelist.push(newnode)
442 renumberednodes[node.to_s]=newnode.to_s
444 points[i][2]=renumberednodes[node.to_s].to_i
447 elsif xc.has_key?(node)
449 # old node from original way - update
450 if ((xs/0.0000001).round!=(xc[node]/0.0000001).round or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
451 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{node},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
452 ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},tags=#{tagsql},visible=1,tile=#{tile} WHERE id=#{node}")
455 # old node, created in another way and now added to this way
459 # -- 6a. delete any nodes not in modified way
461 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
464 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
465 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
466 FROM current_nodes AS cn,#{db_uqn}
469 ActiveRecord::Base.connection.insert(sql)
472 UPDATE current_nodes AS cn, #{db_uqn}
473 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
476 ActiveRecord::Base.connection.update(sql)
478 deleteuniquenoderelations(db_uqn,uid,db_now)
479 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
481 # 6b. insert new version of route into way_nodes
487 if insertsql !='' then insertsql +=',' end
488 if currentsql!='' then currentsql+=',' end
489 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
490 currentsql+="(#{way},#{p[2]},#{sequence})"
494 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
495 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
496 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
498 # -- 7. insert new way tags
502 attributes.each do |k,v|
503 if v=='' or v.nil? then next end
504 if v[0,6]=='(type ' then next end
505 if insertsql !='' then insertsql +=',' end
506 if currentsql!='' then currentsql+=',' end
507 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
508 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
511 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
512 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
513 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
515 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
519 # save POI to the database
520 # in: [0] user token (string),
521 # [1] original node id (may be negative),
522 # [2] projected longitude, [3] projected latitude,
523 # [4] hash of tags, [5] visible (0 to delete, 1 otherwise),
524 # [6] baselong, [7] basey, [8] masterscale
525 # does: saves POI node to the database
526 # refuses save if the node has since become part of a way
527 # out: [0] 0 (success), [1] original node id (unchanged),
529 def putpoi(args) #:doc:
530 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
531 uid=getuserid(usertoken)
532 if !uid then return -1,"You are not logged in, so the point could not be saved." end
534 db_now='@now'+(rand*100).to_i.to_s+uid.to_s+id.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
535 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
540 # if deleting, check node hasn't become part of a way
541 inway=ActiveRecord::Base.connection.select_one("SELECT cw.id FROM current_ways cw,current_way_nodes cwn WHERE cw.id=cwn.id AND cw.visible=1 AND cwn.node_id=#{id} LIMIT 1")
542 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
543 deleteitemrelations(id,'node',uid,db_now)
546 x=coord2long(x.to_f,masterscale,baselong)
547 y=coord2lat(y.to_f,masterscale,basey)
548 tagsql="'"+sqlescape(array2tag(tags))+"'"
549 lat=(y * 10000000).round
550 long=(x * 10000000).round
551 tile=QuadTile.tile_for_point(y, x)
554 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{id},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
555 ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},visible=#{visible},tags=#{tagsql},tile=#{tile} WHERE id=#{id}");
558 newid=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
559 ActiveRecord::Base.connection.update("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newid},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
565 # read POI from database
566 # (only called on revert: POIs are usually read by whichways)
567 # in: [0] node id, [1] baselong, [2] basey, [3] masterscale
569 # out: [0] id (unchanged), [1] projected long, [2] projected lat,
571 def getpoi(args) #:doc:
572 id,baselong,basey,masterscale = args
574 n = Node.find(id.to_i)
576 return [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash]
578 return [nil,nil,nil,'']
583 # delete way and constituent nodes from database
584 # in: [0] user token (string), [1] way id
585 # does: deletes way from db and any constituent nodes not used elsewhere
586 # also removes ways/nodes from any relations they're in
587 # out: [0] 0 (success), [1] way id (unchanged)
589 def deleteway(args) #:doc:
590 usertoken,way_id=args
591 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way_id}")
592 uid=getuserid(usertoken)
593 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
596 # the next bit removes the way from any relations
597 # the delete_with_relations_and_nodes_and_history method should do this,
598 # but at present it just throws a 'precondition failed'
600 db_now='@now'+(rand*100).to_i.to_s+uid.to_s+way.abs.to_s+Time.new.to_i.to_s
601 db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+way.abs.to_s+Time.new.to_i.to_s
602 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
603 createuniquenodes(way,db_uqn,[])
604 deleteuniquenoderelations(db_uqn,uid,db_now)
605 deleteitemrelations(way_id,'way',uid,db_now)
606 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
610 user = User.find(uid)
611 way = Way.find(way_id)
612 way.delete_with_relations_and_nodes_and_history(user)
617 def readwayquery(id,insistonvisible) #:doc:
619 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible
620 FROM current_way_nodes,current_nodes
621 WHERE current_way_nodes.id=#{id}
622 AND current_way_nodes.node_id=current_nodes.id
624 if insistonvisible then sql+=" AND current_nodes.visible=1 " end
625 sql+=" ORDER BY sequence_id"
626 ActiveRecord::Base.connection.select_all(sql)
629 # Get the latest version id of a way
630 def getlastversion(id,version) #:doc:
631 old_way = OldWay.find(:first, :conditions => ['visible=1 AND id=?' , id], :order => 'version DESC')
635 def readwayquery_old(id,version,historic) #:doc:
636 # Node handling on undelete (historic=false):
637 # - always use the node specified, even if it's moved
639 # Node handling on revert (historic=true):
640 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
641 # which means the SWF needs to allocate new ids
642 # - if it's an invisible node, we can reuse the old node id
644 # ----- get node list from specified version of way,
645 # and the _current_ lat/long/tags of each node
647 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
648 waytime=row['timestamp']
651 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
652 FROM way_nodes wn,current_nodes cn
653 WHERE wn.version=#{version}
658 rows=ActiveRecord::Base.connection.select_all(sql)
660 # ----- if historic (full revert), get the old version of each node
661 # - if it's in another way now, generate a new id
662 # - if it's not in another way, use the old ID
665 rows.each_index do |i|
667 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway
669 LEFT JOIN current_way_nodes cwn
670 ON cwn.node_id=n.id AND cwn.id!=#{id}
671 WHERE n.id=#{rows[i]['id']}
672 AND n.timestamp<="#{waytime}"
673 ORDER BY n.timestamp DESC
676 row=ActiveRecord::Base.connection.select_one(sql)
677 nx=row['longitude'].to_f
678 ny=row['latitude'].to_f
680 if (row['currentway'] && (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags'])) then rows[i]['id']=-1 end
682 rows[i]['longitude']=nx
683 rows[i]['latitude' ]=ny
684 rows[i]['tags' ]=row['tags']
690 def createuniquenodes(way,uqn_name,nodelist) #:doc:
691 # Find nodes which appear in this way but no others
693 CREATE TEMPORARY TABLE #{uqn_name}
695 FROM (SELECT DISTINCT node_id FROM current_way_nodes
697 LEFT JOIN current_way_nodes b
698 ON b.node_id=a.node_id
700 WHERE b.node_id IS NULL
702 unless nodelist.empty? then
703 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
705 ActiveRecord::Base.connection.execute(sql)
710 # ====================================================================
712 # deleteuniquenoderelations(uqn_name,uid,db_now)
713 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
715 def deleteuniquenoderelations(uqn_name,uid,db_now) #:doc:
717 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
718 WHERE crm.member_id=node_id
719 AND crm.member_type='node'
724 relnodes=ActiveRecord::Base.connection.select_all(sql)
726 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
730 def deleteitemrelations(objid,type,uid,db_now) #:doc:
732 SELECT cr.id FROM current_relation_members crm,current_relations cr
733 WHERE crm.member_id=#{objid}
734 AND crm.member_type='#{type}'
739 relways=ActiveRecord::Base.connection.select_all(sql)
741 removefromrelation(objid,type,a['id'],uid,db_now)
745 def removefromrelation(objid,type,relation,uid,db_now) #:doc:
746 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
749 INSERT INTO relation_tags (id,k,v,version)
750 SELECT id,k,v,#{rver} FROM current_relation_tags
753 ActiveRecord::Base.connection.insert(tagsql)
756 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
757 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
759 AND (member_id!=#{objid} OR member_type!='#{type}')
761 ActiveRecord::Base.connection.insert(membersql)
763 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
764 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
767 def sqlescape(a) #:doc:
768 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
771 def tag2array(a) #:doc:
773 Tags.split(a) do |k, v|
774 tags[k.gsub(':','|')]=v
779 def array2tag(a) #:doc:
782 if v=='' then next end
783 if v[0,6]=='(type ' then next end
784 tags << [k.gsub('|',':'), v]
786 return Tags.join(tags)
789 def getuserid(token) #:doc:
790 if (token =~ /^(.+)\+(.+)$/) then
791 user = User.authenticate(:username => $1, :password => $2)
793 user = User.authenticate(:token => token)
796 return user ? user.id : nil;
799 # ====================================================================
800 # Co-ordinate conversion
802 def lat2coord(a,basey,masterscale) #:doc:
803 -(lat2y(a)-basey)*masterscale
806 def long2coord(a,baselong,masterscale) #:doc:
807 (a-baselong)*masterscale
811 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
814 def coord2lat(a,masterscale,basey) #:doc:
815 y2lat(a/-masterscale+basey)
818 def coord2long(a,masterscale,baselong) #:doc:
819 a/masterscale+baselong
823 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)