Don't create sessions for API calls.
[rails.git] / app / controllers / amf_controller.rb
1 class AmfController < ApplicationController
2   require 'stringio'
3
4   session :off
5   before_filter :check_availability
6
7   # to log:
8   # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
9
10   # ====================================================================
11   # Main AMF handler
12
13   # ---- talk   process AMF request
14
15   def talk
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
19
20     # -------------
21     # Parse request
22
23     headers=getint(req)                                 # Read number of headers
24
25     headers.times do                                # Read each header
26       name=getstring(req)                               #  |
27       req.getc                                  #  | skip boolean
28       value=getvalue(req)                               #  |
29       header["name"]=value                              #  |
30     end
31
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)
38
39       case message
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       end
47     end
48
49     # ------------------
50     # Write out response
51
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
56                 results.each do |k,v|
57                   output.write(v)
58                 end
59         }
60     RAILS_DEFAULT_LOGGER.info("  Response: end")
61
62   end
63
64   private
65
66   # ====================================================================
67   # Remote calls
68
69   # ----- getpresets
70   #           return presets,presetmenus and presetnames arrays
71
72   def getpresets
73     presets={}
74     presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]
75     presetnames={}; presetnames['point']={}; presetnames['way']={}
76     presettype=''
77     presetcategory=''
78
79     RAILS_DEFAULT_LOGGER.info("  Message: getpresets")
80
81     #           File.open("config/potlatch/presets.txt") do |file|
82
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....)
88
89     txt=<<-EOF
90 way/road
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)
97
98 way/footway
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
103
104 way/cycleway
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)
109
110 way/waterway
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)
117
118 way/railway
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
125
126 way/natural
127 forest: natural=wood,landuse=forest
128 woodland: natural=wood,landuse=
129 reservoir: natural=water,landuse=reservoir
130 lake: natural=water,landuse=
131 marsh: natural=marsh
132 beach: natural=beach
133 coastline: natural=coastline
134
135 point/road
136 mini roundabout: highway=mini_roundabout
137 traffic lights: highway=traffic_signals
138
139 point/footway
140 bridge: highway=bridge
141 gate: highway=gate
142 stile: highway=stile
143 cattle grid: highway=cattle_grid
144
145 point/cycleway
146 gate: highway=gate
147
148 point/waterway
149 lock gate: waterway=lock_gate
150 weir: waterway=weir
151 aqueduct: waterway=aqueduct
152 winding hole: waterway=turning_point
153 mooring: waterway=mooring
154
155 point/railway
156 station: railway=station
157 viaduct: railway=viaduct
158 level crossing: railway=crossing
159
160 point/natural
161 peak: natural=peak
162 EOF
163
164     StringIO.open(txt) do |file|
165       file.each_line {|line|
166         t=line.chomp
167         if (t=~/(\w+)\/(\w+)/) then
168           presettype=$1
169           presetcategory=$2
170           presetmenus[presettype].push(presetcategory)
171           presetnames[presettype][presetcategory]=["(no preset)"]
172         elsif (t=~/^(.+):\s?(.+)$/) then
173           pre=$1; kv=$2
174           presetnames[presettype][presetcategory].push(pre)
175           presets[pre]={}
176           kv.split(',').each {|a|
177             if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
178           }
179         end
180       }
181     end
182     return [presets,presetmenus,presetnames]
183   end
184
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
189
190   def whichways(args)
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
195
196     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
197
198     waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
199        "  FROM current_way_segments,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_segments.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+")")
207
208        ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
209
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")
218
219             points = pointlist.collect {|a| [a['id'],tag2array(a['tags'])]      } # get a list of node ids and their tags
220
221     return [ways,points]
222   end
223
224   # ----- getway (objectname, way, baselong, basey, masterscale)
225   #               returns objectname, array of co-ordinates, attributes,
226   #                               xmin,xmax,ymin,ymax
227
228   def getway(args)
229     objname,wayid,baselong,basey,masterscale=args
230     wayid = wayid.to_i
231     points = []
232     lastid = -1
233     xmin = ymin = 999999
234     xmax = ymax = -999999
235
236     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
237
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
248     }
249
250     attributes={}
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'] }
253
254     [objname,points,attributes,xmin,xmax,ymin,ymax]
255   end
256
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
261
262   def putway(args)
263     usertoken,originalway,points,attributes,baselong,basey,masterscale=args
264     uid=getuserid(usertoken)
265     return if !uid
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
271
272     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
273
274     # -- 3.     read original way into memory
275
276     xc={}; yc={}; tagc={}; seg={}
277     if originalway>0
278       way=originalway
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
283       }
284           ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
285     else
286       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
287     end
288
289     # -- 4.     get version by inserting new row into ways
290
291     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
292
293     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
294
295     xmin = ymin = 999999
296     xmax = ymax = -999999
297     insertsql = ''
298     renumberednodes={}
299
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)+"'"
309
310       # compare node
311       if node<0
312         # new node - create
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})")
316                         points[i][2]=newnode
317                         renumberednodes[node.to_s]=newnode.to_s
318                 else
319                         points[i][2]=renumberednodes[node.to_s].to_i
320                 end
321
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}")
327         end
328       else
329         # old node, created in another way and now added to this way
330       end
331
332     end
333
334
335     # -- 6.i compare segments
336
337     numberedsegments={}
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
348           next
349         end
350           elsif segid>0
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
354                 next
355       end
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,'')")
358       points[i+1][5]=segid
359       numberedsegments[(i+1).to_s]=segid.to_s
360     end
361
362
363     # -- 6.ii insert new way segments
364
365     createuniquesegments(way,db_uqs,seglist)    # segments which appear in this way but no other
366
367     #           delete segments from uniquesegments (and not in modified way)
368
369     sql=<<-EOF
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 
374     EOF
375     ActiveRecord::Base.connection.insert(sql)
376
377     sql=<<-EOF
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 
381     EOF
382     ActiveRecord::Base.connection.update(sql)
383
384     #           delete nodes not in modified way or any other segments
385
386     createuniquenodes(db_uqs,db_uqn)    # nodes which appear in this way but no other
387
388     sql=<<-EOF
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}
392                  WHERE cn.id=node_id
393     EOF
394     ActiveRecord::Base.connection.insert(sql)
395
396     sql=<<-EOF
397       UPDATE current_nodes AS cn, #{db_uqn}
398          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
399        WHERE cn.id=node_id
400     EOF
401     ActiveRecord::Base.connection.update(sql)
402
403     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
404     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
405
406     #           insert new version of route into way_segments
407
408     insertsql =''
409     currentsql=''
410     sequence  =1
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})"
417       sequence  +=1
418     end
419
420     ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
421     ActiveRecord::Base.connection.insert("INSERT INTO         way_segments (id,segment_id,version    ) VALUES #{insertsql}");
422     ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
423
424     # -- 7. insert new way tags
425
426     insertsql =''
427     currentsql=''
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)+"')"
437     end
438
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
442
443     [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
444   end
445
446   # -----       deleteway (user token, way)
447   #                     returns way ID only
448
449   def deleteway(args)
450     usertoken,way=args
451
452     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
453
454     uid=getuserid(usertoken); if !uid then return end
455         way=way.to_i
456
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,'')
462
463         # -     delete any otherwise unused segments
464
465         sql=<<-EOF
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
470     EOF
471         ActiveRecord::Base.connection.insert(sql)
472
473         sql=<<-EOF
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
477     EOF
478         ActiveRecord::Base.connection.update(sql)
479
480         # - delete any unused nodes
481   
482     createuniquenodes(db_uqs,db_uqn)
483
484         sql=<<-EOF
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}
488                  WHERE cn.id=node_id
489     EOF
490         ActiveRecord::Base.connection.insert(sql)
491
492         sql=<<-EOF
493       UPDATE current_nodes AS cn, #{db_uqn}
494          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
495        WHERE cn.id=node_id
496     EOF
497         ActiveRecord::Base.connection.update(sql)
498         
499         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
500         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
501
502         # - delete way
503         
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_segments WHERE id=#{way}")
507         ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
508         
509         way
510 end
511
512 # ----- makeway(x,y,baselong,basey,masterscale)
513 #               returns way made from unwayed segments
514
515 def makeway(args)
516         usertoken,x,y,baselong,basey,masterscale=args
517     uid=getuserid(usertoken)
518     return if !uid
519
520         points=[]
521         toreverse=[]                            # segments to reverse
522         nodesused={}                            # so we don't go over the same node twice
523
524         # - find start point near x
525         
526         xc=coord2long(x,masterscale,baselong)
527         yc=coord2lat(y,masterscale,basey)
528
529         RAILS_DEFAULT_LOGGER.info("  Message: makeway, xc=#{xc}, y=#{yc}")
530
531         xs1=xc-0.001; xs2=xc+0.001
532         ys1=yc-0.001; ys2=yc+0.001
533         
534         sql=<<-EOF
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_segments 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 
544                    AND cs.visible=1
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)) 
549          LIMIT 1
550         EOF
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]
561         
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
568         end
569         while (a,point,nodesused,toreverse=findconnect(points[-1][2],nodesused,'a',toreverse,baselong,basey,masterscale))[0]
570                 points.push(point)
571                 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
572                 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
573         end
574         points[0][3]=0  # start with a move
575
576         # reverse segments in toreverse
577         if toreverse.length>0
578                 sql=<<-EOF
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} 
582                          WHERE c1.id=c2.id 
583                            AND c1.id IN (#{toreverse.join(',')})
584                 EOF
585                 ActiveRecord::Base.connection.update sql
586                 sql=<<-EOF
587                         INSERT INTO segments 
588                    (SELECT * FROM current_segments 
589                      WHERE id IN (#{toreverse.join(',')}))
590                 EOF
591                 ActiveRecord::Base.connection.insert sql
592         end
593
594         [points,xmin,xmax,ymin,ymax]
595 end
596
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)!
600         sql=<<-EOF
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_segments ON segment_id=cs.id 
607                  WHERE segment_id IS NULL 
608                    AND cs.visible=1
609                    AND cn1.id=node_a AND cn1.visible=1 
610                    AND cn2.id=node_b AND cn2.visible=1 
611                    AND node_a=#{id}
612         UNION
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_segments ON segment_id=cs.id 
619                  WHERE segment_id IS NULL 
620                    AND cs.visible=1
621                    AND cn1.id=node_a AND cn1.visible=1 
622                    AND cn2.id=node_b AND cn2.visible=1 
623                    AND node_b=#{id}
624         EOF
625         connectlist=ActiveRecord::Base.connection.select_all sql
626         
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'
629         end
630         
631         # eliminate those already in the hash
632         connex=0
633         point=nil
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
639                         connex+=1
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
645                         connex+=1
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
648                 end
649         }
650         
651         # if only one left, then add it; otherwise return false
652         if connex!=1 or point.nil? then
653                 return [false,[],nodesused,toreverse]
654         else
655                 return [true,point,nodesused,toreverse]
656         end
657 end
658
659
660 # ====================================================================
661 # Support functions for remote calls
662
663 def readwayquery(id)
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_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
667       "   WHERE current_way_segments.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"
673 end
674
675 def createuniquesegments(way,uqs_name,seglist)
676   # Finds segments which appear in (previous version of) this way and no other
677   sql=<<-EOF
678       CREATE TEMPORARY TABLE #{uqs_name}
679               SELECT a.segment_id
680                 FROM (SELECT DISTINCT segment_id FROM current_way_segments 
681                   WHERE id = #{way}) a
682              LEFT JOIN current_way_segments b 
683                 ON b.segment_id = a.segment_id
684                  AND b.id != #{way}
685                WHERE b.segment_id IS NULL
686     EOF
687   if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
688   ActiveRecord::Base.connection.execute(sql)
689 end
690
691 def createuniquenodes(uqs_name,uqn_name)
692         # Finds nodes which appear in uniquesegments but no other segments
693         sql=<<-EOF
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,
699                                                        #{uqs_name} AS us
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
706         EOF
707         ActiveRecord::Base.connection.execute(sql)
708 end
709
710 def sqlescape(a)
711   a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
712 end
713
714 def tag2array(a)
715   tags={}
716   a.gsub(';;;','#%').split(';').each do |b|
717     b.gsub!('#%',';;;')
718     b.gsub!('===','#%')
719     k,v=b.split('=')
720     if k.nil? then k='' end
721     if v.nil? then v='' end
722     tags[k.gsub('#%','=')]=v.gsub('#%','=')
723   end
724   tags
725 end
726
727 def array2tag(a)
728   str=''
729   a.each do |k,v|
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('=','===')
734   end
735   str
736 end
737
738 def getuserid(token)
739   token=sqlescape(token)
740   if (token=~/^(.+)\+(.+)$/) then
741     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
742   else
743     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND token='#{token}'")
744   end
745 end
746
747
748
749 # ====================================================================
750 # AMF read subroutines
751
752 # ----- getint          return two-byte integer
753 # ----- getlong         return four-byte long
754 # ----- getstring       return string with two-byte length
755 # ----- getdouble       return eight-byte double-precision float
756 # ----- getobject       return object/hash
757 # ----- getarray        return numeric array
758
759 def getint(s)
760   s.getc*256+s.getc
761 end
762
763 def getlong(s)
764   ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
765 end
766
767 def getstring(s)
768   len=s.getc*256+s.getc
769   s.read(len)
770 end
771
772 def getdouble(s)
773   a=s.read(8).unpack('G')                       # G big-endian, E little-endian
774   a[0]
775 end
776
777 def getarray(s)
778   len=getlong(s)
779   arr=[]
780   for i in (0..len-1)
781     arr[i]=getvalue(s)
782   end
783   arr
784 end
785
786 def getobject(s)
787   arr={}
788   while (key=getstring(s))
789     if (key=='') then break end
790     arr[key]=getvalue(s)
791   end
792   s.getc                # skip the 9 'end of object' value
793   arr
794 end
795
796 # ----- getvalue        parse and get value
797
798 def getvalue(s)
799   case s.getc
800   when 0;       return getdouble(s)                     # number
801   when 1;       return s.getc                           # boolean
802   when 2;       return getstring(s)                     # string
803   when 3;       return getobject(s)                     # object/hash
804   when 5;       return nil                                      # null
805   when 6;       return nil                                      # undefined
806   when 8;       s.read(4)                                       # mixedArray
807                     return getobject(s)                 #  |
808   when 10;      return getarray(s)                      # array
809   else;         return nil                                      # error
810   end
811 end
812
813 # ====================================================================
814 # AMF write subroutines
815
816 # ----- putdata         envelope data into AMF writeable form
817 # ----- encodevalue     pack variables as AMF
818
819 def putdata(index,n)
820   d =encodestring(index+"/onResult")
821   d+=encodestring("null")
822   d+=[-1].pack("N")
823   d+=encodevalue(n)
824 end
825
826 def encodevalue(n)
827   case n.class.to_s
828   when 'Array'
829     a=10.chr+encodelong(n.length)
830     n.each do |b|
831       a+=encodevalue(b)
832     end
833     a
834   when 'Hash'
835     a=3.chr
836     n.each do |k,v|
837       a+=encodestring(k)+encodevalue(v)
838     end
839     a+0.chr+0.chr+9.chr
840   when 'String'
841     2.chr+encodestring(n)
842   when 'Bignum','Fixnum','Float'
843     0.chr+encodedouble(n)
844   when 'NilClass'
845     5.chr
846   else
847     RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
848   end
849 end
850
851 # ----- encodestring    encode string with two-byte length
852 # ----- encodedouble    encode number as eight-byte double precision float
853 # ----- encodelong              encode number as four-byte long
854
855 def encodestring(n)
856   a,b=n.size.divmod(256)
857   a.chr+b.chr+n
858 end
859
860 def encodedouble(n)
861   [n].pack('G')
862 end
863
864 def encodelong(n)
865   [n].pack('N')
866 end
867
868 # ====================================================================
869 # Co-ordinate conversion
870
871 def lat2coord(a,basey,masterscale)
872   -(lat2y(a)-basey)*masterscale+250
873 end
874
875 def long2coord(a,baselong,masterscale)
876   (a-baselong)*masterscale+350
877 end
878
879 def lat2y(a)
880   180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
881 end
882
883 def coord2lat(a,masterscale,basey)
884   y2lat((a-250)/-masterscale+basey)
885 end
886
887 def coord2long(a,masterscale,baselong)
888   (a-350)/masterscale+baselong
889 end
890
891 def y2lat(a)
892   180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
893 end
894
895 end