]> git.openstreetmap.org Git - rails.git/blob - app/controllers/amf_controller.rb
use render proc to write out results, see if that makes things faster
[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       RAILS_DEFAULT_LOGGER.info("  Message: #{message}")
37
38       case message
39                   when 'getpresets';    results[index]=putdata(index,getpresets)
40                   when 'whichways';             results[index]=putdata(index,whichways(args))
41                   when 'getway';                results[index]=putdata(index,getway(args))
42                   when 'putway';                results[index]=putdata(index,putway(args))
43                   when 'deleteway';             results[index]=putdata(index,deleteway(args))
44       end
45     end
46
47     # ------------------
48     # Write out response
49
50     RAILS_DEFAULT_LOGGER.info("  Response: start")
51     response.headers["Content-Type"]="application/x-amf"
52     a,b=results.length.divmod(256)
53         render :text => proc { |response, output| 
54         output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
55                 results.each do |k,v|
56                   RAILS_DEFAULT_LOGGER.info("  Response: encode #{k}")
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 point/road
127 mini roundabout: highway=mini_roundabout
128 traffic lights: highway=traffic_signals
129
130 point/footway
131 bridge: highway=bridge
132 gate: highway=gate
133 stile: highway=stile
134 cattle grid: highway=cattle_grid
135
136 point/cycleway
137 gate: highway=gate
138
139 point/waterway
140 lock gate: waterway=lock_gate
141 weir: waterway=weir
142 aqueduct: waterway=aqueduct
143 winding hole: waterway=turning_point
144 mooring: waterway=mooring
145
146 point/railway
147 station: railway=station
148 viaduct: railway=viaduct
149 level crossing: railway=crossing
150 EOF
151
152     StringIO.open(txt) do |file|
153       file.each_line {|line|
154         t=line.chomp
155         if (t=~/(\w+)\/(\w+)/) then
156           presettype=$1
157           presetcategory=$2
158           presetmenus[presettype].push(presetcategory)
159           presetnames[presettype][presetcategory]=["(no preset)"]
160         elsif (t=~/^(.+):\s?(.+)$/) then
161           pre=$1; kv=$2
162           presetnames[presettype][presetcategory].push(pre)
163           presets[pre]={}
164           kv.split(',').each {|a|
165             if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
166           }
167         end
168       }
169     end
170     return [presets,presetmenus,presetnames]
171   end
172
173   # -----       whichways(left,bottom,right,top)
174   #             return array of ways in current bounding box
175   #             at present, instead of using correct (=more complex) SQL to find
176   #             corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
177
178   def whichways(args)
179     xmin = args[0].to_f-0.01
180     ymin = args[1].to_f-0.01
181     xmax = args[2].to_f+0.01
182     ymax = args[3].to_f+0.01
183
184     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
185
186     waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
187        "  FROM current_way_segments,current_segments,current_nodes,current_ways "+
188        " WHERE segment_id=current_segments.id "+
189        "   AND current_segments.visible=1 "+
190        "   AND node_a=current_nodes.id "+
191            "   AND current_ways.id=current_way_segments.id "+
192            "   AND current_ways.visible=1 "+
193        "   AND (latitude  BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
194        "   AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+")")
195
196        ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
197
198        pointlist =ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.tags "+
199        "  FROM current_nodes "+
200        "  LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
201        "  LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
202        " WHERE (latitude  BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
203        "   AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+") "+
204        "   AND cs1.id IS NULL AND cs2.id IS NULL "+
205        "   AND current_nodes.visible=1")
206
207             points = pointlist.collect {|a| [a['id'],tag2array(a['tags'])]      } # get a list of node ids and their tags
208
209     return [ways,points]
210   end
211
212   # -----       getway (objectname, way, baselong, basey, masterscale)
213   #                     returns objectname, array of co-ordinates, attributes,
214   #                                     xmin,xmax,ymin,ymax
215
216   def getway(args)
217     objname,wayid,baselong,basey,masterscale=args
218     wayid = wayid.to_i
219     points = []
220     lastid = -1
221     xmin = ymin = 999999
222     xmax = ymax = -999999
223
224     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
225
226     readwayquery(wayid).each {|row|
227       xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
228       xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
229       points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
230       lastid = row['id2'].to_i
231       points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
232       xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
233       xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
234       ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
235       ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
236     }
237
238     attributes={}
239     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
240     attrlist.each {|a| attributes[a['k']]=a['v'] }
241
242     [objname,points,attributes,xmin,xmax,ymin,ymax]
243   end
244
245   # -----       putway (user token, way, array of co-ordinates, array of attributes,
246   #                                     baselong, basey, masterscale)
247   #                     returns current way ID, new way ID, hash of renumbered nodes,
248   #                                     xmin,xmax,ymin,ymax
249
250   def putway(args)
251     usertoken,originalway,points,attributes,baselong,basey,masterscale=args
252     uid=getuserid(usertoken)
253     return if !uid
254     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
255     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
256     db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
257     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
258     originalway=originalway.to_i
259
260     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
261
262     # -- 3.     read original way into memory
263
264     xc={}; yc={}; tagc={}; seg={}
265     if originalway>0
266       way=originalway
267       readwayquery(way).each { |row|
268         id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
269         id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
270         seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
271       }
272           ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
273     else
274       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
275     end
276
277     # -- 4.     get version by inserting new row into ways
278
279     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
280
281     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
282
283     xmin = ymin = 999999
284     xmax = ymax = -999999
285     insertsql = ''
286     renumberednodes={}
287
288     points.each_index do |i|
289       xs=coord2long(points[i][0],masterscale,baselong)
290       ys=coord2lat(points[i][1],masterscale,basey)
291       xmin=[xs,xmin].min; xmax=[xs,xmax].max
292       ymin=[ys,ymin].min; ymax=[ys,ymax].max
293       node=points[i][2].to_i
294       tagstr=array2tag(points[i][4])
295       tagsql="'"+sqlescape(tagstr)+"'"
296
297       # compare node
298       if node<0
299         # new node - create
300         newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (   latitude,longitude,timestamp,user_id,visible,tags) VALUES (           #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
301                         ActiveRecord::Base.connection.insert("INSERT INTO nodes         (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
302         points[i][2]=newnode
303         renumberednodes[node.to_s]=newnode.to_s
304
305       elsif xc.has_key?(node)
306         # old node from original way - update
307         if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
308           ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
309           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}")
310         end
311       else
312         # old node, created in another way and now added to this way
313       end
314
315     end
316
317
318     # -- 6.i compare segments
319
320     numberedsegments={}
321     seglist=''                          # list of existing segments that we want to keep
322     for i in (0..(points.length-2))
323       if (points[i+1][3].to_i==0) then next end
324       segid=points[i+1][5].to_i
325       from =points[i  ][2].to_i
326       to   =points[i+1][2].to_i
327       if seg.has_key?(segid)
328         if seg[segid]=="#{from}-#{to}" then 
329           if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
330           next
331         end
332       end
333       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,'')")
334                 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,'')")
335       points[i+1][5]=segid
336       numberedsegments[(i+1).to_s]=segid.to_s
337     end
338     # numberedsegments.each{|a,b| RAILS_DEFAULT_LOGGER.error("Sending back: seg no. #{a} -> id #{b}") }
339
340
341     # -- 6.ii insert new way segments
342
343     createuniquesegments(way,db_uqs,seglist)    # segments which appear in this way but no other
344
345     #           delete segments from uniquesegments (and not in modified way)
346
347     sql=<<-EOF
348       INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
349       SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
350         FROM current_segments AS cs, #{db_uqs} AS us
351        WHERE cs.id=us.segment_id AND cs.visible=1 
352     EOF
353     ActiveRecord::Base.connection.insert(sql)
354
355     sql=<<-EOF
356          UPDATE current_segments AS cs, #{db_uqs} AS us
357           SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
358         WHERE cs.id=us.segment_id AND cs.visible=1 
359     EOF
360     ActiveRecord::Base.connection.update(sql)
361
362     #           delete nodes not in modified way or any other segments
363
364     createuniquenodes(db_uqs,db_uqn)    # nodes which appear in this way but no other
365
366     sql=<<-EOF
367                 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)  
368                 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
369                   FROM current_nodes AS cn,#{db_uqn}
370                  WHERE cn.id=node_id
371     EOF
372     ActiveRecord::Base.connection.insert(sql)
373
374     sql=<<-EOF
375       UPDATE current_nodes AS cn, #{db_uqn}
376          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
377        WHERE cn.id=node_id
378     EOF
379     ActiveRecord::Base.connection.update(sql)
380
381     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
382     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
383
384     #           insert new version of route into way_segments
385
386     insertsql =''
387     currentsql=''
388     sequence  =1
389     for i in (0..(points.length-2))
390       if (points[i+1][3].to_i==0) then next end
391       if insertsql !='' then insertsql +=',' end
392       if currentsql!='' then currentsql+=',' end
393       insertsql +="(#{way},#{points[i+1][5]},#{version})"
394       currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
395       sequence  +=1
396     end
397
398     ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
399     ActiveRecord::Base.connection.insert("INSERT INTO         way_segments (id,segment_id,version    ) VALUES #{insertsql}");
400     ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
401
402     # -- 7. insert new way tags
403
404     insertsql =''
405     currentsql=''
406     attributes.each do |k,v|
407       if v=='' then next end
408       if v[0,6]=='(type ' then next end
409       if insertsql !='' then insertsql +=',' end
410       if currentsql!='' then currentsql+=',' end
411       insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',#{version})"
412       currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
413     end
414
415     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
416     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
417     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
418
419     [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
420   end
421
422   # -----       deleteway (user token, way)
423   #                     returns way ID only
424
425   def deleteway(args)
426     usertoken,way=args
427
428     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
429
430     uid=getuserid(usertoken); if !uid then return end
431         way=way.to_i
432
433         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
434         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
435         db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
436         ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
437         createuniquesegments(way,db_uqs,'')
438
439         # -     delete any otherwise unused segments
440
441         sql=<<-EOF
442       INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
443       SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0 
444         FROM current_segments AS cs, #{db_uqs} AS us
445        WHERE cs.id=us.segment_id
446     EOF
447         ActiveRecord::Base.connection.insert(sql)
448
449         sql=<<-EOF
450       UPDATE current_segments AS cs, #{db_uqs} AS us
451          SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
452        WHERE cs.id=us.segment_id
453     EOF
454         ActiveRecord::Base.connection.update(sql)
455
456         # - delete any unused nodes
457   
458     createuniquenodes(db_uqs,db_uqn)
459
460         sql=<<-EOF
461                 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)  
462                 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
463                   FROM current_nodes AS cn,#{db_uqn}
464                  WHERE cn.id=node_id
465     EOF
466         ActiveRecord::Base.connection.insert(sql)
467
468         sql=<<-EOF
469       UPDATE current_nodes AS cn, #{db_uqn}
470          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
471        WHERE cn.id=node_id
472     EOF
473         ActiveRecord::Base.connection.update(sql)
474         
475         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
476         ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
477
478         # - delete way
479         
480         ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
481         ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
482         ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
483         ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
484         
485         way
486 end
487
488 # ====================================================================
489 # Support functions for remote calls
490
491 def readwayquery(id)
492   ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
493       "           n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
494       "    FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
495       "   WHERE current_way_segments.id=#{id} "+
496       "     AND segment_id=current_segments.id "+
497           "     AND current_segments.visible=1 "+
498       "     AND n1.id=node_a and n2.id=node_b "+
499       "     AND n1.visible=1 AND n2.visible=1 "+
500       "   ORDER BY sequence_id"
501 end
502
503 def createuniquesegments(way,uqs_name,seglist)
504   # Finds segments which appear in (previous version of) this way and no other
505   sql=<<-EOF
506       CREATE TEMPORARY TABLE #{uqs_name}
507               SELECT a.segment_id
508                 FROM (SELECT DISTINCT segment_id FROM current_way_segments 
509                   WHERE id = #{way}) a
510              LEFT JOIN current_way_segments b 
511                 ON b.segment_id = a.segment_id
512                  AND b.id != #{way}
513                WHERE b.segment_id IS NULL
514     EOF
515   if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
516   ActiveRecord::Base.connection.execute(sql)
517 end
518
519 def createuniquenodes(uqs_name,uqn_name)
520         # Finds nodes which appear in uniquesegments but no other segments
521         sql=<<-EOF
522                 CREATE TEMPORARY TABLE #{uqn_name}
523                            SELECT DISTINCT node_id
524                               FROM (SELECT cn.id AS node_id
525                                                   FROM current_nodes AS cn,
526                                                        current_segments AS cs,
527                                                        #{uqs_name} AS us
528                                                  WHERE cs.id=us.segment_id
529                                                    AND (cn.id=cs.node_a OR cn.id=cs.node_b)) AS n
530                                          LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
531                                          LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
532                                              WHERE cs2.node_a IS NULL
533                                                AND cs3.node_b IS NULL
534         EOF
535         ActiveRecord::Base.connection.execute(sql)
536 end
537
538 def sqlescape(a)
539   a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
540 end
541
542 def tag2array(a)
543   tags={}
544   a.gsub(';;;','#%').split(';').each do |b|
545     b.gsub!('#%',';;;')
546     b.gsub!('===','#%')
547     k,v=b.split('=')
548     if k.nil? then k='' end
549     if v.nil? then v='' end
550     tags[k.gsub('#%','=')]=v.gsub('#%','=')
551   end
552   tags
553 end
554
555 def array2tag(a)
556   str=''
557   a.each do |k,v|
558     if v=='' then next end
559     if v[0,6]=='(type ' then next end
560     if str!='' then str+=';' end
561     str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
562   end
563   str
564 end
565
566 def getuserid(token)
567   token=sqlescape(token)
568   if (token=~/^(.+)\+(.+)$/) then
569     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
570   else
571     return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND token='#{token}'")
572   end
573 end
574
575
576
577 # ====================================================================
578 # AMF read subroutines
579
580 # ----- getint          return two-byte integer
581 # ----- getlong         return four-byte long
582 # ----- getstring       return string with two-byte length
583 # ----- getdouble       return eight-byte double-precision float
584 # ----- getobject       return object/hash
585 # ----- getarray        return numeric array
586
587 def getint(s)
588   s.getc*256+s.getc
589 end
590
591 def getlong(s)
592   ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
593 end
594
595 def getstring(s)
596   len=s.getc*256+s.getc
597   s.read(len)
598 end
599
600 def getdouble(s)
601   a=s.read(8).unpack('G')                       # G big-endian, E little-endian
602   a[0]
603 end
604
605 def getarray(s)
606   len=getlong(s)
607   arr=[]
608   for i in (0..len-1)
609     arr[i]=getvalue(s)
610   end
611   arr
612 end
613
614 def getobject(s)
615   arr={}
616   while (key=getstring(s))
617     if (key=='') then break end
618     arr[key]=getvalue(s)
619   end
620   s.getc                # skip the 9 'end of object' value
621   arr
622 end
623
624 # ----- getvalue        parse and get value
625
626 def getvalue(s)
627   case s.getc
628   when 0;       return getdouble(s)                     # number
629   when 1;       return s.getc                           # boolean
630   when 2;       return getstring(s)                     # string
631   when 3;       return getobject(s)                     # object/hash
632   when 5;       return nil                                      # null
633   when 6;       return nil                                      # undefined
634   when 8;       s.read(4)                                       # mixedArray
635     return getobject(s)                 #  |
636   when 10;return getarray(s)                    # array
637   else; return nil                                      # error
638   end
639 end
640
641 # ====================================================================
642 # AMF write subroutines
643
644 # ----- putdata         envelope data into AMF writeable form
645 # ----- encodevalue     pack variables as AMF
646
647 def putdata(index,n)
648   d =encodestring(index+"/onResult")
649   d+=encodestring("null")
650   d+=[-1].pack("N")
651   d+=encodevalue(n)
652 end
653
654 def encodevalue(n)
655   case n.class.to_s
656   when 'Array'
657     a=10.chr+encodelong(n.length)
658     n.each do |b|
659       a+=encodevalue(b)
660     end
661     a
662   when 'Hash'
663     a=3.chr
664     n.each do |k,v|
665       a+=encodestring(k)+encodevalue(v)
666     end
667     a+0.chr+0.chr+9.chr
668   when 'String'
669     2.chr+encodestring(n)
670   when 'Bignum','Fixnum','Float'
671     0.chr+encodedouble(n)
672   when 'NilClass'
673     5.chr
674   else
675     RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
676   end
677 end
678
679 # ----- encodestring    encode string with two-byte length
680 # ----- encodedouble    encode number as eight-byte double precision float
681 # ----- encodelong              encode number as four-byte long
682
683 def encodestring(n)
684   a,b=n.size.divmod(256)
685   a.chr+b.chr+n
686 end
687
688 def encodedouble(n)
689   [n].pack('G')
690 end
691
692 def encodelong(n)
693   [n].pack('N')
694 end
695
696 # ====================================================================
697 # Co-ordinate conversion
698
699 def lat2coord(a,basey,masterscale)
700   -(lat2y(a)-basey)*masterscale+250
701 end
702
703 def long2coord(a,baselong,masterscale)
704   (a-baselong)*masterscale+350
705 end
706
707 def lat2y(a)
708   180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
709 end
710
711 def coord2lat(a,masterscale,basey)
712   y2lat((a-250)/-masterscale+basey)
713 end
714
715 def coord2long(a,masterscale,baselong)
716   (a-350)/masterscale+baselong
717 end
718
719 def y2lat(a)
720   180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
721 end
722
723 end