nickw's auth stuff, plus some optimisations. If f--king svn finally commits this...
[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         for i in (1..headers)                           # Read each header
22                 name=getstring(req)                             #  |
23                 req.getc                                                #  | skip boolean
24                 value=getvalue(req)                             #  |
25                 header["name"]=value                    #  |
26         end
27
28         bodies=getint(req)                                      # Read number of bodies
29         for i in (1..bodies)                            # Read each body
30                 message=getstring(req)                  #  | get message name
31                 index=getstring(req)                    #  | get index in response sequence
32                 bytes=getlong(req)                              #  | get total size in bytes
33                 args=getvalue(req)                              #  | get response (probably an array)
34         
35                 case message
36                         when 'getpresets';      results[index]=putdata(index,getpresets)
37                         when 'whichways';       results[index]=putdata(index,whichways(args))
38                         when 'getway';          results[index]=putdata(index,getway(args))
39                         when 'putway';          results[index]=putdata(index,putway(args))
40                         when 'deleteway';       results[index]=putdata(index,deleteway(args))
41                 end
42         end
43
44         # ------------------
45         # Write out response
46
47         response.headers["Content-Type"]="application/x-amf"
48         a,b=results.length.divmod(256)
49         ans=0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
50         results.each do |k,v|
51                 ans+=v
52         end
53         render :text=>ans
54
55   end
56
57
58         # ====================================================================
59         # Remote calls
60
61         # ----- getpresets
62         #               return presets,presetmenus and presetnames arrays
63
64         def getpresets
65                 presets={}
66                 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]
67                 presetnames={}; presetnames['point']={}; presetnames['way']={}
68                 presettype=''
69                 presetcategory=''
70                 
71                 File.open("config/potlatch/presets.txt") do |file|
72                         file.each_line {|line|
73                                 t=line.chomp
74                                 if (t=~/(\w+)\/(\w+)/) then
75                                         presettype=$1
76                                         presetcategory=$2
77                                         presetmenus[presettype].push(presetcategory)
78                                         presetnames[presettype][presetcategory]=["(no preset)"]
79                                 elsif (t=~/^(.+):\s?(.+)$/) then
80                                         pre=$1; kv=$2
81                                         presetnames[presettype][presetcategory].push(pre)
82                                         presets[pre]={}
83                                         kv.split(',').each {|a|
84                                                 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
85                                         }
86                                 end
87                         }
88                 end
89                 [presets,presetmenus,presetnames]
90         end
91
92         # ----- whichways(left,bottom,right,top)
93         #               return array of ways in current bounding box
94         #               at present, instead of using correct (=more complex) SQL to find
95         #               corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
96         
97         def whichways(args)
98                 waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
99                          "  FROM current_way_segments,current_segments,current_nodes "+
100                          " WHERE segment_id=current_segments.id "+
101                          "   AND current_segments.visible=1 "+
102                          "   AND node_a=current_nodes.id "+
103                          "   AND (latitude  BETWEEN "+(args[1].to_f-0.01).to_s+" AND "+(args[3].to_f+0.01).to_s+") "+
104                          "   AND (longitude BETWEEN "+(args[0].to_f-0.01).to_s+" AND "+(args[2].to_f+0.01).to_s+")")
105                 ways=[]
106                 waylist.each {|a|
107                         ways<<a.wayid.to_i
108                 }
109                 ways
110         end
111
112         # ----- getway (objectname, way, baselong, basey, masterscale)
113         #               returns objectname, array of co-ordinates, attributes,
114         #                               xmin,xmax,ymin,ymax
115         
116         def getway(args)
117                 objname,wayid,baselong,basey,masterscale=args
118                 wayid=wayid.to_i
119                 points=[]
120                 lastid=-1
121                 xmin=999999; xmax=-999999
122                 ymin=999999; ymax=-999999
123
124                 readwayquery(wayid).each {|row|
125                         xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
126                         xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
127                         if (row['id1'].to_i!=lastid)
128                                 points<<[xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0]
129                         end
130                         lastid=row['id2'].to_i
131                         points<<[xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
132                         xmin=[xmin,row['long1'].to_f,row['long2'].to_f].min
133                         xmax=[xmax,row['long1'].to_f,row['long2'].to_f].max
134                         ymin=[ymin,row['lat1'].to_f,row['lat2'].to_f].min
135                         ymax=[ymax,row['lat1'].to_f,row['lat2'].to_f].max
136                 }
137
138                 attributes={}
139                 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
140                 attrlist.each {|a| attributes[a['k']]=a['v'] }
141
142                 [objname,points,attributes,xmin,xmax,ymin,ymax]
143         end
144         
145         # ----- putway (user token, way, array of co-ordinates, array of attributes,
146         #                               baselong, basey, masterscale)
147         #               returns current way ID, new way ID, hash of renumbered nodes,
148         #                               xmin,xmax,ymin,ymax
149
150         def putway(args)
151                 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
152                 uid=getuserid(usertoken); if !uid then return end
153                 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
154                 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
155                 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
156                 originalway=originalway.to_i
157                 
158                 # -- 3. read original way into memory
159         
160                 xc={}; yc={}; tagc={}; seg={}
161                 if (originalway>0)
162                         way=originalway
163                         readwayquery(way).each { |row|
164                                 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
165                                 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
166                                 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
167                         }
168                 else
169                         way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
170                 end
171
172                 # -- 4. get version by inserting new row into ways
173
174                 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
175
176                 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
177
178                 xmin=999999; xmax=-999999
179                 ymin=999999; ymax=-999999
180                 insertsql=''
181                 nodelist=''
182                 renumberednodes={}
183         
184                 points.each_index do |i|
185                         xs=coord2long(points[i][0],masterscale,baselong)
186                         ys=coord2lat(points[i][1],masterscale,basey)
187                         xmin=[xs,xmin].min; xmax=[xs,xmax].max
188                         ymin=[ys,ymin].min; ymax=[ys,ymax].max
189                         node=points[i][2].to_i
190                         tagstr=array2tag(points[i][4])
191                         tagsql="'"+sqlescape(tagstr)+"'"
192         
193                         # compare node
194                         if node<0
195                                 # new node - create
196                                 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (   latitude,longitude,timestamp,user_id,visible,tags) VALUES (           #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
197                                                 ActiveRecord::Base.connection.insert("INSERT INTO nodes         (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
198                                 points[i][2]=newnode
199                                 renumberednodes[node.to_s]=newnode.to_s
200                                 
201                         elsif xc.has_key?(node)
202                                 # old node from original way - update
203                                 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
204                                         ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
205                                         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}")
206                                 else
207                                         if (nodelist!='') then nodelist+=',' end; nodelist+=node.to_s
208                                 end
209                         else
210                                 # old node, created in another way and now added to this way
211                                 if (nodelist!='') then nodelist+=',' end; nodelist+=node.to_s
212                         end
213         
214                 end
215
216                 if nodelist!='' then
217                         ActiveRecord::Base.connection.update("UPDATE current_nodes SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id IN (#{nodelist})")
218                 end
219
220                 # -- 6.i compare segments
221         
222                 numberedsegments={}
223                 seglist=''
224                 for i in (0..(points.length-2))
225                         if (points[i+1][3].to_i==0) then next end
226                         segid=points[i+1][5].to_i
227                         from =points[i  ][2].to_i
228                         to   =points[i+1][2].to_i
229                         if seg.has_key?(segid)
230                                 if seg[segid]=="#{from}-#{to}" then 
231                                         if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
232                                         next
233                                 end
234                         end
235                         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,'')")
236                                   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,'')")
237                         points[i+1][5]=segid
238                         numberedsegments[(i+1).to_s]=segid.to_s
239                 end
240                 # numberedsegments.each{|a,b| RAILS_DEFAULT_LOGGER.error("Sending back: seg no. #{a} -> id #{b}") }
241
242                 if seglist!='' then
243                         ActiveRecord::Base.connection.update("UPDATE current_segments SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id IN (#{seglist})")
244                 end
245
246
247                 # -- 6.ii insert new way segments
248
249                 createuniquesegments(way,db_uqs)
250
251                 # a=''
252                 # ActiveRecord::Base.connection.select_values("SELECT segment_id FROM #{db_uqs}").each {|b| a+=b+',' }
253                 # RAILS_DEFAULT_LOGGER.error("Unique segments are #{a}")
254                 # a=ActiveRecord::Base.connection.select_value("SELECT #{db_now}")
255                 # RAILS_DEFAULT_LOGGER.error("Timestamp of this edit is #{a}")
256                 # RAILS_DEFAULT_LOGGER.error("Userid of this edit is #{uid}")
257
258                 #               delete nodes from uniquesegments (and not in modified way)
259         
260                 sql=<<-EOF
261                         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)  
262                         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
263                           FROM current_nodes AS cn, 
264                                    current_segments AS cs,
265                                    #{db_uqs} AS us 
266                          WHERE(cn.id=cs.node_a OR cn.id=cs.node_b) 
267                            AND cs.id=us.segment_id AND cs.visible=1 
268                            AND (cn.timestamp!=#{db_now} OR cn.user_id!=#{uid})
269                 EOF
270                 ActiveRecord::Base.connection.insert(sql)
271
272                 sql=<<-EOF
273                         UPDATE current_nodes AS cn, 
274                                    current_segments AS cs, 
275                                    #{db_uqs} AS us 
276                            SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
277                          WHERE (cn.id=cs.node_a OR cn.id=cs.node_b) 
278                            AND cs.id=us.segment_id AND cs.visible=1 
279                            AND (cn.timestamp!=#{db_now} OR cn.user_id!=#{uid})
280                 EOF
281                 ActiveRecord::Base.connection.update(sql)
282         
283                 #               delete segments from uniquesegments (and not in modified way)
284         
285                 sql=<<-EOF
286                         INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
287                         SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
288                           FROM current_segments AS cs, #{db_uqs} AS us
289                          WHERE cs.id=us.segment_id AND cs.visible=1 
290                            AND (cs.timestamp!=#{db_now} OR cs.user_id!=#{uid})
291                 EOF
292                 ActiveRecord::Base.connection.insert(sql)
293                 
294                 sql=<<-EOF
295                            UPDATE current_segments AS cs, #{db_uqs} AS us
296                                   SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
297                                 WHERE cs.id=us.segment_id AND cs.visible=1 
298                                   AND (cs.timestamp!=#{db_now} OR cs.user_id!=#{uid})
299                 EOF
300                 ActiveRecord::Base.connection.update(sql)
301                 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
302
303                 #               insert new version of route into way_segments
304         
305                 insertsql =''
306                 currentsql=''
307                 sequence  =1
308                 for i in (0..(points.length-2))
309                         if (points[i+1][3].to_i==0) then next end
310                         if insertsql !='' then insertsql +=',' end
311                         if currentsql!='' then currentsql+=',' end
312                         insertsql +="(#{way},#{points[i+1][5]},#{version})"
313                         currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
314                         sequence  +=1
315                 end
316                 
317                 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
318                 ActiveRecord::Base.connection.insert("INSERT INTO         way_segments (id,segment_id,version    ) VALUES #{insertsql}");
319                 ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
320         
321                 # -- 7. insert new way tags
322         
323                 insertsql =''
324                 currentsql=''
325                 attributes.each do |k,v|
326                         if v=='' then next end
327                         if v[0,6]=='(type ' then next end
328                         if insertsql !='' then insertsql +=',' end
329                         if currentsql!='' then currentsql+=',' end
330                         insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',version)"
331                         currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
332                 end
333                 
334                 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
335                 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
336                 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
337         
338                 [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
339         end
340         
341         # ----- deleteway (user token, way)
342         #               returns way ID only
343         
344         def deleteway(args)
345                 usertoken,way=args
346                 uid=getuserid(usertoken); if !uid then return end
347                 way=way.to_i
348
349                 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
350                 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
351                 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
352                 createuniquesegments(way,db_uqs)
353         
354                 sql=<<-EOF
355                         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible) 
356                         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0 
357                           FROM current_nodes AS cn, 
358                                    current_segments AS cs, 
359                                    #{db_uqs} AS us
360                          WHERE (cn.id=cs.node_a OR cn.id=cs.node_b) 
361                            AND cs.id=us.segment_id
362                 EOF
363                 ActiveRecord::Base.connection.insert(sql)
364         
365                 sql=<<-EOF
366                         UPDATE current_nodes AS cn, 
367                                    current_segments AS cs, 
368                                    #{db_uqs} AS us
369                            SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
370                          WHERE (cn.id=cs.node_a OR cn.id=cs.node_b) 
371                            AND cs.id=us.segment_id
372                 EOF
373                 ActiveRecord::Base.connection.update(sql)
374         
375                 # -     delete any otherwise unused segments
376                                 
377                 sql=<<-EOF
378                         INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible) 
379                         SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0 
380                           FROM current_segments AS cs, #{db_uqs} AS us
381                          WHERE cs.id=us.segment_id
382                 EOF
383                 ActiveRecord::Base.connection.insert(sql)
384                                 
385                 sql=<<-EOF
386                         UPDATE current_segments AS cs, #{db_uqs} AS us
387                            SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid} 
388                          WHERE cs.id=us.segment_id
389                 EOF
390                 ActiveRecord::Base.connection.update(sql)
391                 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
392         
393                 # - delete way
394                 
395                 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
396                 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
397                 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
398                 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
399         
400                 way
401         end
402         
403         # ====================================================================
404         # Support functions for remote calls
405
406         def readwayquery(id)
407                 ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
408                         "                 n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
409                         "    FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
410                         "   WHERE current_way_segments.id=#{id} "+
411                         "     AND segment_id=current_segments.id "+
412                         "     AND n1.id=node_a and n2.id=node_b "+
413                         "   ORDER BY sequence_id"
414         end
415
416         def createuniquesegments(way,uqs_name)
417                 sql=<<-EOF
418                         CREATE TEMPORARY TABLE #{uqs_name}
419                                                         SELECT a.segment_id,COUNT(a.segment_id) AS ct
420                                                           FROM current_way_segments AS a, current_way_segments AS b
421                                                          WHERE a.segment_id=b.segment_id 
422                                                            AND a.id=#{way} 
423                                                   GROUP BY a.segment_id
424                                                         HAVING ct=1
425                 EOF
426                 ActiveRecord::Base.connection.execute(sql)
427         end
428         
429
430         def sqlescape(a)
431                 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
432         end
433
434         def tag2array(a)
435                 tags={}
436                 a.gsub(';;;','#%').split(';').each do |b|
437                         b.gsub!('#%',';;;')
438                         b.gsub!('===','#%')
439                         k,v=b.split('=')
440                         tags[k.gsub('#%','=')]=v.gsub('#%','=')
441                 end
442                 tags
443         end
444
445         def array2tag(a)
446                 str=''
447                 a.each do |k,v|
448                         if v=='' then next end
449                         if v[0,6]=='(type ' then next end
450                         if str!='' then str+=';' end
451                         str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
452                 end
453                 str
454         end
455         
456         def getuserid(token)
457                 token=sqlescape(token)
458                 if (token=~/^(.+)\+(.+)$/) then
459                         return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND timeout>NOW() AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
460                 else
461                         return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND timeout>NOW() AND token='#{token}'")
462                 end
463         end
464         
465
466
467         # ====================================================================
468         # AMF read subroutines
469         
470         # ----- getint          return two-byte integer
471         # ----- getlong         return four-byte long
472         # ----- getstring       return string with two-byte length
473         # ----- getdouble       return eight-byte double-precision float
474         # ----- getobject       return object/hash
475         # ----- getarray        return numeric array
476         
477         def getint(s)
478                 s.getc*256+s.getc
479         end
480         
481         def getlong(s)
482                 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
483         end
484         
485         def getstring(s)
486                 len=s.getc*256+s.getc
487                 s.read(len)
488         end
489         
490         def getdouble(s)
491                 a=s.read(8).unpack('G')                 # G big-endian, E little-endian
492                 a[0]
493         end
494         
495         def getarray(s)
496                 len=getlong(s)
497                 arr=[]
498                 for i in (0..len-1)
499                         arr[i]=getvalue(s)
500                 end
501                 arr
502         end
503         
504         def getobject(s)
505                 arr={}
506                 while (key=getstring(s))
507                         if (key=='') then break end
508                         arr[key]=getvalue(s)
509                 end
510                 s.getc          # skip the 9 'end of object' value
511                 arr
512         end
513         
514         # ----- getvalue        parse and get value
515         
516         def getvalue(s)
517                 case s.getc
518                         when 0; return getdouble(s)                     # number
519                         when 1; return s.getc                           # boolean
520                         when 2; return getstring(s)                     # string
521                         when 3; return getobject(s)                     # object/hash
522                         when 5; return nil                                      # null
523                         when 6; return nil                                      # undefined
524                         when 8; s.read(4)                                       # mixedArray
525                                         return getobject(s)                     #  |
526                         when 10;return getarray(s)                      # array
527                         else;   return nil                                      # error
528                 end
529         end
530
531         # ====================================================================
532         # AMF write subroutines
533         
534         # ----- putdata         envelope data into AMF writeable form
535         # ----- encodevalue     pack variables as AMF
536         
537         def putdata(index,n)
538                 d =encodestring(index+"/onResult")
539                 d+=encodestring("null")
540                 d+=[-1].pack("N")
541                 d+=encodevalue(n)
542         end
543         
544         def encodevalue(n)
545                 case n.class.to_s
546                         when 'Array'
547                                 a=10.chr+encodelong(n.length)
548                                 n.each do |b|
549                                         a+=encodevalue(b)
550                                 end
551                                 a
552                         when 'Hash'
553                                 a=3.chr
554                                 n.each do |k,v|
555                                         a+=encodestring(k)+encodevalue(v)
556                                 end
557                                 a+0.chr+0.chr+9.chr
558                         when 'String'
559                                 2.chr+encodestring(n)
560                         when 'Bignum','Fixnum','Float'
561                                 0.chr+encodedouble(n)
562                         when 'NilClass'
563                                 5.chr
564                         else
565                                 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
566                 end
567         end
568         
569         # ----- encodestring    encode string with two-byte length
570         # ----- encodedouble    encode number as eight-byte double precision float
571         # ----- encodelong              encode number as four-byte long
572         
573         def encodestring(n)
574                 a,b=n.size.divmod(256)
575                 a.chr+b.chr+n
576         end
577         
578         def encodedouble(n)
579                 [n].pack('G')
580         end
581         
582         def encodelong(n)
583                 [n].pack('N')
584         end
585         
586         # ====================================================================
587         # Co-ordinate conversion
588         
589         def lat2coord(a,basey,masterscale)
590                 -(lat2y(a)-basey)*masterscale+250
591         end
592         
593         def long2coord(a,baselong,masterscale)
594                 (a-baselong)*masterscale+350
595         end
596         
597         def lat2y(a)
598                 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
599         end
600         
601         def coord2lat(a,masterscale,basey)
602                 y2lat((a-250)/-masterscale+basey)
603         end
604         
605         def coord2long(a,masterscale,baselong)
606                 (a-350)/masterscale+baselong
607         end
608         
609         def y2lat(a)
610                 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
611         end
612
613
614 end