ways from unwayed segments now automatically fix segment direction
[rails.git] / app / controllers / amf_controller.rb
1 class AmfController < ApplicationController
2   require 'stringio'
3
4   # to log:
5   # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
6
7   # ====================================================================
8   # Main AMF handler
9
10   # ---- talk   process AMF request
11
12   def talk
13     req=StringIO.new(request.raw_post)  # Get POST data as request
14     req.read(2)                                                 # Skip version indicator and client ID
15     results={}                                                  # Results of each body
16
17     # -------------
18     # Parse request
19
20     headers=getint(req)                                 # Read number of headers
21
22     headers.times do                                # Read each header
23       name=getstring(req)                               #  |
24       req.getc                                  #  | skip boolean
25       value=getvalue(req)                               #  |
26       header["name"]=value                              #  |
27     end
28
29     bodies=getint(req)                                  # Read number of bodies
30     bodies.times do                                     # Read each body
31       message=getstring(req)                    #  | get message name
32       index=getstring(req)                              #  | get index in response sequence
33       bytes=getlong(req)                                #  | get total size in bytes
34       args=getvalue(req)                                #  | get response (probably an array)
35
36       case message
37                   when 'getpresets';    results[index]=putdata(index,getpresets)
38                   when 'whichways';             results[index]=putdata(index,whichways(args))
39                   when 'getway';                results[index]=putdata(index,getway(args))
40                   when 'putway';                results[index]=putdata(index,putway(args))
41                   when 'deleteway';             results[index]=putdata(index,deleteway(args))
42                   when 'makeway';               results[index]=putdata(index,makeway(args))
43       end
44     end
45
46     # ------------------
47     # Write out response
48
49     RAILS_DEFAULT_LOGGER.info("  Response: start")
50     a,b=results.length.divmod(256)
51         render :content_type => "application/x-amf", :text => proc { |response, output| 
52         output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
53                 results.each do |k,v|
54                   output.write(v)
55                 end
56         }
57     RAILS_DEFAULT_LOGGER.info("  Response: end")
58
59   end
60
61   private
62
63   # ====================================================================
64   # Remote calls
65
66   # ----- getpresets
67   #           return presets,presetmenus and presetnames arrays
68
69   def getpresets
70     presets={}
71     presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]
72     presetnames={}; presetnames['point']={}; presetnames['way']={}
73     presettype=''
74     presetcategory=''
75
76     RAILS_DEFAULT_LOGGER.info("  Message: getpresets")
77
78     #           File.open("config/potlatch/presets.txt") do |file|
79
80     # Temporary patch to get around filepath problem
81     # To remove this patch and make the code nice again:
82     # 1. uncomment above line
83     # 2. fix the path in the above line
84     # 3. delete this here document, and the following line (StringIO....)
85
86     txt=<<-EOF
87 way/road
88 motorway: highway=motorway,ref=(type road number)
89 trunk road: highway=trunk,ref=(type road number),name=(type road name)
90 primary road: highway=primary,ref=(type road number),name=(type road name)
91 secondary road: highway=secondary,ref=(type road number),name=(type road name)
92 residential road: highway=residential,name=(type road name)
93 unclassified road: highway=unclassified,name=(type road name)
94
95 way/footway
96 footpath: highway=footway,foot=yes
97 bridleway: highway=bridleway,foot=yes,horse=yes,bicycle=yes
98 byway: highway=byway,foot=yes,horse=yes,bicycle=yes,motorcar=yes
99 permissive path: highway=footway,foot=permissive
100
101 way/cycleway
102 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
103 cycle track: highway=cycleway,cycleway=track,ncn_ref=
104 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
105 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
106
107 way/waterway
108 canal: waterway=canal,name=(type name here)
109 navigable river: waterway=river,boat=yes,name=(type name here)
110 navigable drain: waterway=drain,boat=yes,name=(type name here)
111 derelict canal: waterway=derelict_canal,name=(type name here)
112 unnavigable river: waterway=river,boat=no,name=(type name here)
113 unnavigable drain: waterway=drain,boat=no,name=(type name here)
114
115 way/railway
116 railway: railway=rail
117 tramway: railway=tram
118 light railway: railway=light_rail
119 preserved railway: railway=preserved
120 disused railway tracks: railway=disused
121 course of old railway: railway=abandoned
122
123 point/road
124 mini roundabout: highway=mini_roundabout
125 traffic lights: highway=traffic_signals
126
127 point/footway
128 bridge: highway=bridge
129 gate: highway=gate
130 stile: highway=stile
131 cattle grid: highway=cattle_grid
132
133 point/cycleway
134 gate: highway=gate
135
136 point/waterway
137 lock gate: waterway=lock_gate
138 weir: waterway=weir
139 aqueduct: waterway=aqueduct
140 winding hole: waterway=turning_point
141 mooring: waterway=mooring
142
143 point/railway
144 station: railway=station
145 viaduct: railway=viaduct
146 level crossing: railway=crossing
147 EOF
148
149     StringIO.open(txt) do |file|
150       file.each_line {|line|
151         t=line.chomp
152         if (t=~/(\w+)\/(\w+)/) then
153           presettype=$1
154           presetcategory=$2
155           presetmenus[presettype].push(presetcategory)
156           presetnames[presettype][presetcategory]=["(no preset)"]
157         elsif (t=~/^(.+):\s?(.+)$/) then
158           pre=$1; kv=$2
159           presetnames[presettype][presetcategory].push(pre)
160           presets[pre]={}
161           kv.split(',').each {|a|
162             if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
163           }
164         end
165       }
166     end
167     return [presets,presetmenus,presetnames]
168   end
169
170   # ----- whichways(left,bottom,right,top)
171   #               return array of ways in current bounding box
172   #               at present, instead of using correct (=more complex) SQL to find
173   #               corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
174
175   def whichways(args)
176     xmin = args[0].to_f-0.01
177     ymin = args[1].to_f-0.01
178     xmax = args[2].to_f+0.01
179     ymax = args[3].to_f+0.01
180
181     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
182
183     waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
184        "  FROM current_way_segments,current_segments,current_nodes,current_ways "+
185        " WHERE segment_id=current_segments.id "+
186        "   AND current_segments.visible=1 "+
187        "   AND node_a=current_nodes.id "+
188            "   AND current_ways.id=current_way_segments.id "+
189            "   AND current_ways.visible=1 "+
190        "   AND (latitude  BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
191        "   AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+")")
192
193        ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
194
195        pointlist =ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.tags "+
196        "  FROM current_nodes "+
197        "  LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
198        "  LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
199        " WHERE (latitude  BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
200        "   AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+") "+
201        "   AND cs1.id IS NULL AND cs2.id IS NULL "+
202        "   AND current_nodes.visible=1")
203
204             points = pointlist.collect {|a| [a['id'],tag2array(a['tags'])]      } # get a list of node ids and their tags
205
206     return [ways,points]
207   end
208
209   # ----- getway (objectname, way, baselong, basey, masterscale)
210   #               returns objectname, array of co-ordinates, attributes,
211   #                               xmin,xmax,ymin,ymax
212
213   def getway(args)
214     objname,wayid,baselong,basey,masterscale=args
215     wayid = wayid.to_i
216     points = []
217     lastid = -1
218     xmin = ymin = 999999
219     xmax = ymax = -999999
220
221     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
222
223     readwayquery(wayid).each {|row|
224       xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
225       xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
226       points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
227       lastid = row['id2'].to_i
228       points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
229       xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
230       xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
231       ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
232       ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
233     }
234
235     attributes={}
236     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
237     attrlist.each {|a| attributes[a['k']]=a['v'] }
238
239     [objname,points,attributes,xmin,xmax,ymin,ymax]
240   end
241
242   # -----       putway (user token, way, array of co-ordinates, array of attributes,
243   #                                     baselong, basey, masterscale)
244   #                     returns current way ID, new way ID, hash of renumbered nodes,
245   #                                     xmin,xmax,ymin,ymax
246
247   def putway(args)
248     usertoken,originalway,points,attributes,baselong,basey,masterscale=args
249     uid=getuserid(usertoken)
250     return if !uid
251     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
252     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
253     db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
254     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
255     originalway=originalway.to_i
256
257     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
258
259     # -- 3.     read original way into memory
260
261     xc={}; yc={}; tagc={}; seg={}
262     if originalway>0
263       way=originalway
264       readwayquery(way).each { |row|
265         id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
266         id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
267         seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
268       }
269           ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
270     else
271       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
272     end
273
274     # -- 4.     get version by inserting new row into ways
275
276     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
277
278     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
279
280     xmin = ymin = 999999
281     xmax = ymax = -999999
282     insertsql = ''
283     renumberednodes={}
284
285     points.each_index do |i|
286       xs=coord2long(points[i][0],masterscale,baselong)
287       ys=coord2lat(points[i][1],masterscale,basey)
288       xmin=[xs,xmin].min; xmax=[xs,xmax].max
289       ymin=[ys,ymin].min; ymax=[ys,ymax].max
290       node=points[i][2].to_i
291       tagstr=array2tag(points[i][4])
292           tagstr=tagstr.gsub(/[\000-\037]/,"")
293       tagsql="'"+sqlescape(tagstr)+"'"
294
295       # compare node
296       if node<0
297         # new node - create
298         newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (   latitude,longitude,timestamp,user_id,visible,tags) VALUES (           #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
299                         ActiveRecord::Base.connection.insert("INSERT INTO nodes         (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
300         points[i][2]=newnode
301         renumberednodes[node.to_s]=newnode.to_s
302
303       elsif xc.has_key?(node)
304         # old node from original way - update
305         if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
306           ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
307           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}")
308         end
309       else
310         # old node, created in another way and now added to this way
311       end
312
313     end
314
315
316     # -- 6.i compare segments
317
318     numberedsegments={}
319     seglist=''                          # list of existing segments that we want to keep
320     for i in (0..(points.length-2))
321       if (points[i+1][3].to_i==0) then next end
322       segid=points[i+1][5].to_i
323       from =points[i  ][2].to_i
324       to   =points[i+1][2].to_i
325       if seg.has_key?(segid)
326                 # if segment exists, check it still refers to the same nodes
327         if seg[segid]=="#{from}-#{to}" then 
328           if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
329           next
330         end
331           elsif segid>0
332                 # not in previous version of way, but supplied, so assume
333                 # that it's come from makeway (i.e. unwayed segments)
334                 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
335                 next
336       end
337       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,'')")
338                 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,'')")
339       points[i+1][5]=segid
340       numberedsegments[(i+1).to_s]=segid.to_s
341     end
342
343
344     # -- 6.ii insert new way segments
345
346     createuniquesegments(way,db_uqs,seglist)    # segments which appear in this way but no other
347
348     #           delete segments from uniquesegments (and not in modified way)
349
350     sql=<<-EOF
351       INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
352       SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
353         FROM current_segments AS cs, #{db_uqs} AS us
354        WHERE cs.id=us.segment_id AND cs.visible=1 
355     EOF
356     ActiveRecord::Base.connection.insert(sql)
357
358     sql=<<-EOF
359          UPDATE current_segments AS cs, #{db_uqs} AS us
360           SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
361         WHERE cs.id=us.segment_id AND cs.visible=1 
362     EOF
363     ActiveRecord::Base.connection.update(sql)
364
365     #           delete nodes not in modified way or any other segments
366
367     createuniquenodes(db_uqs,db_uqn)    # nodes which appear in this way but no other
368
369     sql=<<-EOF
370                 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)  
371                 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
372                   FROM current_nodes AS cn,#{db_uqn}
373                  WHERE cn.id=node_id
374     EOF
375     ActiveRecord::Base.connection.insert(sql)
376
377     sql=<<-EOF
378       UPDATE current_nodes AS cn, #{db_uqn}
379          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
380        WHERE cn.id=node_id
381     EOF
382     ActiveRecord::Base.connection.update(sql)
383
384     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
385     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
386
387     #           insert new version of route into way_segments
388
389     insertsql =''
390     currentsql=''
391     sequence  =1
392     for i in (0..(points.length-2))
393       if (points[i+1][3].to_i==0) then next end
394       if insertsql !='' then insertsql +=',' end
395       if currentsql!='' then currentsql+=',' end
396       insertsql +="(#{way},#{points[i+1][5]},#{version})"
397       currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
398       sequence  +=1
399     end
400
401     ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
402     ActiveRecord::Base.connection.insert("INSERT INTO         way_segments (id,segment_id,version    ) VALUES #{insertsql}");
403     ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
404
405     # -- 7. insert new way tags
406
407     insertsql =''
408     currentsql=''
409     attributes.each do |k,v|
410       if v=='' or v.nil? then next end
411       if v[0,6]=='(type ' then next end
412       if insertsql !='' then insertsql +=',' end
413       if currentsql!='' then currentsql+=',' end
414           k=k.gsub(/[\000-\037]/,"")
415           v=v.gsub(/[\000-\037]/,"")
416       insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',#{version})"
417       currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
418     end
419
420     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
421     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
422     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
423
424     [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
425   end
426
427   # -----       deleteway (user token, way)
428   #                     returns way ID only
429
430   def deleteway(args)
431     usertoken,way=args
432
433     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
434
435     uid=getuserid(usertoken); if !uid then return end
436         way=way.to_i
437
438         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
439         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
440         db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
441         ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
442         createuniquesegments(way,db_uqs,'')
443
444         # -     delete any otherwise unused segments
445
446         sql=<<-EOF
447       INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
448       SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0 
449         FROM current_segments AS cs, #{db_uqs} AS us
450        WHERE cs.id=us.segment_id
451     EOF
452         ActiveRecord::Base.connection.insert(sql)
453
454         sql=<<-EOF
455       UPDATE current_segments AS cs, #{db_uqs} AS us
456          SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
457        WHERE cs.id=us.segment_id
458     EOF
459         ActiveRecord::Base.connection.update(sql)
460
461         # - delete any unused nodes
462   
463     createuniquenodes(db_uqs,db_uqn)
464
465         sql=<<-EOF
466                 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)  
467                 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
468                   FROM current_nodes AS cn,#{db_uqn}
469                  WHERE cn.id=node_id
470     EOF
471         ActiveRecord::Base.connection.insert(sql)
472
473         sql=<<-EOF
474       UPDATE current_nodes AS cn, #{db_uqn}
475          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
476        WHERE cn.id=node_id
477     EOF
478         ActiveRecord::Base.connection.update(sql)
479         
480         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
481         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
482
483         # - delete way
484         
485         ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
486         ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
487         ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
488         ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
489         
490         way
491 end
492
493 # ----- makeway(x,y,baselong,basey,masterscale)
494 #               returns way made from unwayed segments
495
496 def makeway(args)
497         usertoken,x,y,baselong,basey,masterscale=args
498     uid=getuserid(usertoken)
499     return if !uid
500
501         points=[]
502         toreverse=[]                            # segments to reverse
503         nodesused={}                            # so we don't go over the same node twice
504
505         # - find start point near x
506         
507         xc=coord2long(x,masterscale,baselong)
508         yc=coord2lat(y,masterscale,basey)
509
510         RAILS_DEFAULT_LOGGER.info("  Message: makeway, xc=#{xc}, y=#{yc}")
511
512         xs1=xc-0.001; xs2=xc+0.001
513         ys1=yc-0.001; ys2=yc+0.001
514         
515         sql=<<-EOF
516                 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
517                        cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
518                   FROM current_nodes AS cn1,
519                        current_nodes AS cn2,
520                        current_segments AS cs 
521                        LEFT OUTER JOIN current_way_segments ON segment_id=cs.id 
522                  WHERE (cn1.longitude BETWEEN #{xs1} AND #{xs2}) 
523                    AND (cn1.latitude  BETWEEN #{ys1} AND #{ys2}) 
524                    AND segment_id IS NULL 
525                    AND cs.visible=1
526                    AND cn1.id=node_a AND cn1.visible=1 
527                    AND cn2.id=node_b AND cn2.visible=1 
528               ORDER BY SQRT(POW(cn1.longitude-#{xc},2)+
529                                 POW(cn1.latitude -#{yc},2)) 
530          LIMIT 1
531         EOF
532         row=ActiveRecord::Base.connection.select_one sql
533         if row.nil? then return [0,0,0,0,0] end
534         xs1=long2coord(row['lon1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
535         xs2=long2coord(row['lon2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
536         xmin=[xs1,xs2].min; xmax=[xs1,xs2].max
537         ymin=[ys1,ys2].min; ymax=[ys1,ys2].max
538         nodesused[row['id1'].to_i]=true
539         nodesused[row['id2'].to_i]=true
540         points<<[xs1,ys1,row['id1'].to_i,1,{},0]
541         points<<[xs2,ys2,row['id2'].to_i,1,{},row['segid'].to_i]
542         
543         # - extend at start, then end
544         while (a,point,nodesused,toreverse=findconnect(points[0][2],nodesused,'b',toreverse,baselong,basey,masterscale))[0]
545                 points[0][5]=point[5]; point[5]=0       # segment leads to next node
546                 points.unshift(point)
547                 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
548                 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
549         end
550         while (a,point,nodesused,toreverse=findconnect(points[-1][2],nodesused,'a',toreverse,baselong,basey,masterscale))[0]
551                 points.push(point)
552                 xmin=[point[0],xmin].min; xmax=[point[0],xmax].max
553                 ymin=[point[1],ymin].min; ymax=[point[1],ymax].max
554         end
555         points[0][3]=0  # start with a move
556
557         # reverse segments in toreverse
558         if toreverse.length>0
559                 sql=<<-EOF
560                         UPDATE current_segments c1, current_segments c2 
561                            SET c1.node_a=c2.node_b,c1.node_b=c2.node_a,
562                                c1.timestamp=NOW(),c1.user_id=#{uid} 
563                          WHERE c1.id=c2.id 
564                            AND c1.id IN (#{toreverse.join(',')})
565                 EOF
566                 ActiveRecord::Base.connection.update sql
567                 sql=<<-EOF
568                         INSERT INTO segments 
569                    (SELECT * FROM current_segments 
570                      WHERE id IN (#{toreverse.join(',')}))
571                 EOF
572                 ActiveRecord::Base.connection.insert sql
573         end
574
575         [points,xmin,xmax,ymin,ymax]
576 end
577
578 def findconnect(id,nodesused,lookfor,toreverse,baselong,basey,masterscale)
579         # get all segments with 'id' as a point
580         # (to look for both node_a and node_b, UNION is faster than node_a=id OR node_b=id)!
581         sql=<<-EOF
582                 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
583                        cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
584                   FROM current_nodes AS cn1,
585                        current_nodes AS cn2,
586                        current_segments AS cs 
587                        LEFT OUTER JOIN current_way_segments ON segment_id=cs.id 
588                  WHERE segment_id IS NULL 
589                    AND cs.visible=1
590                    AND cn1.id=node_a AND cn1.visible=1 
591                    AND cn2.id=node_b AND cn2.visible=1 
592                    AND node_a=#{id}
593         UNION
594                 SELECT cn1.latitude AS lat1,cn1.longitude AS lon1,cn1.id AS id1,
595                        cn2.latitude AS lat2,cn2.longitude AS lon2,cn2.id AS id2, cs.id AS segid
596                   FROM current_nodes AS cn1,
597                        current_nodes AS cn2,
598                        current_segments AS cs 
599                        LEFT OUTER JOIN current_way_segments ON segment_id=cs.id 
600                  WHERE segment_id IS NULL 
601                    AND cs.visible=1
602                    AND cn1.id=node_a AND cn1.visible=1 
603                    AND cn2.id=node_b AND cn2.visible=1 
604                    AND node_b=#{id}
605         EOF
606         connectlist=ActiveRecord::Base.connection.select_all sql
607         
608         if lookfor=='b' then tocol='id1'; tolat='lat1'; tolon='lon1'; fromcol='id2'; fromlat='lat2'; fromlon='lon2'
609                                         else tocol='id2'; tolat='lat2'; tolon='lon2'; fromcol='id1'; fromlat='lat1'; fromlon='lon1'
610         end
611         
612         # eliminate those already in the hash
613         connex=0
614         point=nil
615         connectlist.each { |row|
616                 tonode=row[tocol].to_i
617                 fromnode=row[fromcol].to_i
618                 if id==tonode and !nodesused.has_key?(fromnode)
619                         # wrong way round; add, then add to 'segments to reverse' list
620                         connex+=1
621                         nodesused[fromnode]=true
622                         point=[long2coord(row[fromlon].to_f,baselong,masterscale),lat2coord(row[fromlat].to_f,basey,masterscale),fromnode,1,{},row['segid'].to_i]
623                         toreverse.push(row['segid'].to_i)
624                 elsif id==fromnode and !nodesused.has_key?(tonode)
625                         # right way round; just add
626                         connex+=1
627                         point=[long2coord(row[tolon].to_f,baselong,masterscale),lat2coord(row[tolat].to_f,basey,masterscale),tonode,1,{},row['segid'].to_i]
628                         nodesused[tonode]=true
629                 end
630         }
631         
632         # if only one left, then add it; otherwise return false
633         if connex!=1 or point.nil? then
634                 return [false,[],nodesused,toreverse]
635         else
636                 return [true,point,nodesused,toreverse]
637         end
638 end
639
640
641 # ====================================================================
642 # Support functions for remote calls
643
644 def readwayquery(id)
645   ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
646       "           n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
647       "    FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
648       "   WHERE current_way_segments.id=#{id} "+
649       "     AND segment_id=current_segments.id "+
650           "     AND current_segments.visible=1 "+
651       "     AND n1.id=node_a and n2.id=node_b "+
652       "     AND n1.visible=1 AND n2.visible=1 "+
653       "   ORDER BY sequence_id"
654 end
655
656 def createuniquesegments(way,uqs_name,seglist)
657   # Finds segments which appear in (previous version of) this way and no other
658   sql=<<-EOF
659       CREATE TEMPORARY TABLE #{uqs_name}
660               SELECT a.segment_id
661                 FROM (SELECT DISTINCT segment_id FROM current_way_segments 
662                   WHERE id = #{way}) a
663              LEFT JOIN current_way_segments b 
664                 ON b.segment_id = a.segment_id
665                  AND b.id != #{way}
666                WHERE b.segment_id IS NULL
667     EOF
668   if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
669   ActiveRecord::Base.connection.execute(sql)
670 end
671
672 def createuniquenodes(uqs_name,uqn_name)
673         # Finds nodes which appear in uniquesegments but no other segments
674         sql=<<-EOF
675                 CREATE TEMPORARY TABLE #{uqn_name}
676                            SELECT DISTINCT node_id
677                               FROM (SELECT cn.id AS node_id
678                                                   FROM current_nodes AS cn,
679                                                        current_segments AS cs,
680                                                        #{uqs_name} AS us
681                                                  WHERE cs.id=us.segment_id
682                                                    AND (cn.id=cs.node_a OR cn.id=cs.node_b)) AS n
683                                          LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
684                                          LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
685                                              WHERE cs2.node_a IS NULL
686                                                AND cs3.node_b IS NULL
687         EOF
688         ActiveRecord::Base.connection.execute(sql)
689 end
690
691 def sqlescape(a)
692   a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
693 end
694
695 def tag2array(a)
696   tags={}
697   a.gsub(';;;','#%').split(';').each do |b|
698     b.gsub!('#%',';;;')
699     b.gsub!('===','#%')
700     k,v=b.split('=')
701     if k.nil? then k='' end
702     if v.nil? then v='' end
703     tags[k.gsub('#%','=')]=v.gsub('#%','=')
704   end
705   tags
706 end
707
708 def array2tag(a)
709   str=''
710   a.each do |k,v|
711     if v=='' then next end
712     if v[0,6]=='(type ' then next end
713     if str!='' then str+=';' end
714     str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
715   end
716   str
717 end
718
719 def getuserid(token)
720   token=sqlescape(token)
721   if (token=~/^(.+)\+(.+)$/) then
722     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
723   else
724     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND token='#{token}'")
725   end
726 end
727
728
729
730 # ====================================================================
731 # AMF read subroutines
732
733 # ----- getint          return two-byte integer
734 # ----- getlong         return four-byte long
735 # ----- getstring       return string with two-byte length
736 # ----- getdouble       return eight-byte double-precision float
737 # ----- getobject       return object/hash
738 # ----- getarray        return numeric array
739
740 def getint(s)
741   s.getc*256+s.getc
742 end
743
744 def getlong(s)
745   ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
746 end
747
748 def getstring(s)
749   len=s.getc*256+s.getc
750   s.read(len)
751 end
752
753 def getdouble(s)
754   a=s.read(8).unpack('G')                       # G big-endian, E little-endian
755   a[0]
756 end
757
758 def getarray(s)
759   len=getlong(s)
760   arr=[]
761   for i in (0..len-1)
762     arr[i]=getvalue(s)
763   end
764   arr
765 end
766
767 def getobject(s)
768   arr={}
769   while (key=getstring(s))
770     if (key=='') then break end
771     arr[key]=getvalue(s)
772   end
773   s.getc                # skip the 9 'end of object' value
774   arr
775 end
776
777 # ----- getvalue        parse and get value
778
779 def getvalue(s)
780   case s.getc
781   when 0;       return getdouble(s)                     # number
782   when 1;       return s.getc                           # boolean
783   when 2;       return getstring(s)                     # string
784   when 3;       return getobject(s)                     # object/hash
785   when 5;       return nil                                      # null
786   when 6;       return nil                                      # undefined
787   when 8;       s.read(4)                                       # mixedArray
788                     return getobject(s)                 #  |
789   when 10;      return getarray(s)                      # array
790   else;         return nil                                      # error
791   end
792 end
793
794 # ====================================================================
795 # AMF write subroutines
796
797 # ----- putdata         envelope data into AMF writeable form
798 # ----- encodevalue     pack variables as AMF
799
800 def putdata(index,n)
801   d =encodestring(index+"/onResult")
802   d+=encodestring("null")
803   d+=[-1].pack("N")
804   d+=encodevalue(n)
805 end
806
807 def encodevalue(n)
808   case n.class.to_s
809   when 'Array'
810     a=10.chr+encodelong(n.length)
811     n.each do |b|
812       a+=encodevalue(b)
813     end
814     a
815   when 'Hash'
816     a=3.chr
817     n.each do |k,v|
818       a+=encodestring(k)+encodevalue(v)
819     end
820     a+0.chr+0.chr+9.chr
821   when 'String'
822     2.chr+encodestring(n)
823   when 'Bignum','Fixnum','Float'
824     0.chr+encodedouble(n)
825   when 'NilClass'
826     5.chr
827   else
828     RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
829   end
830 end
831
832 # ----- encodestring    encode string with two-byte length
833 # ----- encodedouble    encode number as eight-byte double precision float
834 # ----- encodelong              encode number as four-byte long
835
836 def encodestring(n)
837   a,b=n.size.divmod(256)
838   a.chr+b.chr+n
839 end
840
841 def encodedouble(n)
842   [n].pack('G')
843 end
844
845 def encodelong(n)
846   [n].pack('N')
847 end
848
849 # ====================================================================
850 # Co-ordinate conversion
851
852 def lat2coord(a,basey,masterscale)
853   -(lat2y(a)-basey)*masterscale+250
854 end
855
856 def long2coord(a,baselong,masterscale)
857   (a-baselong)*masterscale+350
858 end
859
860 def lat2y(a)
861   180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
862 end
863
864 def coord2lat(a,masterscale,basey)
865   y2lat((a-250)/-masterscale+basey)
866 end
867
868 def coord2long(a,masterscale,baselong)
869   (a-350)/masterscale+baselong
870 end
871
872 def y2lat(a)
873   180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
874 end
875
876 end