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