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