1 class AmfController < ApplicationController
5 before_filter :check_write_availability
7 # AMF controller for Potlatch
8 # ---------------------------
9 # All interaction between Potlatch (as a .SWF application) and the
10 # OSM database takes place using this controller. Messages are
11 # encoded in the Actionscript Message Format (AMF).
13 # Public domain. Set your tab width to 4 to read this document. :)
14 # editions Systeme D / Richard Fairhurst 2004-2007
16 # to trap errors (getway_old,putway,putpoi,deleteway only):
17 # return(-1,"message") <-- just puts up a dialogue
18 # return(-2,"message") <-- also asks the user to e-mail me
20 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
22 # ====================================================================
25 # ---- talk process AMF request
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
36 headers=getint(req) # Read number of headers
38 headers.times do # Read each header
39 name=getstring(req) # |
40 req.getc # | skip boolean
41 value=getvalue(req) # |
42 header["name"]=value # |
45 bodies=getint(req) # Read number of bodies
46 bodies.times do # Read each body
47 message=getstring(req) # | get message name
48 index=getstring(req) # | get index in response sequence
49 bytes=getlong(req) # | get total size in bytes
50 args=getvalue(req) # | get response (probably an array)
53 when 'getpresets'; results[index]=putdata(index,getpresets)
54 when 'whichways'; results[index]=putdata(index,whichways(args))
55 when 'whichways_deleted'; results[index]=putdata(index,whichways_deleted(args))
56 when 'getway'; results[index]=putdata(index,getway(args))
57 when 'getway_old'; results[index]=putdata(index,getway_old(args))
58 when 'getway_history'; results[index]=putdata(index,getway_history(args))
59 when 'putway'; results[index]=putdata(index,putway(args))
60 when 'deleteway'; results[index]=putdata(index,deleteway(args))
61 when 'putpoi'; results[index]=putdata(index,putpoi(args))
62 when 'getpoi'; results[index]=putdata(index,getpoi(args))
69 RAILS_DEFAULT_LOGGER.info(" Response: start")
70 a,b=results.length.divmod(256)
71 render :content_type => "application/x-amf", :text => proc { |response, output|
72 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
77 RAILS_DEFAULT_LOGGER.info(" Response: end")
83 # ====================================================================
87 # return presets,presetmenus and presetnames arrays
91 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
92 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
96 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
98 # File.open("config/potlatch/presets.txt") do |file|
100 # Temporary patch to get around filepath problem
101 # To remove this patch and make the code nice again:
102 # 1. uncomment above line
103 # 2. fix the path in the above line
104 # 3. delete this here document, and the following line (StringIO....)
108 motorway: highway=motorway,ref=(type road number)
109 trunk road: highway=trunk,ref=(type road number),name=(type road name)
110 primary road: highway=primary,ref=(type road number),name=(type road name)
111 secondary road: highway=secondary,ref=(type road number),name=(type road name)
112 tertiary road: highway=tertiary,ref=,name=(type road name)
113 residential road: highway=residential,ref=,name=(type road name)
114 unclassified road: highway=unclassified,ref=,name=(type road name)
117 footpath: highway=footway,foot=yes
118 bridleway: highway=bridleway,foot=yes
119 byway: highway=unsurfaced,foot=yes
120 permissive path: highway=footway,foot=permissive
123 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
124 cycle track: highway=cycleway,cycleway=track,ncn_ref=
125 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
126 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
129 canal: waterway=canal,name=(type name here)
130 navigable river: waterway=river,boat=yes,name=(type name here)
131 navigable drain: waterway=drain,boat=yes,name=(type name here)
132 derelict canal: waterway=derelict_canal,name=(type name here)
133 unnavigable river: waterway=river,boat=no,name=(type name here)
134 unnavigable drain: waterway=drain,boat=no,name=(type name here)
137 railway: railway=rail
138 tramway: railway=tram
139 light railway: railway=light_rail
140 preserved railway: railway=preserved
141 disused railway tracks: railway=disused
142 course of old railway: railway=abandoned
145 lake: natural=water,landuse=
146 forest: landuse=forest,natural=
149 mini roundabout: highway=mini_roundabout
150 traffic lights: highway=traffic_signals
153 bridge: highway=bridge
156 cattle grid: highway=cattle_grid
162 lock gate: waterway=lock_gate
164 aqueduct: waterway=aqueduct
165 winding hole: waterway=turning_point
166 mooring: waterway=mooring
169 station: railway=station
170 viaduct: railway=viaduct
171 level crossing: railway=crossing
177 car park: amenity=parking
178 petrol station: amenity=fuel
181 bike park: amenity=bicycle_parking
184 city: place=city,name=(type name here),is_in=(type region or county)
185 town: place=town,name=(type name here),is_in=(type region or county)
186 suburb: place=suburb,name=(type name here),is_in=(type region or county)
187 village: place=village,name=(type name here),is_in=(type region or county)
188 hamlet: place=hamlet,name=(type name here),is_in=(type region or county)
191 attraction: tourism=attraction,amenity=,religion=,denomination=
192 church: tourism=,amenity=place_of_worship,name=(type name here),religion=christian,denomination=(type denomination here)
193 hotel: tourism=hotel,amenity=,religion=,denomination=
194 other religious: tourism=,amenity=place_of_worship,name=(type name here),religion=(type religion),denomination=
195 post box: amenity=post_box,tourism=,name=,religion=,denomination=
196 post office: amenity=post_office,tourism=,name=,religion=,denomination=
197 pub: tourism=,amenity=pub,name=(type name here),religion=,denomination=
203 StringIO.open(txt) do |file|
204 file.each_line {|line|
206 if (t=~/(\w+)\/(\w+)/) then
209 presetmenus[presettype].push(presetcategory)
210 presetnames[presettype][presetcategory]=["(no preset)"]
211 elsif (t=~/^(.+):\s?(.+)$/) then
213 presetnames[presettype][presetcategory].push(pre)
215 kv.split(',').each {|a|
216 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
221 [presets,presetmenus,presetnames]
224 # ----- whichways(left,bottom,right,top)
225 # return array of ways in current bounding box
226 # at present, instead of using correct (=more complex) SQL to find
227 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
230 xmin = args[0].to_f-0.01
231 ymin = args[1].to_f-0.01
232 xmax = args[2].to_f+0.01
233 ymax = args[3].to_f+0.01
236 masterscale = args[6]
238 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
240 waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
241 " FROM current_way_nodes,current_nodes,current_ways "+
242 " WHERE current_nodes.id=current_way_nodes.node_id "+
243 " AND current_nodes.visible=1 "+
244 " AND current_ways.id=current_way_nodes.id "+
245 " AND current_ways.visible=1 "+
246 " AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
248 ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
250 pointlist = ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lng,current_nodes.tags "+
251 " FROM current_nodes "+
252 " LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
253 " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
254 " AND cwn.id IS NULL "+
255 " AND current_nodes.visible=1")
257 points = pointlist.collect {|a| [a['id'],long2coord(a['lng'].to_f,baselong,masterscale),lat2coord(a['lat'].to_f,basey,masterscale),tag2array(a['tags'])] } # get a list of node ids and their tags
262 # ----- whichways_deleted(left,bottom,right,top)
263 # return array of deleted ways in current bounding box
265 def whichways_deleted(args)
266 xmin = args[0].to_f-0.01
267 ymin = args[1].to_f-0.01
268 xmax = args[2].to_f+0.01
269 ymax = args[3].to_f+0.01
272 masterscale = args[6]
275 SELECT DISTINCT current_ways.id
276 FROM current_nodes,way_nodes,current_ways
277 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
278 AND way_nodes.node_id=current_nodes.id
279 AND way_nodes.id=current_ways.id
280 AND current_nodes.visible=0
281 AND current_ways.visible=0
283 waylist = ActiveRecord::Base.connection.select_all(sql)
284 ways = waylist.collect {|a| a['id'].to_i }
288 # ----- getway (objectname, way, baselong, basey, masterscale)
289 # returns objectname, array of co-ordinates, attributes,
290 # xmin,xmax,ymin,ymax
293 objname,wayid,baselong,basey,masterscale=args
297 xmax = ymax = -999999
299 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
301 readwayquery(wayid).each {|row|
302 points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,nil,tag2array(row['tags'])]
303 xmin = [xmin,row['longitude'].to_f].min
304 xmax = [xmax,row['longitude'].to_f].max
305 ymin = [ymin,row['latitude'].to_f].min
306 ymax = [ymax,row['latitude'].to_f].max
310 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
311 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
313 [objname,points,attributes,xmin,xmax,ymin,ymax]
316 # ----- getway_old (objectname, way, version, baselong, basey, masterscale)
317 # returns old version of way
320 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
321 if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
323 objname,wayid,version,baselong,basey,masterscale=args
325 version = version.to_i
327 xmax = ymax = -999999
331 version=getlastversion(wayid,version)
335 readwayquery_old(wayid,version,historic).each { |row|
336 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)]
337 xmin=[xmin,row['longitude'].to_f].min
338 xmax=[xmax,row['longitude'].to_f].max
339 ymin=[ymin,row['latitude' ].to_f].min
340 ymax=[ymax,row['latitude' ].to_f].max
343 # get tags from this version
345 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
346 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
347 attributes['history']="Retrieved from v"+version.to_s
349 [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
352 # ----- getway_history (way)
353 # returns array of previous versions (version,timestamp,visible,user)
354 # should also show 'created_by'
356 def getway_history(wayid)
359 SELECT version,timestamp,visible,display_name,data_public
361 WHERE ways.id=#{wayid}
362 AND ways.user_id=users.id
363 ORDER BY version DESC
365 histlist=ActiveRecord::Base.connection.select_all(sql)
366 histlist.each { |row|
367 if row['data_public'] then user=row['display_name'] else user='anonymous' end
368 history<<[row['version'],row['timestamp'],row['visible'],user]
373 # ----- putway (user token, way, array of co-ordinates, array of attributes,
374 # baselong, basey, masterscale)
375 # returns current way ID, new way ID, hash of renumbered nodes,
376 # xmin,xmax,ymin,ymax
379 RAILS_DEFAULT_LOGGER.info(" putway started")
380 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
381 uid=getuserid(usertoken)
382 if !uid then return -1,"You are not logged in, so the way could not be saved." end
384 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
385 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
386 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
387 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
388 originalway=originalway.to_i
389 oldversion=oldversion.to_i
391 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
393 # -- Temporary check for null IDs
396 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
399 # -- 3. read original way into memory
401 xc={}; yc={}; tagc={}; vc={}
405 readwayquery(way).each { |row|
407 xc[id]=row['longitude'].to_f
408 yc[id]=row['latitude' ].to_f
413 readwayquery_old(way,oldversion,true).each { |row|
416 xc[id]=row['longitude'].to_f
417 yc[id]=row['latitude' ].to_f
419 vc[id]=row['visible'].to_i
423 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
425 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
428 # -- 4. get version by inserting new row into ways
430 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
432 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
440 points.each_index do |i|
441 xs=coord2long(points[i][0],masterscale,baselong)
442 ys=coord2lat(points[i][1],masterscale,basey)
443 xmin=[xs,xmin].min; xmax=[xs,xmax].max
444 ymin=[ys,ymin].min; ymax=[ys,ymax].max
445 node=points[i][2].to_i
446 tagstr=array2tag(points[i][4])
447 tagsql="'"+sqlescape(tagstr)+"'"
448 lat=(ys * 10000000).round
449 long=(xs * 10000000).round
450 tile=QuadTile.tile_for_point(ys, xs)
455 if renumberednodes[node.to_s].nil?
456 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})")
457 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})")
459 nodelist.push(newnode)
460 renumberednodes[node.to_s]=newnode.to_s
462 points[i][2]=renumberednodes[node.to_s].to_i
465 elsif xc.has_key?(node)
467 # old node from original way - update
468 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
469 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})")
470 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}")
473 # old node, created in another way and now added to this way
478 # -- 6a. delete any nodes not in modified way
480 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
483 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
484 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
485 FROM current_nodes AS cn,#{db_uqn}
488 ActiveRecord::Base.connection.insert(sql)
491 UPDATE current_nodes AS cn, #{db_uqn}
492 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
495 ActiveRecord::Base.connection.update(sql)
497 deleteuniquenoderelations(db_uqn,uid,db_now)
498 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
500 # 6b. insert new version of route into way_nodes
506 if insertsql !='' then insertsql +=',' end
507 if currentsql!='' then currentsql+=',' end
508 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
509 currentsql+="(#{way},#{p[2]},#{sequence})"
513 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
514 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
515 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
517 # -- 7. insert new way tags
521 attributes.each do |k,v|
522 if v=='' or v.nil? then next end
523 if v[0,6]=='(type ' then next end
524 if insertsql !='' then insertsql +=',' end
525 if currentsql!='' then currentsql+=',' end
526 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
527 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
530 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
531 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
532 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
534 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
537 # ----- putpoi (user token, id, x,y,tag array,visible,baselong,basey,masterscale)
538 # returns current id, new id
539 # if new: add new row to current_nodes and nodes
540 # if old: add new row to nodes, update current_nodes
543 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
544 uid=getuserid(usertoken)
545 if !uid then return -1,"You are not logged in, so the point could not be saved." end
547 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
548 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
553 # if deleting, check node hasn't become part of a way
554 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")
555 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
556 deleteitemrelations(id,'node',uid,db_now)
559 x=coord2long(x.to_f,masterscale,baselong)
560 y=coord2lat(y.to_f,masterscale,basey)
561 tagsql="'"+sqlescape(array2tag(tags))+"'"
562 lat=(y * 10000000).round
563 long=(x * 10000000).round
564 tile=QuadTile.tile_for_point(y, x)
567 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})");
568 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}");
571 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})");
572 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})");
577 # ----- getpoi (id,baselong,basey,masterscale)
578 # returns id,x,y,tag array
581 id,baselong,basey,masterscale=args; id=id.to_i
582 poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
583 "FROM current_nodes WHERE visible=1 AND id=#{id}")
584 if poi.nil? then return [nil,nil,nil,''] end
586 long2coord(poi['lng'].to_f,baselong,masterscale),
587 lat2coord(poi['lat'].to_f,basey,masterscale),
588 tag2array(poi['tags'])]
591 # ----- deleteway (user token, way, nodes to keep)
592 # returns way ID only
597 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
598 uid=getuserid(usertoken)
599 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
602 db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
603 db_now='@now'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
604 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
606 # - delete any otherwise unused nodes
608 createuniquenodes(way,db_uqn,[])
610 # unless (preserve.empty?) then
611 # ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
615 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
616 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
617 FROM current_nodes AS cn,#{db_uqn}
620 ActiveRecord::Base.connection.insert(sql)
623 UPDATE current_nodes AS cn, #{db_uqn}
624 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
627 ActiveRecord::Base.connection.update(sql)
629 deleteuniquenoderelations(db_uqn,uid,db_now)
630 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
634 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
635 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
636 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
637 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
638 deleteitemrelations(way,'way',uid,db_now)
644 # ====================================================================
645 # Support functions for remote calls
648 ActiveRecord::Base.connection.select_all "SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags "+
649 " FROM current_way_nodes,current_nodes "+
650 " WHERE current_way_nodes.id=#{id} "+
651 " AND current_way_nodes.node_id=current_nodes.id "+
652 " AND current_nodes.visible=1 "+
653 " ORDER BY sequence_id"
656 def getlastversion(id,version)
657 row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
661 def readwayquery_old(id,version,historic)
662 # Node handling on undelete (historic=false):
663 # - always use the node specified, even if it's moved
665 # Node handling on revert (historic=true):
666 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
667 # which means the SWF needs to allocate new ids
668 # - if it's an invisible node, we can reuse the old node id
670 # get node list from specified version of way,
671 # and the _current_ lat/long/tags of each node
673 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
674 waytime=row['timestamp']
677 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
678 FROM way_nodes wn,current_nodes cn
679 WHERE wn.version=#{version}
684 rows=ActiveRecord::Base.connection.select_all(sql)
686 # if historic (full revert), get the old version of each node,
687 # and use this (though with a new id) if it differs from the current one
689 rows.each_index do |i|
691 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
693 WHERE id=#{rows[i]['id']}
694 AND timestamp<="#{waytime}"
695 ORDER BY timestamp DESC
698 row=ActiveRecord::Base.connection.select_one(sql)
700 nx=row['longitude'].to_f
701 ny=row['latitude'].to_f
702 if (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags']) then
704 # This generates a new node id if x/y/tags differ from current node.
705 # Strictly speaking, it need only do this for uniquenodes, but we're
706 # not generating uniquenodes for historic ways (yet!).
708 rows[i]['longitude']=nx
709 rows[i]['latitude' ]=ny
710 rows[i]['tags' ]=row['tags']
717 def createuniquenodes(way,uqn_name,nodelist)
718 # Find nodes which appear in this way but no others
720 CREATE TEMPORARY TABLE #{uqn_name}
722 FROM (SELECT DISTINCT node_id FROM current_way_nodes
724 LEFT JOIN current_way_nodes b
725 ON b.node_id=a.node_id
727 WHERE b.node_id IS NULL
729 unless nodelist.empty? then
730 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
732 ActiveRecord::Base.connection.execute(sql)
737 # ====================================================================
739 # deleteuniquenoderelations(uqn_name,uid,db_now)
740 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
742 def deleteuniquenoderelations(uqn_name,uid,db_now)
744 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
745 WHERE crm.member_id=node_id
746 AND crm.member_type='node'
751 relnodes=ActiveRecord::Base.connection.select_all(sql)
753 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
757 def deleteitemrelations(objid,type,uid,db_now)
759 SELECT cr.id FROM current_relation_members crm,current_relations cr
760 WHERE crm.member_id=#{objid}
761 AND crm.member_type='#{type}'
766 relways=ActiveRecord::Base.connection.select_all(sql)
768 removefromrelation(objid,type,a['id'],uid,db_now)
772 def removefromrelation(objid,type,relation,uid,db_now)
773 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
776 INSERT INTO relation_tags (id,k,v,version)
777 SELECT id,k,v,#{rver} FROM current_relation_tags
780 ActiveRecord::Base.connection.insert(tagsql)
783 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
784 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
786 AND (member_id!=#{objid} OR member_type!='#{type}')
788 ActiveRecord::Base.connection.insert(membersql)
790 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
791 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
796 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr,92.chr+92.chr)
801 a.gsub(';;;','#%').split(';').each do |b|
805 if k.nil? then k='' end
806 if v.nil? then v='' end
807 tags[k.gsub('#%','=').gsub(':','|')]=v.gsub('#%','=')
815 if v=='' then next end
816 if v[0,6]=='(type ' then next end
817 if str!='' then str+=';' end
818 str+=k.gsub(';',';;;').gsub('=','===').gsub('|',':')+'='+v.gsub(';',';;;').gsub('=','===')
824 if (token =~ /^(.+)\+(.+)$/) then
825 user = User.authenticate(:username => $1, :password => $2)
827 user = User.authenticate(:token => token)
830 return user ? user.id : nil;
835 # ====================================================================
836 # AMF read subroutines
838 # ----- getint return two-byte integer
839 # ----- getlong return four-byte long
840 # ----- getstring return string with two-byte length
841 # ----- getdouble return eight-byte double-precision float
842 # ----- getobject return object/hash
843 # ----- getarray return numeric array
850 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
854 len=s.getc*256+s.getc
859 a=s.read(8).unpack('G') # G big-endian, E little-endian
874 while (key=getstring(s))
875 if (key=='') then break end
878 s.getc # skip the 9 'end of object' value
882 # ----- getvalue parse and get value
886 when 0; return getdouble(s) # number
887 when 1; return s.getc # boolean
888 when 2; return getstring(s) # string
889 when 3; return getobject(s) # object/hash
890 when 5; return nil # null
891 when 6; return nil # undefined
892 when 8; s.read(4) # mixedArray
893 return getobject(s) # |
894 when 10;return getarray(s) # array
895 else; return nil # error
899 # ====================================================================
900 # AMF write subroutines
902 # ----- putdata envelope data into AMF writeable form
903 # ----- encodevalue pack variables as AMF
906 d =encodestring(index+"/onResult")
907 d+=encodestring("null")
915 a=10.chr+encodelong(n.length)
923 a+=encodestring(k)+encodevalue(v)
927 2.chr+encodestring(n)
928 when 'Bignum','Fixnum','Float'
929 0.chr+encodedouble(n)
933 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
937 # ----- encodestring encode string with two-byte length
938 # ----- encodedouble encode number as eight-byte double precision float
939 # ----- encodelong encode number as four-byte long
942 a,b=n.size.divmod(256)
954 # ====================================================================
955 # Co-ordinate conversion
957 def lat2coord(a,basey,masterscale)
958 -(lat2y(a)-basey)*masterscale+250
961 def long2coord(a,baselong,masterscale)
962 (a-baselong)*masterscale+350
966 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
969 def coord2lat(a,masterscale,basey)
970 y2lat((a-250)/-masterscale+basey)
973 def coord2long(a,masterscale,baselong)
974 (a-350)/masterscale+baselong
978 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)