1 class AmfController < ApplicationController
5 before_filter :check_write_availability
8 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
10 # ====================================================================
13 # ---- talk process AMF request
16 req=StringIO.new(request.raw_post) # Get POST data as request
17 req.read(2) # Skip version indicator and client ID
18 results={} # Results of each body
23 headers=getint(req) # Read number of headers
25 headers.times do # Read each header
26 name=getstring(req) # |
27 req.getc # | skip boolean
28 value=getvalue(req) # |
29 header["name"]=value # |
32 bodies=getint(req) # Read number of bodies
33 bodies.times do # Read each body
34 message=getstring(req) # | get message name
35 index=getstring(req) # | get index in response sequence
36 bytes=getlong(req) # | get total size in bytes
37 args=getvalue(req) # | get response (probably an array)
40 when 'getpresets'; results[index]=putdata(index,getpresets)
41 when 'whichways'; results[index]=putdata(index,whichways(args))
42 when 'getway'; results[index]=putdata(index,getway(args))
43 when 'putway'; results[index]=putdata(index,putway(args))
44 when 'deleteway'; results[index]=putdata(index,deleteway(args))
45 when 'makeway'; results[index]=putdata(index,makeway(args))
46 when 'putpoi'; results[index]=putdata(index,putpoi(args))
47 when 'getpoi'; results[index]=putdata(index,getpoi(args))
54 RAILS_DEFAULT_LOGGER.info(" Response: start")
55 a,b=results.length.divmod(256)
56 render :content_type => "application/x-amf", :text => proc { |response, output|
57 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
62 RAILS_DEFAULT_LOGGER.info(" Response: end")
68 # ====================================================================
72 # return presets,presetmenus and presetnames arrays
76 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
77 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
81 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
83 # File.open("config/potlatch/presets.txt") do |file|
85 # Temporary patch to get around filepath problem
86 # To remove this patch and make the code nice again:
87 # 1. uncomment above line
88 # 2. fix the path in the above line
89 # 3. delete this here document, and the following line (StringIO....)
93 motorway: highway=motorway,ref=(type road number)
94 trunk road: highway=trunk,ref=(type road number),name=(type road name)
95 primary road: highway=primary,ref=(type road number),name=(type road name)
96 secondary road: highway=secondary,ref=(type road number),name=(type road name)
97 residential road: highway=residential,name=(type road name)
98 unclassified road: highway=unclassified,name=(type road name)
101 footpath: highway=footway,foot=yes
102 bridleway: highway=bridleway,foot=yes
103 byway: highway=unsurfaced,foot=yes
104 permissive path: highway=footway,foot=permissive
107 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
108 cycle track: highway=cycleway,cycleway=track,ncn_ref=
109 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
110 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
113 canal: waterway=canal,name=(type name here)
114 navigable river: waterway=river,boat=yes,name=(type name here)
115 navigable drain: waterway=drain,boat=yes,name=(type name here)
116 derelict canal: waterway=derelict_canal,name=(type name here)
117 unnavigable river: waterway=river,boat=no,name=(type name here)
118 unnavigable drain: waterway=drain,boat=no,name=(type name here)
121 railway: railway=rail
122 tramway: railway=tram
123 light railway: railway=light_rail
124 preserved railway: railway=preserved
125 disused railway tracks: railway=disused
126 course of old railway: railway=abandoned
130 forest: landuse=forest
133 mini roundabout: highway=mini_roundabout
134 traffic lights: highway=traffic_signals
137 bridge: highway=bridge
140 cattle grid: highway=cattle_grid
146 lock gate: waterway=lock_gate
148 aqueduct: waterway=aqueduct
149 winding hole: waterway=turning_point
150 mooring: waterway=mooring
153 station: railway=station
154 viaduct: railway=viaduct
155 level crossing: railway=crossing
161 car park: amenity=parking
162 petrol station: amenity=fuel
165 bike park: amenity=bicycle_parking
168 city: place=city,name=(type name here),is_in=(type region or county)
169 town: place=town,name=(type name here),is_in=(type region or county)
170 suburb: place=suburb,name=(type name here),is_in=(type region or county)
171 village: place=village,name=(type name here),is_in=(type region or county)
172 hamlet: place=hamlet,name=(type name here),is_in=(type region or county)
175 attraction: tourism=attraction,amenity=,religion=,denomination=
176 church: tourism=,amenity=place_of_worship,name=(type name here),religion=christian,denomination=(type denomination here)
177 hotel: tourism=hotel,amenity=,religion=,denomination=
178 other religious: tourism=,amenity=place_of_worship,name=(type name here),religion=(type religion),denomination=
179 post box: amenity=post_box,tourism=,name=,religion=,denomination=
180 post office: amenity=post_office,tourism=,name=,religion=,denomination=
181 pub: tourism=,amenity=pub,name=(type name here),religion=,denomination=
187 StringIO.open(txt) do |file|
188 file.each_line {|line|
190 if (t=~/(\w+)\/(\w+)/) then
193 presetmenus[presettype].push(presetcategory)
194 presetnames[presettype][presetcategory]=["(no preset)"]
195 elsif (t=~/^(.+):\s?(.+)$/) then
197 presetnames[presettype][presetcategory].push(pre)
199 kv.split(',').each {|a|
200 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
205 return [presets,presetmenus,presetnames]
208 # ----- whichways(left,bottom,right,top)
209 # return array of ways in current bounding box
210 # at present, instead of using correct (=more complex) SQL to find
211 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
214 xmin = args[0].to_f-0.01
215 ymin = args[1].to_f-0.01
216 xmax = args[2].to_f+0.01
217 ymax = args[3].to_f+0.01
220 masterscale = args[6]
222 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
224 waylist = WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
225 " FROM current_way_segments,current_segments,current_nodes,current_ways "+
226 " WHERE segment_id=current_segments.id "+
227 " AND current_segments.visible=1 "+
228 " AND node_a=current_nodes.id "+
229 " AND current_ways.id=current_way_segments.id "+
230 " AND current_ways.visible=1 "+
231 " AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
233 ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
235 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 "+
236 " FROM current_nodes "+
237 " LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
238 " LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
239 " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
240 " AND cs1.id IS NULL AND cs2.id IS NULL "+
241 " AND current_nodes.visible=1")
243 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
248 # ----- getway (objectname, way, baselong, basey, masterscale)
249 # returns objectname, array of co-ordinates, attributes,
250 # xmin,xmax,ymin,ymax
253 objname,wayid,baselong,basey,masterscale=args
258 xmax = ymax = -999999
260 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
262 readwayquery(wayid).each {|row|
263 xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
264 xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
265 points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
266 lastid = row['id2'].to_i
267 points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
268 xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
269 xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
270 ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
271 ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
275 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
276 attrlist.each {|a| attributes[a['k']]=a['v'] }
278 [objname,points,attributes,xmin,xmax,ymin,ymax]
281 # ----- putway (user token, way, array of co-ordinates, array of attributes,
282 # baselong, basey, masterscale)
283 # returns current way ID, new way ID, hash of renumbered nodes,
284 # xmin,xmax,ymin,ymax
287 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
288 uid=getuserid(usertoken)
290 db_uqs='uniq'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquesegments table name, typically 51 chars
291 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
292 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
293 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
294 originalway=originalway.to_i
296 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
298 # -- 3. read original way into memory
300 xc={}; yc={}; tagc={}; seg={}
303 readwayquery(way).each { |row|
304 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
305 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
306 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
308 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
310 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
313 # -- 4. get version by inserting new row into ways
315 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
317 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
320 xmax = ymax = -999999
324 points.each_index do |i|
325 xs=coord2long(points[i][0],masterscale,baselong)
326 ys=coord2lat(points[i][1],masterscale,basey)
327 xmin=[xs,xmin].min; xmax=[xs,xmax].max
328 ymin=[ys,ymin].min; ymax=[ys,ymax].max
329 node=points[i][2].to_i
330 tagstr=array2tag(points[i][4])
331 tagstr=tagstr.gsub(/[\000-\037]/,"")
332 tagsql="'"+sqlescape(tagstr)+"'"
333 lat=(ys * 10000000).round
334 long=(xs * 10000000).round
335 tile=QuadTile.tile_for_point(ys, xs)
340 if renumberednodes[node.to_s].nil?
341 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})")
342 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})")
344 renumberednodes[node.to_s]=newnode.to_s
346 points[i][2]=renumberednodes[node.to_s].to_i
349 elsif xc.has_key?(node)
350 # old node from original way - update
351 if (xs!=xc[node] or ys!=yc[node] or tagstr!=tagc[node])
352 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})")
353 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}")
356 # old node, created in another way and now added to this way
361 # -- 6.i compare segments
364 seglist='' # list of existing segments that we want to keep
365 for i in (0..(points.length-2))
366 if (points[i+1][3].to_i==0) then next end
367 segid=points[i+1][5].to_i
368 from =points[i ][2].to_i
369 to =points[i+1][2].to_i
370 if seg.has_key?(segid)
371 # if segment exists, check it still refers to the same nodes
372 if seg[segid]=="#{from}-#{to}" then
373 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
377 # not in previous version of way, but supplied, so assume
378 # that it's come from makeway (i.e. unwayed segments)
379 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
382 segid=ActiveRecord::Base.connection.insert("INSERT INTO current_segments ( node_a,node_b,timestamp,user_id,visible,tags) VALUES ( #{from},#{to},#{db_now},#{uid},1,'')")
383 ActiveRecord::Base.connection.insert("INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible,tags) VALUES (#{segid},#{from},#{to},#{db_now},#{uid},1,'')")
385 numberedsegments[(i+1).to_s]=segid.to_s
389 # -- 6.ii insert new way segments
391 createuniquesegments(way,db_uqs,seglist) # segments which appear in this way but no other
393 # delete segments from uniquesegments (and not in modified way)
396 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
397 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
398 FROM current_segments AS cs, #{db_uqs} AS us
399 WHERE cs.id=us.segment_id AND cs.visible=1
401 ActiveRecord::Base.connection.insert(sql)
404 UPDATE current_segments AS cs, #{db_uqs} AS us
405 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
406 WHERE cs.id=us.segment_id AND cs.visible=1
408 ActiveRecord::Base.connection.update(sql)
410 # delete nodes not in modified way or any other segments
412 createuniquenodes(db_uqs,db_uqn) # nodes which appear in this way but no other
415 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
416 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
417 FROM current_nodes AS cn,#{db_uqn}
420 ActiveRecord::Base.connection.insert(sql)
423 UPDATE current_nodes AS cn, #{db_uqn}
424 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
427 ActiveRecord::Base.connection.update(sql)
429 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
430 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
432 # insert new version of route into way_segments
437 for i in (0..(points.length-2))
438 if (points[i+1][3].to_i==0) then next end
439 if insertsql !='' then insertsql +=',' end
440 if currentsql!='' then currentsql+=',' end
441 insertsql +="(#{way},#{points[i+1][5]},#{version})"
442 currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
446 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
447 ActiveRecord::Base.connection.insert("INSERT INTO way_segments (id,segment_id,version ) VALUES #{insertsql}");
448 ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
450 # -- 7. insert new way tags
454 attributes.each do |k,v|
455 if v=='' or v.nil? then next end
456 if v[0,6]=='(type ' then next end
457 if insertsql !='' then insertsql +=',' end
458 if currentsql!='' then currentsql+=',' end
459 k=k.gsub(/[\000-\037]/,"")
460 v=v.gsub(/[\000-\037]/,"")
461 insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',#{version})"
462 currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
465 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
466 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
467 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
469 [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
472 # ----- putpoi (user token, id, x,y,tag array,visible,baselong,basey,masterscale)
473 # returns current id, new id
474 # if new: add new row to current_nodes and nodes
475 # if old: add new row to nodes, update current_nodes
478 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
479 uid=getuserid(usertoken)
481 db_now='@now'+uid.to_s+id.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
482 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
486 x=coord2long(x.to_f,masterscale,baselong)
487 y=coord2lat(y.to_f,masterscale,basey)
488 tagsql="'"+sqlescape(array2tag(tags))+"'"
489 lat=(y * 10000000).round
490 long=(x * 10000000).round
491 tile=QuadTile.tile_for_point(y, x)
494 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})");
495 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}");
498 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})");
499 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})");
504 # ----- getpoi (id,baselong,basey,masterscale)
505 # returns id,x,y,tag array
508 id,baselong,basey,masterscale=args; id=id.to_i
509 poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
510 "FROM current_nodes WHERE visible=1 AND id=#{id}")
511 if poi.nil? then return [nil,nil,nil,''] end
513 long2coord(poi['lng'].to_f,baselong,masterscale),
514 lat2coord(poi['lat'].to_f,basey,masterscale),
515 tag2array(poi['tags'])]
518 # ----- deleteway (user token, way)
519 # returns way ID only
524 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
526 uid=getuserid(usertoken); if !uid then return end
529 db_uqs='uniq'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquesegments table name, typically 51 chars
530 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
531 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
532 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
533 createuniquesegments(way,db_uqs,'')
535 # - delete any otherwise unused segments
538 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
539 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
540 FROM current_segments AS cs, #{db_uqs} AS us
541 WHERE cs.id=us.segment_id
543 ActiveRecord::Base.connection.insert(sql)
546 UPDATE current_segments AS cs, #{db_uqs} AS us
547 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
548 WHERE cs.id=us.segment_id
550 ActiveRecord::Base.connection.update(sql)
552 # - delete any unused nodes
554 createuniquenodes(db_uqs,db_uqn)
557 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
558 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
559 FROM current_nodes AS cn,#{db_uqn}
562 ActiveRecord::Base.connection.insert(sql)
565 UPDATE current_nodes AS cn, #{db_uqn}
566 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
569 ActiveRecord::Base.connection.update(sql)
571 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
572 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
576 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
577 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
578 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
579 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
584 # ----- makeway(x,y,baselong,basey,masterscale)
585 # returns way made from unwayed segments
588 usertoken,x,y,baselong,basey,masterscale=args
589 uid=getuserid(usertoken)
593 toreverse=[] # segments to reverse
594 nodesused={} # so we don't go over the same node twice
596 # - find start point near x
598 xc=coord2long(x,masterscale,baselong)
599 yc=coord2lat(y,masterscale,basey)
601 RAILS_DEFAULT_LOGGER.info(" Message: makeway, xc=#{xc}, y=#{yc}")
603 xs1=xc-0.001; xs2=xc+0.001
604 ys1=yc-0.001; ys2=yc+0.001
607 SELECT cn1.latitude*0.0000001 AS lat1,cn1.longitude*0.0000001 AS lon1,cn1.id AS id1,
608 cn2.latitude*0.0000001 AS lat2,cn2.longitude*0.0000001 AS lon2,cn2.id AS id2, cs.id AS segid
609 FROM current_nodes AS cn1,
610 current_nodes AS cn2,
611 current_segments AS cs
612 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
613 WHERE #{OSM.sql_for_area(ys1,xs1,ys2,xs2,"cn1.")}
614 AND segment_id IS NULL
616 AND cn1.id=node_a AND cn1.visible=1
617 AND cn2.id=node_b AND cn2.visible=1
618 ORDER BY SQRT(POW(cn1.longitude-#{xc},2)+
619 POW(cn1.latitude -#{yc},2))
622 row=ActiveRecord::Base.connection.select_one sql
623 if row.nil? then return [0,0,0,0,0] end
624 xs1=long2coord(row['lon1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
625 xs2=long2coord(row['lon2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
626 xmin=[xs1,xs2].min; xmax=[xs1,xs2].max
627 ymin=[ys1,ys2].min; ymax=[ys1,ys2].max
628 nodesused[row['id1'].to_i]=true
629 nodesused[row['id2'].to_i]=true
630 points<<[xs1,ys1,row['id1'].to_i,1,{},0]
631 points<<[xs2,ys2,row['id2'].to_i,1,{},row['segid'].to_i]
633 # - extend at start, then end
634 while (a,point,nodesused,toreverse=findconnect(points[0][2],nodesused,'b',toreverse,baselong,basey,masterscale))[0]
635 points[0][5]=point[5]; point[5]=0 # segment leads to next node
636 points.unshift(point)
637 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
638 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
640 while (a,point,nodesused,toreverse=findconnect(points[-1][2],nodesused,'a',toreverse,baselong,basey,masterscale))[0]
642 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
643 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
645 points[0][3]=0 # start with a move
647 # reverse segments in toreverse
648 if toreverse.length>0
650 UPDATE current_segments c1, current_segments c2
651 SET c1.node_a=c2.node_b,c1.node_b=c2.node_a,
652 c1.timestamp=NOW(),c1.user_id=#{uid}
654 AND c1.id IN (#{toreverse.join(',')})
656 ActiveRecord::Base.connection.update sql
659 (SELECT * FROM current_segments
660 WHERE id IN (#{toreverse.join(',')}))
662 ActiveRecord::Base.connection.insert sql
665 [points,xmin,xmax,ymin,ymax]
668 def findconnect(id,nodesused,lookfor,toreverse,baselong,basey,masterscale)
669 # get all segments with 'id' as a point
670 # (to look for both node_a and node_b, UNION is faster than node_a=id OR node_b=id)!
672 SELECT cn1.latitude*0.0000001 AS lat1,cn1.longitude*0.0000001 AS lon1,cn1.id AS id1,
673 cn2.latitude*0.0000001 AS lat2,cn2.longitude*0.0000001 AS lon2,cn2.id AS id2, cs.id AS segid
674 FROM current_nodes AS cn1,
675 current_nodes AS cn2,
676 current_segments AS cs
677 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
678 WHERE segment_id IS NULL
680 AND cn1.id=node_a AND cn1.visible=1
681 AND cn2.id=node_b AND cn2.visible=1
684 SELECT cn1.latitude*0.0000001 AS lat1,cn1.longitude*0.0000001 AS lon1,cn1.id AS id1,
685 cn2.latitude*0.0000001 AS lat2,cn2.longitude*0.0000001 AS lon2,cn2.id AS id2, cs.id AS segid
686 FROM current_nodes AS cn1,
687 current_nodes AS cn2,
688 current_segments AS cs
689 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
690 WHERE segment_id IS NULL
692 AND cn1.id=node_a AND cn1.visible=1
693 AND cn2.id=node_b AND cn2.visible=1
696 connectlist=ActiveRecord::Base.connection.select_all sql
698 if lookfor=='b' then tocol='id1'; tolat='lat1'; tolon='lon1'; fromcol='id2'; fromlat='lat2'; fromlon='lon2'
699 else tocol='id2'; tolat='lat2'; tolon='lon2'; fromcol='id1'; fromlat='lat1'; fromlon='lon1'
702 # eliminate those already in the hash
705 connectlist.each { |row|
706 tonode=row[tocol].to_i
707 fromnode=row[fromcol].to_i
708 if id==tonode and !nodesused.has_key?(fromnode)
709 # wrong way round; add, then add to 'segments to reverse' list
711 nodesused[fromnode]=true
712 point=[long2coord(row[fromlon].to_f,baselong,masterscale),lat2coord(row[fromlat].to_f,basey,masterscale),fromnode,1,{},row['segid'].to_i]
713 toreverse.push(row['segid'].to_i)
714 elsif id==fromnode and !nodesused.has_key?(tonode)
715 # right way round; just add
717 point=[long2coord(row[tolon].to_f,baselong,masterscale),lat2coord(row[tolat].to_f,basey,masterscale),tonode,1,{},row['segid'].to_i]
718 nodesused[tonode]=true
722 # if only one left, then add it; otherwise return false
723 if connex!=1 or point.nil? then
724 return [false,[],nodesused,toreverse]
726 return [true,point,nodesused,toreverse]
731 # ====================================================================
732 # Support functions for remote calls
735 ActiveRecord::Base.connection.select_all "SELECT n1.latitude*0.0000001 AS lat1,n1.longitude*0.0000001 AS long1,n1.id AS id1,n1.tags as tags1, "+
736 " n2.latitude*0.0000001 AS lat2,n2.longitude*0.0000001 AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
737 " FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
738 " WHERE current_way_segments.id=#{id} "+
739 " AND segment_id=current_segments.id "+
740 " AND current_segments.visible=1 "+
741 " AND n1.id=node_a AND n2.id=node_b "+
742 " AND n1.visible=1 AND n2.visible=1 "+
743 " ORDER BY sequence_id"
746 def createuniquesegments(way,uqs_name,seglist)
747 # Finds segments which appear in (previous version of) this way and no other
749 CREATE TEMPORARY TABLE #{uqs_name}
751 FROM (SELECT DISTINCT segment_id FROM current_way_segments
753 LEFT JOIN current_way_segments b
754 ON b.segment_id = a.segment_id
756 WHERE b.segment_id IS NULL
758 if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
759 ActiveRecord::Base.connection.execute(sql)
762 def createuniquenodes(uqs_name,uqn_name)
763 # Finds nodes which appear in uniquesegments but no other segments
765 CREATE TEMPORARY TABLE #{uqn_name}
766 SELECT DISTINCT node_id
767 FROM (SELECT cn.id AS node_id
768 FROM current_nodes AS cn,
769 current_segments AS cs,
771 WHERE cs.id=us.segment_id
772 AND cn.id=cs.node_a) AS n
773 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
774 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
775 WHERE cs2.node_a IS NULL
776 AND cs3.node_b IS NULL
778 ActiveRecord::Base.connection.execute(sql)
780 INSERT INTO #{uqn_name}
781 SELECT DISTINCT node_id
782 FROM (SELECT cn.id AS node_id
783 FROM current_nodes AS cn,
784 current_segments AS cs,
786 WHERE cs.id=us.segment_id
787 AND cn.id=cs.node_b) AS n
788 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
789 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
790 WHERE cs2.node_a IS NULL
791 AND cs3.node_b IS NULL
793 ActiveRecord::Base.connection.execute(sql)
797 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
802 a.gsub(';;;','#%').split(';').each do |b|
806 if k.nil? then k='' end
807 if v.nil? then v='' end
808 tags[k.gsub('#%','=')]=v.gsub('#%','=')
816 if v=='' then next end
817 if v[0,6]=='(type ' then next end
818 if str!='' then str+=';' end
819 str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
825 if (token =~ /^(.+)\+(.+)$/) then
826 user = User.authenticate(:username => $1, :password => $2)
828 user = User.authenticate(:token => token)
831 return user ? user.id : nil;
836 # ====================================================================
837 # AMF read subroutines
839 # ----- getint return two-byte integer
840 # ----- getlong return four-byte long
841 # ----- getstring return string with two-byte length
842 # ----- getdouble return eight-byte double-precision float
843 # ----- getobject return object/hash
844 # ----- getarray return numeric array
851 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
855 len=s.getc*256+s.getc
860 a=s.read(8).unpack('G') # G big-endian, E little-endian
875 while (key=getstring(s))
876 if (key=='') then break end
879 s.getc # skip the 9 'end of object' value
883 # ----- getvalue parse and get value
887 when 0; return getdouble(s) # number
888 when 1; return s.getc # boolean
889 when 2; return getstring(s) # string
890 when 3; return getobject(s) # object/hash
891 when 5; return nil # null
892 when 6; return nil # undefined
893 when 8; s.read(4) # mixedArray
894 return getobject(s) # |
895 when 10; return getarray(s) # array
896 else; return nil # error
900 # ====================================================================
901 # AMF write subroutines
903 # ----- putdata envelope data into AMF writeable form
904 # ----- encodevalue pack variables as AMF
907 d =encodestring(index+"/onResult")
908 d+=encodestring("null")
916 a=10.chr+encodelong(n.length)
924 a+=encodestring(k)+encodevalue(v)
928 2.chr+encodestring(n)
929 when 'Bignum','Fixnum','Float'
930 0.chr+encodedouble(n)
934 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
938 # ----- encodestring encode string with two-byte length
939 # ----- encodedouble encode number as eight-byte double precision float
940 # ----- encodelong encode number as four-byte long
943 a,b=n.size.divmod(256)
955 # ====================================================================
956 # Co-ordinate conversion
958 def lat2coord(a,basey,masterscale)
959 -(lat2y(a)-basey)*masterscale+250
962 def long2coord(a,baselong,masterscale)
963 (a-baselong)*masterscale+350
967 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
970 def coord2lat(a,masterscale,basey)
971 y2lat((a-250)/-masterscale+basey)
974 def coord2long(a,masterscale,baselong)
975 (a-350)/masterscale+baselong
979 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)