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
17 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
19 # ====================================================================
22 # ---- talk process AMF request
25 req=StringIO.new(request.raw_post+0.chr) # Get POST data as request
26 # (cf http://www.ruby-forum.com/topic/122163)
27 req.read(2) # Skip version indicator and client ID
28 results={} # Results of each body
33 headers=getint(req) # Read number of headers
35 headers.times do # Read each header
36 name=getstring(req) # |
37 req.getc # | skip boolean
38 value=getvalue(req) # |
39 header["name"]=value # |
42 bodies=getint(req) # Read number of bodies
43 bodies.times do # Read each body
44 message=getstring(req) # | get message name
45 index=getstring(req) # | get index in response sequence
46 bytes=getlong(req) # | get total size in bytes
47 args=getvalue(req) # | get response (probably an array)
50 when 'getpresets'; results[index]=putdata(index,getpresets)
51 when 'whichways'; results[index]=putdata(index,whichways(args))
52 when 'whichways_deleted'; results[index]=putdata(index,whichways_deleted(args))
53 when 'getway'; results[index]=putdata(index,getway(args))
54 when 'getway_old'; results[index]=putdata(index,getway_old(args))
55 when 'getway_history'; results[index]=putdata(index,getway_history(args))
56 when 'putway'; results[index]=putdata(index,putway(args))
57 when 'deleteway'; results[index]=putdata(index,deleteway(args))
58 when 'putpoi'; results[index]=putdata(index,putpoi(args))
59 when 'getpoi'; results[index]=putdata(index,getpoi(args))
66 RAILS_DEFAULT_LOGGER.info(" Response: start")
67 a,b=results.length.divmod(256)
68 render :content_type => "application/x-amf", :text => proc { |response, output|
69 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
74 RAILS_DEFAULT_LOGGER.info(" Response: end")
80 # ====================================================================
84 # return presets,presetmenus and presetnames arrays
88 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
89 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
93 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
95 # File.open("config/potlatch/presets.txt") do |file|
97 # Temporary patch to get around filepath problem
98 # To remove this patch and make the code nice again:
99 # 1. uncomment above line
100 # 2. fix the path in the above line
101 # 3. delete this here document, and the following line (StringIO....)
105 motorway: highway=motorway,ref=(type road number)
106 trunk road: highway=trunk,ref=(type road number),name=(type road name)
107 primary road: highway=primary,ref=(type road number),name=(type road name)
108 secondary road: highway=secondary,ref=(type road number),name=(type road name)
109 tertiary road: highway=tertiary,ref=,name=(type road name)
110 residential road: highway=residential,ref=,name=(type road name)
111 unclassified road: highway=unclassified,ref=,name=(type road name)
114 footpath: highway=footway,foot=yes
115 bridleway: highway=bridleway,foot=yes
116 byway: highway=unsurfaced,foot=yes
117 permissive path: highway=footway,foot=permissive
120 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
121 cycle track: highway=cycleway,cycleway=track,ncn_ref=
122 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
123 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
126 canal: waterway=canal,name=(type name here)
127 navigable river: waterway=river,boat=yes,name=(type name here)
128 navigable drain: waterway=drain,boat=yes,name=(type name here)
129 derelict canal: waterway=derelict_canal,name=(type name here)
130 unnavigable river: waterway=river,boat=no,name=(type name here)
131 unnavigable drain: waterway=drain,boat=no,name=(type name here)
134 railway: railway=rail
135 tramway: railway=tram
136 light railway: railway=light_rail
137 preserved railway: railway=preserved
138 disused railway tracks: railway=disused
139 course of old railway: railway=abandoned
142 lake: natural=water,landuse=
143 forest: landuse=forest,natural=
146 mini roundabout: highway=mini_roundabout
147 traffic lights: highway=traffic_signals
150 bridge: highway=bridge
153 cattle grid: highway=cattle_grid
159 lock gate: waterway=lock_gate
161 aqueduct: waterway=aqueduct
162 winding hole: waterway=turning_point
163 mooring: waterway=mooring
166 station: railway=station
167 viaduct: railway=viaduct
168 level crossing: railway=crossing
174 car park: amenity=parking
175 petrol station: amenity=fuel
178 bike park: amenity=bicycle_parking
181 city: place=city,name=(type name here),is_in=(type region or county)
182 town: place=town,name=(type name here),is_in=(type region or county)
183 suburb: place=suburb,name=(type name here),is_in=(type region or county)
184 village: place=village,name=(type name here),is_in=(type region or county)
185 hamlet: place=hamlet,name=(type name here),is_in=(type region or county)
188 attraction: tourism=attraction,amenity=,religion=,denomination=
189 church: tourism=,amenity=place_of_worship,name=(type name here),religion=christian,denomination=(type denomination here)
190 hotel: tourism=hotel,amenity=,religion=,denomination=
191 other religious: tourism=,amenity=place_of_worship,name=(type name here),religion=(type religion),denomination=
192 post box: amenity=post_box,tourism=,name=,religion=,denomination=
193 post office: amenity=post_office,tourism=,name=,religion=,denomination=
194 pub: tourism=,amenity=pub,name=(type name here),religion=,denomination=
200 StringIO.open(txt) do |file|
201 file.each_line {|line|
203 if (t=~/(\w+)\/(\w+)/) then
206 presetmenus[presettype].push(presetcategory)
207 presetnames[presettype][presetcategory]=["(no preset)"]
208 elsif (t=~/^(.+):\s?(.+)$/) then
210 presetnames[presettype][presetcategory].push(pre)
212 kv.split(',').each {|a|
213 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
218 return [presets,presetmenus,presetnames]
221 # ----- whichways(left,bottom,right,top)
222 # return array of ways in current bounding box
223 # at present, instead of using correct (=more complex) SQL to find
224 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
227 xmin = args[0].to_f-0.01
228 ymin = args[1].to_f-0.01
229 xmax = args[2].to_f+0.01
230 ymax = args[3].to_f+0.01
233 masterscale = args[6]
235 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
237 waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
238 " FROM current_way_nodes,current_nodes,current_ways "+
239 " WHERE current_nodes.id=current_way_nodes.node_id "+
240 " AND current_nodes.visible=1 "+
241 " AND current_ways.id=current_way_nodes.id "+
242 " AND current_ways.visible=1 "+
243 " AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
245 ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
247 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 "+
248 " FROM current_nodes "+
249 " LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
250 " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
251 " AND cwn.id IS NULL "+
252 " AND current_nodes.visible=1")
254 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
259 # ----- whichways_deleted(left,bottom,right,top)
260 # return array of deleted ways in current bounding box
262 def whichways_deleted(args)
263 xmin = args[0].to_f-0.01
264 ymin = args[1].to_f-0.01
265 xmax = args[2].to_f+0.01
266 ymax = args[3].to_f+0.01
269 masterscale = args[6]
272 SELECT DISTINCT current_ways.id
273 FROM current_nodes,way_nodes,current_ways
274 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
275 AND way_nodes.node_id=current_nodes.id
276 AND way_nodes.id=current_ways.id
277 AND current_nodes.visible=0
278 AND current_ways.visible=0
280 waylist = ActiveRecord::Base.connection.select_all(sql)
281 ways = waylist.collect {|a| a['id'].to_i }
285 # ----- getway (objectname, way, baselong, basey, masterscale)
286 # returns objectname, array of co-ordinates, attributes,
287 # xmin,xmax,ymin,ymax
290 objname,wayid,baselong,basey,masterscale=args
294 xmax = ymax = -999999
296 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
298 readwayquery(wayid).each {|row|
299 points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,nil,tag2array(row['tags'])]
300 xmin = [xmin,row['longitude'].to_f].min
301 xmax = [xmax,row['longitude'].to_f].max
302 ymin = [ymin,row['latitude'].to_f].min
303 ymax = [ymax,row['latitude'].to_f].max
307 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
308 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
310 [objname,points,attributes,xmin,xmax,ymin,ymax]
313 # ----- getway_old (objectname, way, version, baselong, basey, masterscale)
314 # returns old version of way
317 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
318 return if SERVER_URL=='www.openstreetmap.org'
320 objname,wayid,version,baselong,basey,masterscale=args
322 version = version.to_i
324 xmax = ymax = -999999
328 version=getlastversion(wayid,version)
332 readwayquery_old(wayid,version,historic).each { |row|
333 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)]
334 xmin=[xmin,row['longitude'].to_f].min
335 xmax=[xmax,row['longitude'].to_f].max
336 ymin=[ymin,row['latitude' ].to_f].min
337 ymax=[ymax,row['latitude' ].to_f].max
340 # get tags from this version
342 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
343 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
344 attributes['history']="Retrieved from v"+version.to_s
346 [objname,points,attributes,xmin,xmax,ymin,ymax,version]
349 # ----- getway_history (way)
350 # returns array of previous versions (version,timestamp,visible,user)
351 # should also show 'created_by'
353 def getway_history(wayid)
356 SELECT version,timestamp,visible,display_name,data_public
358 WHERE ways.id=#{wayid}
359 AND ways.user_id=users.id
360 ORDER BY version DESC
362 histlist=ActiveRecord::Base.connection.select_all(sql)
363 histlist.each { |row|
364 if row['data_public'] then user=row['display_name'] else user='anonymous' end
365 history<<[row['version'],row['timestamp'],row['visible'],user]
370 # ----- putway (user token, way, array of co-ordinates, array of attributes,
371 # baselong, basey, masterscale)
372 # returns current way ID, new way ID, hash of renumbered nodes,
373 # xmin,xmax,ymin,ymax
375 # ** needs to be updated so that nodes with visible=0 (i.e. undeleted)
376 # no longer cause a problem
377 # best way to do this would be to know which version it was recovered from;
378 # then replace readwayquery with historic query. Line 506 would also need
379 # to check if visible had changed, and update if so
380 # (a side-effect is that merging/splitting ways will need to be forbidden
381 # for undeleted ways, I think)
384 RAILS_DEFAULT_LOGGER.info(" putway started")
385 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
386 uid=getuserid(usertoken)
388 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
389 db_uqn='unin'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
390 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
391 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
392 originalway=originalway.to_i
393 oldversion=oldversion.to_i
395 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
397 # -- 3. read original way into memory
399 xc={}; yc={}; tagc={}; vc={}
403 readwayquery(way).each { |row|
405 xc[id]=row['longitude'].to_f
406 yc[id]=row['latitude' ].to_f
411 readwayquery_old(way,oldversion,true).each { |row|
414 xc[id]=row['longitude'].to_f
415 yc[id]=row['latitude' ].to_f
417 vc[id]=row['visible'].to_i
421 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
423 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
426 # -- 4. get version by inserting new row into ways
428 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
430 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
438 points.each_index do |i|
439 xs=coord2long(points[i][0],masterscale,baselong)
440 ys=coord2lat(points[i][1],masterscale,basey)
441 xmin=[xs,xmin].min; xmax=[xs,xmax].max
442 ymin=[ys,ymin].min; ymax=[ys,ymax].max
443 node=points[i][2].to_i
444 tagstr=array2tag(points[i][4])
445 tagsql="'"+sqlescape(tagstr)+"'"
446 lat=(ys * 10000000).round
447 long=(xs * 10000000).round
448 tile=QuadTile.tile_for_point(ys, xs)
453 if renumberednodes[node.to_s].nil?
454 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})")
455 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})")
457 nodelist.push(newnode)
458 renumberednodes[node.to_s]=newnode.to_s
460 points[i][2]=renumberednodes[node.to_s].to_i
463 elsif xc.has_key?(node)
465 # old node from original way - update
466 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
467 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})")
468 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}")
471 # old node, created in another way and now added to this way
476 # -- 6a. delete any nodes not in modified way
478 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
481 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
482 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
483 FROM current_nodes AS cn,#{db_uqn}
486 ActiveRecord::Base.connection.insert(sql)
489 UPDATE current_nodes AS cn, #{db_uqn}
490 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
493 ActiveRecord::Base.connection.update(sql)
495 deleteuniquenoderelations(db_uqn,uid,db_now)
496 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
498 # 6b. insert new version of route into way_nodes
504 if insertsql !='' then insertsql +=',' end
505 if currentsql!='' then currentsql+=',' end
506 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
507 currentsql+="(#{way},#{p[2]},#{sequence})"
511 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
512 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
513 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
515 # -- 7. insert new way tags
519 attributes.each do |k,v|
520 if v=='' or v.nil? then next end
521 if v[0,6]=='(type ' then next end
522 if insertsql !='' then insertsql +=',' end
523 if currentsql!='' then currentsql+=',' end
524 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
525 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
528 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
529 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
530 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
532 [originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
535 # ----- putpoi (user token, id, x,y,tag array,visible,baselong,basey,masterscale)
536 # returns current id, new id
537 # if new: add new row to current_nodes and nodes
538 # if old: add new row to nodes, update current_nodes
541 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
542 uid=getuserid(usertoken)
544 db_now='@now'+uid.to_s+id.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
545 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
550 # if deleting, check node hasn't become part of a way
551 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")
552 unless inway.nil? then return [id,id] end # should really return an error
553 deleteitemrelations(id,'node',uid,db_now)
556 x=coord2long(x.to_f,masterscale,baselong)
557 y=coord2lat(y.to_f,masterscale,basey)
558 tagsql="'"+sqlescape(array2tag(tags))+"'"
559 lat=(y * 10000000).round
560 long=(x * 10000000).round
561 tile=QuadTile.tile_for_point(y, x)
564 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})");
565 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}");
568 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})");
569 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})");
574 # ----- getpoi (id,baselong,basey,masterscale)
575 # returns id,x,y,tag array
578 id,baselong,basey,masterscale=args; id=id.to_i
579 poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
580 "FROM current_nodes WHERE visible=1 AND id=#{id}")
581 if poi.nil? then return [nil,nil,nil,''] end
583 long2coord(poi['lng'].to_f,baselong,masterscale),
584 lat2coord(poi['lat'].to_f,basey,masterscale),
585 tag2array(poi['tags'])]
588 # ----- deleteway (user token, way, nodes to keep)
589 # returns way ID only
592 usertoken,way,preserve=args
594 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
596 uid=getuserid(usertoken); if !uid then return end
599 db_uqn='unin'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
600 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
601 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
603 # - delete any otherwise unused nodes
605 createuniquenodes(way,db_uqn,[])
607 unless (preserve.empty?) then
608 ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
612 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
613 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
614 FROM current_nodes AS cn,#{db_uqn}
617 ActiveRecord::Base.connection.insert(sql)
620 UPDATE current_nodes AS cn, #{db_uqn}
621 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
624 ActiveRecord::Base.connection.update(sql)
626 deleteuniquenoderelations(db_uqn,uid,db_now)
627 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
631 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
632 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
633 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
634 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
635 deleteitemrelations(way,'way',uid,db_now)
641 # ====================================================================
642 # Support functions for remote calls
645 ActiveRecord::Base.connection.select_all "SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags "+
646 " FROM current_way_nodes,current_nodes "+
647 " WHERE current_way_nodes.id=#{id} "+
648 " AND current_way_nodes.node_id=current_nodes.id "+
649 " AND current_nodes.visible=1 "+
650 " ORDER BY sequence_id"
653 def getlastversion(id,version)
654 row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
658 def readwayquery_old(id,version,historic)
659 # Node handling on undelete (historic=false):
660 # - always use the node specified, even if it's moved
662 # Node handling on revert (historic=true):
663 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
664 # which means the SWF needs to allocate new ids
665 # - if it's an invisible node, we can reuse the old node id
667 # get node list from specified version of way,
668 # and the _current_ lat/long/tags of each node
670 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
671 waytime=row['timestamp']
674 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
675 FROM way_nodes wn,current_nodes cn
676 WHERE wn.version=#{version}
681 rows=ActiveRecord::Base.connection.select_all(sql)
683 # if historic (full revert), get the old version of each node,
684 # and use this (though with a new id) if it differs from the current one
686 rows.each_index do |i|
688 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
690 WHERE id=#{rows[i]['id']}
691 AND timestamp<="#{waytime}"
692 ORDER BY timestamp DESC
695 row=ActiveRecord::Base.connection.select_one(sql)
697 nx=row['longitude'].to_f
698 ny=row['latitude'].to_f
699 if (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags']) then
701 # This generates a new node id if x/y/tags differ from current node.
702 # Strictly speaking, it need only do this for uniquenodes, but we're
703 # not generating uniquenodes for historic ways (yet!).
705 rows[i]['longitude']=nx
706 rows[i]['latitude' ]=ny
707 rows[i]['tags' ]=row['tags']
714 def createuniquenodes(way,uqn_name,nodelist)
715 # Find nodes which appear in this way but no others
717 CREATE TEMPORARY TABLE #{uqn_name}
719 FROM (SELECT DISTINCT node_id FROM current_way_nodes
721 LEFT JOIN current_way_nodes b
722 ON b.node_id=a.node_id
724 WHERE b.node_id IS NULL
726 unless nodelist.empty? then
727 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
729 ActiveRecord::Base.connection.execute(sql)
734 # ====================================================================
736 # deleteuniquenoderelations(uqn_name,uid,db_now)
737 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
739 def deleteuniquenoderelations(uqn_name,uid,db_now)
741 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
742 WHERE crm.member_id=node_id
743 AND crm.member_type='node'
748 relnodes=ActiveRecord::Base.connection.select_all(sql)
750 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
754 def deleteitemrelations(objid,type,uid,db_now)
756 SELECT cr.id FROM current_relation_members crm,current_relations cr
757 WHERE crm.member_id=#{objid}
758 AND crm.member_type='#{type}'
763 relways=ActiveRecord::Base.connection.select_all(sql)
765 removefromrelation(objid,type,a['id'],uid,db_now)
769 def removefromrelation(objid,type,relation,uid,db_now)
770 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
773 INSERT INTO relation_tags (id,k,v,version)
774 SELECT id,k,v,#{rver} FROM current_relation_tags
777 ActiveRecord::Base.connection.insert(tagsql)
780 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
781 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
783 AND (member_id!=#{objid} OR member_type!='#{type}')
785 ActiveRecord::Base.connection.insert(membersql)
787 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
788 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
793 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr,92.chr+92.chr)
798 a.gsub(';;;','#%').split(';').each do |b|
802 if k.nil? then k='' end
803 if v.nil? then v='' end
804 tags[k.gsub('#%','=').gsub(':','|')]=v.gsub('#%','=')
812 if v=='' then next end
813 if v[0,6]=='(type ' then next end
814 if str!='' then str+=';' end
815 str+=k.gsub(';',';;;').gsub('=','===').gsub('|',':')+'='+v.gsub(';',';;;').gsub('=','===')
821 if (token =~ /^(.+)\+(.+)$/) then
822 user = User.authenticate(:username => $1, :password => $2)
824 user = User.authenticate(:token => token)
827 return user ? user.id : nil;
832 # ====================================================================
833 # AMF read subroutines
835 # ----- getint return two-byte integer
836 # ----- getlong return four-byte long
837 # ----- getstring return string with two-byte length
838 # ----- getdouble return eight-byte double-precision float
839 # ----- getobject return object/hash
840 # ----- getarray return numeric array
847 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
851 len=s.getc*256+s.getc
856 a=s.read(8).unpack('G') # G big-endian, E little-endian
871 while (key=getstring(s))
872 if (key=='') then break end
875 s.getc # skip the 9 'end of object' value
879 # ----- getvalue parse and get value
883 when 0; return getdouble(s) # number
884 when 1; return s.getc # boolean
885 when 2; return getstring(s) # string
886 when 3; return getobject(s) # object/hash
887 when 5; return nil # null
888 when 6; return nil # undefined
889 when 8; s.read(4) # mixedArray
890 return getobject(s) # |
891 when 10;return getarray(s) # array
892 else; return nil # error
896 # ====================================================================
897 # AMF write subroutines
899 # ----- putdata envelope data into AMF writeable form
900 # ----- encodevalue pack variables as AMF
903 d =encodestring(index+"/onResult")
904 d+=encodestring("null")
912 a=10.chr+encodelong(n.length)
920 a+=encodestring(k)+encodevalue(v)
924 2.chr+encodestring(n)
925 when 'Bignum','Fixnum','Float'
926 0.chr+encodedouble(n)
930 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
934 # ----- encodestring encode string with two-byte length
935 # ----- encodedouble encode number as eight-byte double precision float
936 # ----- encodelong encode number as four-byte long
939 a,b=n.size.divmod(256)
951 # ====================================================================
952 # Co-ordinate conversion
954 def lat2coord(a,basey,masterscale)
955 -(lat2y(a)-basey)*masterscale+250
958 def long2coord(a,baselong,masterscale)
959 (a-baselong)*masterscale+350
963 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
966 def coord2lat(a,masterscale,basey)
967 y2lat((a-250)/-masterscale+basey)
970 def coord2long(a,masterscale,baselong)
971 (a-350)/masterscale+baselong
975 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)