1 class AmfController < ApplicationController
5 before_filter :check_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))
52 RAILS_DEFAULT_LOGGER.info(" Response: start")
53 a,b=results.length.divmod(256)
54 render :content_type => "application/x-amf", :text => proc { |response, output|
55 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
60 RAILS_DEFAULT_LOGGER.info(" Response: end")
66 # ====================================================================
70 # return presets,presetmenus and presetnames arrays
74 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]
75 presetnames={}; presetnames['point']={}; presetnames['way']={}
79 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
81 # File.open("config/potlatch/presets.txt") do |file|
83 # Temporary patch to get around filepath problem
84 # To remove this patch and make the code nice again:
85 # 1. uncomment above line
86 # 2. fix the path in the above line
87 # 3. delete this here document, and the following line (StringIO....)
91 motorway: highway=motorway,ref=(type road number)
92 trunk road: highway=trunk,ref=(type road number),name=(type road name)
93 primary road: highway=primary,ref=(type road number),name=(type road name)
94 secondary road: highway=secondary,ref=(type road number),name=(type road name)
95 residential road: highway=residential,name=(type road name)
96 unclassified road: highway=unclassified,name=(type road name)
99 footpath: highway=footway,foot=yes
100 bridleway: highway=bridleway,foot=yes,horse=yes,bicycle=yes
101 byway: highway=byway,foot=yes,horse=yes,bicycle=yes,motorcar=yes
102 permissive path: highway=footway,foot=permissive
105 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
106 cycle track: highway=cycleway,cycleway=track,ncn_ref=
107 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
108 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
111 canal: waterway=canal,name=(type name here)
112 navigable river: waterway=river,boat=yes,name=(type name here)
113 navigable drain: waterway=drain,boat=yes,name=(type name here)
114 derelict canal: waterway=derelict_canal,name=(type name here)
115 unnavigable river: waterway=river,boat=no,name=(type name here)
116 unnavigable drain: waterway=drain,boat=no,name=(type name here)
119 railway: railway=rail
120 tramway: railway=tram
121 light railway: railway=light_rail
122 preserved railway: railway=preserved
123 disused railway tracks: railway=disused
124 course of old railway: railway=abandoned
127 forest: natural=wood,landuse=forest
128 woodland: natural=wood,landuse=
129 reservoir: natural=water,landuse=reservoir
130 lake: natural=water,landuse=
133 coastline: natural=coastline
136 mini roundabout: highway=mini_roundabout
137 traffic lights: highway=traffic_signals
140 bridge: highway=bridge
143 cattle grid: highway=cattle_grid
149 lock gate: waterway=lock_gate
151 aqueduct: waterway=aqueduct
152 winding hole: waterway=turning_point
153 mooring: waterway=mooring
156 station: railway=station
157 viaduct: railway=viaduct
158 level crossing: railway=crossing
164 StringIO.open(txt) do |file|
165 file.each_line {|line|
167 if (t=~/(\w+)\/(\w+)/) then
170 presetmenus[presettype].push(presetcategory)
171 presetnames[presettype][presetcategory]=["(no preset)"]
172 elsif (t=~/^(.+):\s?(.+)$/) then
174 presetnames[presettype][presetcategory].push(pre)
176 kv.split(',').each {|a|
177 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
182 return [presets,presetmenus,presetnames]
185 # ----- whichways(left,bottom,right,top)
186 # return array of ways in current bounding box
187 # at present, instead of using correct (=more complex) SQL to find
188 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
191 xmin = args[0].to_f-0.01
192 ymin = args[1].to_f-0.01
193 xmax = args[2].to_f+0.01
194 ymax = args[3].to_f+0.01
196 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
198 waylist=WayNode.find_by_sql("SELECT DISTINCT current_way_nodes.id AS wayid"+
199 " FROM current_way_nodes,current_segments,current_nodes,current_ways "+
200 " WHERE segment_id=current_segments.id "+
201 " AND current_segments.visible=1 "+
202 " AND node_a=current_nodes.id "+
203 " AND current_ways.id=current_way_nodes.id "+
204 " AND current_ways.visible=1 "+
205 " AND (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
206 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+")")
208 ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
210 pointlist =ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.tags "+
211 " FROM current_nodes "+
212 " LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
213 " LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
214 " WHERE (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
215 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+") "+
216 " AND cs1.id IS NULL AND cs2.id IS NULL "+
217 " AND current_nodes.visible=1")
219 points = pointlist.collect {|a| [a['id'],tag2array(a['tags'])] } # get a list of node ids and their tags
224 # ----- getway (objectname, way, baselong, basey, masterscale)
225 # returns objectname, array of co-ordinates, attributes,
226 # xmin,xmax,ymin,ymax
229 objname,wayid,baselong,basey,masterscale=args
234 xmax = ymax = -999999
236 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
238 readwayquery(wayid).each {|row|
239 xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
240 xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
241 points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
242 lastid = row['id2'].to_i
243 points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
244 xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
245 xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
246 ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
247 ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
251 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
252 attrlist.each {|a| attributes[a['k']]=a['v'] }
254 [objname,points,attributes,xmin,xmax,ymin,ymax]
257 # ----- putway (user token, way, array of co-ordinates, array of attributes,
258 # baselong, basey, masterscale)
259 # returns current way ID, new way ID, hash of renumbered nodes,
260 # xmin,xmax,ymin,ymax
263 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
264 uid=getuserid(usertoken)
266 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
267 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
268 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
269 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
270 originalway=originalway.to_i
272 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
274 # -- 3. read original way into memory
276 xc={}; yc={}; tagc={}; seg={}
279 readwayquery(way).each { |row|
280 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
281 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
282 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
284 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
286 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
289 # -- 4. get version by inserting new row into ways
291 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
293 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
296 xmax = ymax = -999999
300 points.each_index do |i|
301 xs=coord2long(points[i][0],masterscale,baselong)
302 ys=coord2lat(points[i][1],masterscale,basey)
303 xmin=[xs,xmin].min; xmax=[xs,xmax].max
304 ymin=[ys,ymin].min; ymax=[ys,ymax].max
305 node=points[i][2].to_i
306 tagstr=array2tag(points[i][4])
307 tagstr=tagstr.gsub(/[\000-\037]/,"")
308 tagsql="'"+sqlescape(tagstr)+"'"
313 if renumberednodes[node.to_s].nil?
314 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes ( latitude,longitude,timestamp,user_id,visible,tags) VALUES ( #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
315 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
317 renumberednodes[node.to_s]=newnode.to_s
319 points[i][2]=renumberednodes[node.to_s].to_i
322 elsif xc.has_key?(node)
323 # old node from original way - update
324 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
325 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
326 ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{ys},longitude=#{xs},timestamp=#{db_now},user_id=#{uid},tags=#{tagsql},visible=1 WHERE id=#{node}")
329 # old node, created in another way and now added to this way
335 # -- 6.i compare segments
338 seglist='' # list of existing segments that we want to keep
339 for i in (0..(points.length-2))
340 if (points[i+1][3].to_i==0) then next end
341 segid=points[i+1][5].to_i
342 from =points[i ][2].to_i
343 to =points[i+1][2].to_i
344 if seg.has_key?(segid)
345 # if segment exists, check it still refers to the same nodes
346 if seg[segid]=="#{from}-#{to}" then
347 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
351 # not in previous version of way, but supplied, so assume
352 # that it's come from makeway (i.e. unwayed segments)
353 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
356 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,'')")
357 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,'')")
359 numberedsegments[(i+1).to_s]=segid.to_s
363 # -- 6.ii insert new way segments
365 createuniquesegments(way,db_uqs,seglist) # segments which appear in this way but no other
367 # delete segments from uniquesegments (and not in modified way)
370 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
371 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
372 FROM current_segments AS cs, #{db_uqs} AS us
373 WHERE cs.id=us.segment_id AND cs.visible=1
375 ActiveRecord::Base.connection.insert(sql)
378 UPDATE current_segments AS cs, #{db_uqs} AS us
379 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
380 WHERE cs.id=us.segment_id AND cs.visible=1
382 ActiveRecord::Base.connection.update(sql)
384 # delete nodes not in modified way or any other segments
386 createuniquenodes(db_uqs,db_uqn) # nodes which appear in this way but no other
389 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
390 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
391 FROM current_nodes AS cn,#{db_uqn}
394 ActiveRecord::Base.connection.insert(sql)
397 UPDATE current_nodes AS cn, #{db_uqn}
398 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
401 ActiveRecord::Base.connection.update(sql)
403 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
404 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
406 # insert new version of route into way_nodes
411 for i in (0..(points.length-2))
412 if (points[i+1][3].to_i==0) then next end
413 if insertsql !='' then insertsql +=',' end
414 if currentsql!='' then currentsql+=',' end
415 insertsql +="(#{way},#{points[i+1][5]},#{version})"
416 currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
420 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
421 ActiveRecord::Base.connection.insert("INSERT INTO way_nodes (id,segment_id,version ) VALUES #{insertsql}");
422 ActiveRecord::Base.connection.insert("INSERT INTO current_way_nodes (id,segment_id,sequence_id) VALUES #{currentsql}");
424 # -- 7. insert new way tags
428 attributes.each do |k,v|
429 if v=='' or v.nil? then next end
430 if v[0,6]=='(type ' then next end
431 if insertsql !='' then insertsql +=',' end
432 if currentsql!='' then currentsql+=',' end
433 k=k.gsub(/[\000-\037]/,"")
434 v=v.gsub(/[\000-\037]/,"")
435 insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',#{version})"
436 currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
439 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
440 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
441 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
443 [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
446 # ----- deleteway (user token, way)
447 # returns way ID only
452 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
454 uid=getuserid(usertoken); if !uid then return end
457 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
458 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
459 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
460 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
461 createuniquesegments(way,db_uqs,'')
463 # - delete any otherwise unused segments
466 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
467 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
468 FROM current_segments AS cs, #{db_uqs} AS us
469 WHERE cs.id=us.segment_id
471 ActiveRecord::Base.connection.insert(sql)
474 UPDATE current_segments AS cs, #{db_uqs} AS us
475 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
476 WHERE cs.id=us.segment_id
478 ActiveRecord::Base.connection.update(sql)
480 # - delete any unused nodes
482 createuniquenodes(db_uqs,db_uqn)
485 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
486 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
487 FROM current_nodes AS cn,#{db_uqn}
490 ActiveRecord::Base.connection.insert(sql)
493 UPDATE current_nodes AS cn, #{db_uqn}
494 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
497 ActiveRecord::Base.connection.update(sql)
499 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
500 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
504 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
505 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
506 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
507 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
512 # ----- makeway(x,y,baselong,basey,masterscale)
513 # returns way made from unwayed segments
516 usertoken,x,y,baselong,basey,masterscale=args
517 uid=getuserid(usertoken)
521 toreverse=[] # segments to reverse
522 nodesused={} # so we don't go over the same node twice
524 # - find start point near x
526 xc=coord2long(x,masterscale,baselong)
527 yc=coord2lat(y,masterscale,basey)
529 RAILS_DEFAULT_LOGGER.info(" Message: makeway, xc=#{xc}, y=#{yc}")
531 xs1=xc-0.001; xs2=xc+0.001
532 ys1=yc-0.001; ys2=yc+0.001
535 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
536 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
537 FROM current_nodes AS cn1,
538 current_nodes AS cn2,
539 current_segments AS cs
540 LEFT OUTER JOIN current_way_nodes ON segment_id=cs.id
541 WHERE (cn1.longitude BETWEEN #{xs1} AND #{xs2})
542 AND (cn1.latitude BETWEEN #{ys1} AND #{ys2})
543 AND segment_id IS NULL
545 AND cn1.id=node_a AND cn1.visible=1
546 AND cn2.id=node_b AND cn2.visible=1
547 ORDER BY SQRT(POW(cn1.longitude-#{xc},2)+
548 POW(cn1.latitude -#{yc},2))
551 row=ActiveRecord::Base.connection.select_one sql
552 if row.nil? then return [0,0,0,0,0] end
553 xs1=long2coord(row['lon1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
554 xs2=long2coord(row['lon2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
555 xmin=[xs1,xs2].min; xmax=[xs1,xs2].max
556 ymin=[ys1,ys2].min; ymax=[ys1,ys2].max
557 nodesused[row['id1'].to_i]=true
558 nodesused[row['id2'].to_i]=true
559 points<<[xs1,ys1,row['id1'].to_i,1,{},0]
560 points<<[xs2,ys2,row['id2'].to_i,1,{},row['segid'].to_i]
562 # - extend at start, then end
563 while (a,point,nodesused,toreverse=findconnect(points[0][2],nodesused,'b',toreverse,baselong,basey,masterscale))[0]
564 points[0][5]=point[5]; point[5]=0 # segment leads to next node
565 points.unshift(point)
566 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
567 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
569 while (a,point,nodesused,toreverse=findconnect(points[-1][2],nodesused,'a',toreverse,baselong,basey,masterscale))[0]
571 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
572 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
574 points[0][3]=0 # start with a move
576 # reverse segments in toreverse
577 if toreverse.length>0
579 UPDATE current_segments c1, current_segments c2
580 SET c1.node_a=c2.node_b,c1.node_b=c2.node_a,
581 c1.timestamp=NOW(),c1.user_id=#{uid}
583 AND c1.id IN (#{toreverse.join(',')})
585 ActiveRecord::Base.connection.update sql
588 (SELECT * FROM current_segments
589 WHERE id IN (#{toreverse.join(',')}))
591 ActiveRecord::Base.connection.insert sql
594 [points,xmin,xmax,ymin,ymax]
597 def findconnect(id,nodesused,lookfor,toreverse,baselong,basey,masterscale)
598 # get all segments with 'id' as a point
599 # (to look for both node_a and node_b, UNION is faster than node_a=id OR node_b=id)!
601 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
602 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
603 FROM current_nodes AS cn1,
604 current_nodes AS cn2,
605 current_segments AS cs
606 LEFT OUTER JOIN current_way_nodes ON segment_id=cs.id
607 WHERE segment_id IS NULL
609 AND cn1.id=node_a AND cn1.visible=1
610 AND cn2.id=node_b AND cn2.visible=1
613 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
614 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
615 FROM current_nodes AS cn1,
616 current_nodes AS cn2,
617 current_segments AS cs
618 LEFT OUTER JOIN current_way_nodes ON segment_id=cs.id
619 WHERE segment_id IS NULL
621 AND cn1.id=node_a AND cn1.visible=1
622 AND cn2.id=node_b AND cn2.visible=1
625 connectlist=ActiveRecord::Base.connection.select_all sql
627 if lookfor=='b' then tocol='id1'; tolat='lat1'; tolon='lon1'; fromcol='id2'; fromlat='lat2'; fromlon='lon2'
628 else tocol='id2'; tolat='lat2'; tolon='lon2'; fromcol='id1'; fromlat='lat1'; fromlon='lon1'
631 # eliminate those already in the hash
634 connectlist.each { |row|
635 tonode=row[tocol].to_i
636 fromnode=row[fromcol].to_i
637 if id==tonode and !nodesused.has_key?(fromnode)
638 # wrong way round; add, then add to 'segments to reverse' list
640 nodesused[fromnode]=true
641 point=[long2coord(row[fromlon].to_f,baselong,masterscale),lat2coord(row[fromlat].to_f,basey,masterscale),fromnode,1,{},row['segid'].to_i]
642 toreverse.push(row['segid'].to_i)
643 elsif id==fromnode and !nodesused.has_key?(tonode)
644 # right way round; just add
646 point=[long2coord(row[tolon].to_f,baselong,masterscale),lat2coord(row[tolat].to_f,basey,masterscale),tonode,1,{},row['segid'].to_i]
647 nodesused[tonode]=true
651 # if only one left, then add it; otherwise return false
652 if connex!=1 or point.nil? then
653 return [false,[],nodesused,toreverse]
655 return [true,point,nodesused,toreverse]
660 # ====================================================================
661 # Support functions for remote calls
664 ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
665 " n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
666 " FROM current_way_nodes,current_segments,current_nodes AS n1,current_nodes AS n2 "+
667 " WHERE current_way_nodes.id=#{id} "+
668 " AND segment_id=current_segments.id "+
669 " AND current_segments.visible=1 "+
670 " AND n1.id=node_a and n2.id=node_b "+
671 " AND n1.visible=1 AND n2.visible=1 "+
672 " ORDER BY sequence_id"
675 def createuniquesegments(way,uqs_name,seglist)
676 # Finds segments which appear in (previous version of) this way and no other
678 CREATE TEMPORARY TABLE #{uqs_name}
680 FROM (SELECT DISTINCT segment_id FROM current_way_nodes
682 LEFT JOIN current_way_nodes b
683 ON b.segment_id = a.segment_id
685 WHERE b.segment_id IS NULL
687 if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
688 ActiveRecord::Base.connection.execute(sql)
691 def createuniquenodes(uqs_name,uqn_name)
692 # Finds nodes which appear in uniquesegments but no other segments
694 CREATE TEMPORARY TABLE #{uqn_name}
695 SELECT DISTINCT node_id
696 FROM (SELECT cn.id AS node_id
697 FROM current_nodes AS cn,
698 current_segments AS cs,
700 WHERE cs.id=us.segment_id
701 AND (cn.id=cs.node_a OR cn.id=cs.node_b)) AS n
702 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
703 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
704 WHERE cs2.node_a IS NULL
705 AND cs3.node_b IS NULL
707 ActiveRecord::Base.connection.execute(sql)
711 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
716 a.gsub(';;;','#%').split(';').each do |b|
720 if k.nil? then k='' end
721 if v.nil? then v='' end
722 tags[k.gsub('#%','=')]=v.gsub('#%','=')
730 if v=='' then next end
731 if v[0,6]=='(type ' then next end
732 if str!='' then str+=';' end
733 str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
739 if (token =~ /^(.+)\+(.+)$/) then
740 user = User.authenticate(:username => $1, :password => $2)
742 user = User.authenticate(:token => token)
745 return user ? user.id : nil;
750 # ====================================================================
751 # AMF read subroutines
753 # ----- getint return two-byte integer
754 # ----- getlong return four-byte long
755 # ----- getstring return string with two-byte length
756 # ----- getdouble return eight-byte double-precision float
757 # ----- getobject return object/hash
758 # ----- getarray return numeric array
765 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
769 len=s.getc*256+s.getc
774 a=s.read(8).unpack('G') # G big-endian, E little-endian
789 while (key=getstring(s))
790 if (key=='') then break end
793 s.getc # skip the 9 'end of object' value
797 # ----- getvalue parse and get value
801 when 0; return getdouble(s) # number
802 when 1; return s.getc # boolean
803 when 2; return getstring(s) # string
804 when 3; return getobject(s) # object/hash
805 when 5; return nil # null
806 when 6; return nil # undefined
807 when 8; s.read(4) # mixedArray
808 return getobject(s) # |
809 when 10; return getarray(s) # array
810 else; return nil # error
814 # ====================================================================
815 # AMF write subroutines
817 # ----- putdata envelope data into AMF writeable form
818 # ----- encodevalue pack variables as AMF
821 d =encodestring(index+"/onResult")
822 d+=encodestring("null")
830 a=10.chr+encodelong(n.length)
838 a+=encodestring(k)+encodevalue(v)
842 2.chr+encodestring(n)
843 when 'Bignum','Fixnum','Float'
844 0.chr+encodedouble(n)
848 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
852 # ----- encodestring encode string with two-byte length
853 # ----- encodedouble encode number as eight-byte double precision float
854 # ----- encodelong encode number as four-byte long
857 a,b=n.size.divmod(256)
869 # ====================================================================
870 # Co-ordinate conversion
872 def lat2coord(a,basey,masterscale)
873 -(lat2y(a)-basey)*masterscale+250
876 def long2coord(a,baselong,masterscale)
877 (a-baselong)*masterscale+350
881 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
884 def coord2lat(a,masterscale,basey)
885 y2lat((a-250)/-masterscale+basey)
888 def coord2long(a,masterscale,baselong)
889 (a-350)/masterscale+baselong
893 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)