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