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))
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 (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
232 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+")")
234 ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
236 pointlist =ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,latitude,longitude,current_nodes.tags "+
237 " FROM current_nodes "+
238 " LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
239 " LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
240 " WHERE (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
241 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+") "+
242 " AND cs1.id IS NULL AND cs2.id IS NULL "+
243 " AND current_nodes.visible=1")
245 points = pointlist.collect {|a| [a['id'],long2coord(a['longitude'].to_f,baselong,masterscale),lat2coord(a['latitude'].to_f,basey,masterscale),tag2array(a['tags'])] } # get a list of node ids and their tags
250 # ----- getway (objectname, way, baselong, basey, masterscale)
251 # returns objectname, array of co-ordinates, attributes,
252 # xmin,xmax,ymin,ymax
255 objname,wayid,baselong,basey,masterscale=args
260 xmax = ymax = -999999
262 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
264 readwayquery(wayid).each {|row|
265 xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
266 xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
267 points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
268 lastid = row['id2'].to_i
269 points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
270 xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
271 xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
272 ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
273 ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
277 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
278 attrlist.each {|a| attributes[a['k']]=a['v'] }
280 [objname,points,attributes,xmin,xmax,ymin,ymax]
283 # ----- putway (user token, way, array of co-ordinates, array of attributes,
284 # baselong, basey, masterscale)
285 # returns current way ID, new way ID, hash of renumbered nodes,
286 # xmin,xmax,ymin,ymax
289 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
290 uid=getuserid(usertoken)
292 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
293 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
294 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
295 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
296 originalway=originalway.to_i
298 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
300 # -- 3. read original way into memory
302 xc={}; yc={}; tagc={}; seg={}
305 readwayquery(way).each { |row|
306 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
307 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
308 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
310 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
312 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
315 # -- 4. get version by inserting new row into ways
317 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
319 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
322 xmax = ymax = -999999
326 points.each_index do |i|
327 xs=coord2long(points[i][0],masterscale,baselong)
328 ys=coord2lat(points[i][1],masterscale,basey)
329 xmin=[xs,xmin].min; xmax=[xs,xmax].max
330 ymin=[ys,ymin].min; ymax=[ys,ymax].max
331 node=points[i][2].to_i
332 tagstr=array2tag(points[i][4])
333 tagstr=tagstr.gsub(/[\000-\037]/,"")
334 tagsql="'"+sqlescape(tagstr)+"'"
339 if renumberednodes[node.to_s].nil?
340 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes ( latitude,longitude,timestamp,user_id,visible,tags) VALUES ( #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
341 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
343 renumberednodes[node.to_s]=newnode.to_s
345 points[i][2]=renumberednodes[node.to_s].to_i
348 elsif xc.has_key?(node)
349 # old node from original way - update
350 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
351 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
352 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}")
355 # 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)
416 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
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))+"'"
491 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{id},#{y},#{x},#{db_now},#{uid},#{visible},#{tagsql})");
492 ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{y},longitude=#{x},timestamp=#{db_now},user_id=#{uid},visible=#{visible},tags=#{tagsql} WHERE id=#{id}");
495 newid=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{y},#{x},#{db_now},#{uid},#{visible},#{tagsql})");
496 ActiveRecord::Base.connection.update("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newid},#{y},#{x},#{db_now},#{uid},#{visible},#{tagsql})");
501 # ----- getpoi (id,baselong,basey,masterscale)
502 # returns id,x,y,tag array
505 id,baselong,basey,masterscale=args; id=id.to_i
506 poi=ActiveRecord::Base.connection.select_one("SELECT latitude,longitude,tags "+
507 "FROM current_nodes WHERE visible=1 AND id=#{id}")
508 if poi.nil? then return [nil,nil,nil,''] end
510 long2coord(poi['longitude'].to_f,baselong,masterscale),
511 lat2coord(poi['latitude'].to_f,basey,masterscale),
512 tag2array(poi['tags'])]
515 # ----- deleteway (user token, way)
516 # returns way ID only
521 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
523 uid=getuserid(usertoken); if !uid then return end
526 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
527 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
528 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
529 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
530 createuniquesegments(way,db_uqs,'')
532 # - delete any otherwise unused segments
535 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
536 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
537 FROM current_segments AS cs, #{db_uqs} AS us
538 WHERE cs.id=us.segment_id
540 ActiveRecord::Base.connection.insert(sql)
543 UPDATE current_segments AS cs, #{db_uqs} AS us
544 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
545 WHERE cs.id=us.segment_id
547 ActiveRecord::Base.connection.update(sql)
549 # - delete any unused nodes
551 createuniquenodes(db_uqs,db_uqn)
554 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
555 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
556 FROM current_nodes AS cn,#{db_uqn}
559 ActiveRecord::Base.connection.insert(sql)
562 UPDATE current_nodes AS cn, #{db_uqn}
563 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
566 ActiveRecord::Base.connection.update(sql)
568 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
569 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
573 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
574 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
575 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
576 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
581 # ----- makeway(x,y,baselong,basey,masterscale)
582 # returns way made from unwayed segments
585 usertoken,x,y,baselong,basey,masterscale=args
586 uid=getuserid(usertoken)
590 toreverse=[] # segments to reverse
591 nodesused={} # so we don't go over the same node twice
593 # - find start point near x
595 xc=coord2long(x,masterscale,baselong)
596 yc=coord2lat(y,masterscale,basey)
598 RAILS_DEFAULT_LOGGER.info(" Message: makeway, xc=#{xc}, y=#{yc}")
600 xs1=xc-0.001; xs2=xc+0.001
601 ys1=yc-0.001; ys2=yc+0.001
604 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
605 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
606 FROM current_nodes AS cn1,
607 current_nodes AS cn2,
608 current_segments AS cs
609 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
610 WHERE (cn1.longitude BETWEEN #{xs1} AND #{xs2})
611 AND (cn1.latitude BETWEEN #{ys1} AND #{ys2})
612 AND segment_id IS NULL
614 AND cn1.id=node_a AND cn1.visible=1
615 AND cn2.id=node_b AND cn2.visible=1
616 ORDER BY SQRT(POW(cn1.longitude-#{xc},2)+
617 POW(cn1.latitude -#{yc},2))
620 row=ActiveRecord::Base.connection.select_one sql
621 if row.nil? then return [0,0,0,0,0] end
622 xs1=long2coord(row['lon1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
623 xs2=long2coord(row['lon2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
624 xmin=[xs1,xs2].min; xmax=[xs1,xs2].max
625 ymin=[ys1,ys2].min; ymax=[ys1,ys2].max
626 nodesused[row['id1'].to_i]=true
627 nodesused[row['id2'].to_i]=true
628 points<<[xs1,ys1,row['id1'].to_i,1,{},0]
629 points<<[xs2,ys2,row['id2'].to_i,1,{},row['segid'].to_i]
631 # - extend at start, then end
632 while (a,point,nodesused,toreverse=findconnect(points[0][2],nodesused,'b',toreverse,baselong,basey,masterscale))[0]
633 points[0][5]=point[5]; point[5]=0 # segment leads to next node
634 points.unshift(point)
635 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
636 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
638 while (a,point,nodesused,toreverse=findconnect(points[-1][2],nodesused,'a',toreverse,baselong,basey,masterscale))[0]
640 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
641 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
643 points[0][3]=0 # start with a move
645 # reverse segments in toreverse
646 if toreverse.length>0
648 UPDATE current_segments c1, current_segments c2
649 SET c1.node_a=c2.node_b,c1.node_b=c2.node_a,
650 c1.timestamp=NOW(),c1.user_id=#{uid}
652 AND c1.id IN (#{toreverse.join(',')})
654 ActiveRecord::Base.connection.update sql
657 (SELECT * FROM current_segments
658 WHERE id IN (#{toreverse.join(',')}))
660 ActiveRecord::Base.connection.insert sql
663 [points,xmin,xmax,ymin,ymax]
666 def findconnect(id,nodesused,lookfor,toreverse,baselong,basey,masterscale)
667 # get all segments with 'id' as a point
668 # (to look for both node_a and node_b, UNION is faster than node_a=id OR node_b=id)!
670 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
671 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
672 FROM current_nodes AS cn1,
673 current_nodes AS cn2,
674 current_segments AS cs
675 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
676 WHERE segment_id IS NULL
678 AND cn1.id=node_a AND cn1.visible=1
679 AND cn2.id=node_b AND cn2.visible=1
682 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
683 cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
684 FROM current_nodes AS cn1,
685 current_nodes AS cn2,
686 current_segments AS cs
687 LEFT OUTER JOIN current_way_segments ON segment_id=cs.id
688 WHERE segment_id IS NULL
690 AND cn1.id=node_a AND cn1.visible=1
691 AND cn2.id=node_b AND cn2.visible=1
694 connectlist=ActiveRecord::Base.connection.select_all sql
696 if lookfor=='b' then tocol='id1'; tolat='lat1'; tolon='lon1'; fromcol='id2'; fromlat='lat2'; fromlon='lon2'
697 else tocol='id2'; tolat='lat2'; tolon='lon2'; fromcol='id1'; fromlat='lat1'; fromlon='lon1'
700 # eliminate those already in the hash
703 connectlist.each { |row|
704 tonode=row[tocol].to_i
705 fromnode=row[fromcol].to_i
706 if id==tonode and !nodesused.has_key?(fromnode)
707 # wrong way round; add, then add to 'segments to reverse' list
709 nodesused[fromnode]=true
710 point=[long2coord(row[fromlon].to_f,baselong,masterscale),lat2coord(row[fromlat].to_f,basey,masterscale),fromnode,1,{},row['segid'].to_i]
711 toreverse.push(row['segid'].to_i)
712 elsif id==fromnode and !nodesused.has_key?(tonode)
713 # right way round; just add
715 point=[long2coord(row[tolon].to_f,baselong,masterscale),lat2coord(row[tolat].to_f,basey,masterscale),tonode,1,{},row['segid'].to_i]
716 nodesused[tonode]=true
720 # if only one left, then add it; otherwise return false
721 if connex!=1 or point.nil? then
722 return [false,[],nodesused,toreverse]
724 return [true,point,nodesused,toreverse]
729 # ====================================================================
730 # Support functions for remote calls
733 ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
734 " n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
735 " FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
736 " WHERE current_way_segments.id=#{id} "+
737 " AND segment_id=current_segments.id "+
738 " AND current_segments.visible=1 "+
739 " AND n1.id=node_a and n2.id=node_b "+
740 " AND n1.visible=1 AND n2.visible=1 "+
741 " ORDER BY sequence_id"
744 def createuniquesegments(way,uqs_name,seglist)
745 # Finds segments which appear in (previous version of) this way and no other
747 CREATE TEMPORARY TABLE #{uqs_name}
749 FROM (SELECT DISTINCT segment_id FROM current_way_segments
751 LEFT JOIN current_way_segments b
752 ON b.segment_id = a.segment_id
754 WHERE b.segment_id IS NULL
756 if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
757 ActiveRecord::Base.connection.execute(sql)
760 def createuniquenodes(uqs_name,uqn_name)
761 # Finds nodes which appear in uniquesegments but no other segments
763 CREATE TEMPORARY TABLE #{uqn_name}
764 SELECT DISTINCT node_id
765 FROM (SELECT cn.id AS node_id
766 FROM current_nodes AS cn,
767 current_segments AS cs,
769 WHERE cs.id=us.segment_id
770 AND cn.id=cs.node_a) AS n
771 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
772 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
773 WHERE cs2.node_a IS NULL
774 AND cs3.node_b IS NULL
776 ActiveRecord::Base.connection.execute(sql)
778 INSERT INTO #{uqn_name}
779 SELECT DISTINCT node_id
780 FROM (SELECT cn.id AS node_id
781 FROM current_nodes AS cn,
782 current_segments AS cs,
784 WHERE cs.id=us.segment_id
785 AND cn.id=cs.node_b) AS n
786 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
787 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
788 WHERE cs2.node_a IS NULL
789 AND cs3.node_b IS NULL
791 ActiveRecord::Base.connection.execute(sql)
795 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
800 a.gsub(';;;','#%').split(';').each do |b|
804 if k.nil? then k='' end
805 if v.nil? then v='' end
806 tags[k.gsub('#%','=')]=v.gsub('#%','=')
814 if v=='' then next end
815 if v[0,6]=='(type ' then next end
816 if str!='' then str+=';' end
817 str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
823 if (token =~ /^(.+)\+(.+)$/) then
824 user = User.authenticate(:username => $1, :password => $2)
826 user = User.authenticate(:token => token)
829 return user ? user.id : nil;
834 # ====================================================================
835 # AMF read subroutines
837 # ----- getint return two-byte integer
838 # ----- getlong return four-byte long
839 # ----- getstring return string with two-byte length
840 # ----- getdouble return eight-byte double-precision float
841 # ----- getobject return object/hash
842 # ----- getarray return numeric array
849 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
853 len=s.getc*256+s.getc
858 a=s.read(8).unpack('G') # G big-endian, E little-endian
873 while (key=getstring(s))
874 if (key=='') then break end
877 s.getc # skip the 9 'end of object' value
881 # ----- getvalue parse and get value
885 when 0; return getdouble(s) # number
886 when 1; return s.getc # boolean
887 when 2; return getstring(s) # string
888 when 3; return getobject(s) # object/hash
889 when 5; return nil # null
890 when 6; return nil # undefined
891 when 8; s.read(4) # mixedArray
892 return getobject(s) # |
893 when 10; return getarray(s) # array
894 else; return nil # error
898 # ====================================================================
899 # AMF write subroutines
901 # ----- putdata envelope data into AMF writeable form
902 # ----- encodevalue pack variables as AMF
905 d =encodestring(index+"/onResult")
906 d+=encodestring("null")
914 a=10.chr+encodelong(n.length)
922 a+=encodestring(k)+encodevalue(v)
926 2.chr+encodestring(n)
927 when 'Bignum','Fixnum','Float'
928 0.chr+encodedouble(n)
932 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
936 # ----- encodestring encode string with two-byte length
937 # ----- encodedouble encode number as eight-byte double precision float
938 # ----- encodelong encode number as four-byte long
941 a,b=n.size.divmod(256)
953 # ====================================================================
954 # Co-ordinate conversion
956 def lat2coord(a,basey,masterscale)
957 -(lat2y(a)-basey)*masterscale+250
960 def long2coord(a,baselong,masterscale)
961 (a-baselong)*masterscale+350
965 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
968 def coord2lat(a,masterscale,basey)
969 y2lat((a-250)/-masterscale+basey)
972 def coord2long(a,masterscale,baselong)
973 (a-350)/masterscale+baselong
977 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)