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