php-serialize 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (4) hide show
  1. data/README +34 -0
  2. data/lib/php_serialize.rb +314 -0
  3. data/test.rb +109 -0
  4. metadata +54 -0
data/README ADDED
@@ -0,0 +1,34 @@
1
+ Ruby PHP Serializer
2
+ ===================
3
+
4
+ This module provides two methods: PHP.serialize() and PHP.unserialize(), both
5
+ of which should be compatible with the similarly named functions in PHP.
6
+
7
+ Basic usage:
8
+
9
+ require 'php_serialize'
10
+ in = {'foo' => 'bar'}
11
+ php = PHP.serialize(in)
12
+ # pass string to PHP unserialize() to get array('foo' => 'bar')
13
+ out = PHP.unserialize(php) # => {'foo' => 'bar'}
14
+
15
+
16
+ PHP.unserialize can also read PHP sessions, which are collections of named
17
+ serialized objects. These can be reserialized using PHP.serialize_session(),
18
+ which has the same semantics as PHP.serialize(), but which only supports
19
+ Hash and associative Arrays for the root object.
20
+
21
+
22
+ Acknowledgements
23
+ ================
24
+
25
+ TJ Vanderpoel, initial PHP serialized session support.
26
+
27
+ Philip Hallstrom, fix for self-generated Structs on unserialization.
28
+
29
+ Edward Speyer, fix for assoc serialization in nested structures.
30
+
31
+
32
+
33
+ Author: Thomas Hurst <tom@hur.st>, http://hur.st/
34
+ WWW: http://www.aagh.net/projects/ruby-php-serialize
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env ruby
2
+ # Copyright (c) 2003-2009 Thomas Hurst <tom@hur.st>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ # of this software and associated documentation files (the "Software"), to deal
6
+ # in the Software without restriction, including without limitation the rights
7
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ # copies of the Software, and to permit persons to whom the Software is
9
+ # furnished to do so, subject to the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be included in
12
+ # all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ # SOFTWARE.
21
+
22
+ # PHP serialize() and unserialize() workalikes
23
+ #
24
+ # Release History:
25
+ # 1.0.0 - 2003-06-02 - First release.
26
+ # 1.0.1 - 2003-06-16 - Minor bugfixes.
27
+ # 1.0.2 - 2004-09-17 - Switch all {}'s to explicit Hash.new's.
28
+ # 1.1.0 - 2009-04-01 - Pass assoc to recursive calls (thanks to Edward Speyer).
29
+ # - Serialize Symbol like String.
30
+ # - Add testsuite.
31
+ # - Instantiate auto-generated Structs properly (thanks
32
+ # to Philip Hallstrom).
33
+ # - Unserialize arrays properly in assoc mode.
34
+ # - Add PHP session support (thanks to TJ Vanderpoel).
35
+ # - Release as tarball and gem.
36
+ #
37
+ # See http://www.php.net/serialize and http://www.php.net/unserialize for
38
+ # details on the PHP side of all this.
39
+ module PHP
40
+ # string = PHP.serialize(mixed var[, bool assoc])
41
+ #
42
+ # Returns a string representing the argument in a form PHP.unserialize
43
+ # and PHP's unserialize() should both be able to load.
44
+ #
45
+ # Array, Hash, Fixnum, Float, True/FalseClass, NilClass, String and Struct
46
+ # are supported; as are objects which support the to_assoc method, which
47
+ # returns an array of the form [['attr_name', 'value']..]. Anything else
48
+ # will raise a TypeError.
49
+ #
50
+ # If 'assoc' is specified, Array's who's first element is a two value
51
+ # array will be assumed to be an associative array, and will be serialized
52
+ # as a PHP associative array rather than a multidimensional array.
53
+ def PHP.serialize(var, assoc = false) # {{{
54
+ s = ''
55
+ case var
56
+ when Array
57
+ s << "a:#{var.size}:{"
58
+ if assoc and var.first.is_a?(Array) and var.first.size == 2
59
+ var.each { |k,v|
60
+ s << PHP.serialize(k, assoc) << PHP.serialize(v, assoc)
61
+ }
62
+ else
63
+ var.each_with_index { |v,i|
64
+ s << "i:#{i};#{PHP.serialize(v, assoc)}"
65
+ }
66
+ end
67
+
68
+ s << '}'
69
+
70
+ when Hash
71
+ s << "a:#{var.size}:{"
72
+ var.each do |k,v|
73
+ s << "#{PHP.serialize(k, assoc)}#{PHP.serialize(v, assoc)}"
74
+ end
75
+ s << '}'
76
+
77
+ when Struct
78
+ # encode as Object with same name
79
+ s << "O:#{var.class.to_s.length}:\"#{var.class.to_s.downcase}\":#{var.members.length}:{"
80
+ var.members.each do |member|
81
+ s << "#{PHP.serialize(member, assoc)}#{PHP.serialize(var[member], assoc)}"
82
+ end
83
+ s << '}'
84
+
85
+ when String, Symbol
86
+ s << "s:#{var.to_s.length}:\"#{var.to_s}\";"
87
+
88
+ when Fixnum # PHP doesn't have bignums
89
+ s << "i:#{var};"
90
+
91
+ when Float
92
+ s << "d:#{var};"
93
+
94
+ when NilClass
95
+ s << 'N;'
96
+
97
+ when FalseClass, TrueClass
98
+ s << "b:#{var ? 1 :0};"
99
+
100
+ else
101
+ if var.respond_to?(:to_assoc)
102
+ v = var.to_assoc
103
+ # encode as Object with same name
104
+ s << "O:#{var.class.to_s.length}:\"#{var.class.to_s.downcase}\":#{v.length}:{"
105
+ v.each do |k,v|
106
+ s << "#{PHP.serialize(k.to_s, assoc)}#{PHP.serialize(v, assoc)}"
107
+ end
108
+ s << '}'
109
+ else
110
+ raise TypeError, "Unable to serialize type #{var.class}"
111
+ end
112
+ end
113
+
114
+ s
115
+ end # }}}
116
+
117
+ # string = PHP.serialize_session(mixed var[, bool assoc])
118
+ #
119
+ # Like PHP.serialize, but only accepts a Hash or associative Array as the root
120
+ # type. The results are returned in PHP session format.
121
+ def PHP.serialize_session(var, assoc = false) # {{{
122
+ s = ''
123
+ case var
124
+ when Hash
125
+ var.each do |key,value|
126
+ if key.to_s =~ /\|/
127
+ raise IndexError, "Top level names may not contain pipes"
128
+ end
129
+ s << "#{key}|#{PHP.serialize(value, assoc)}"
130
+ end
131
+ when Array
132
+ var.each do |x|
133
+ case x
134
+ when Array
135
+ if x.size == 2
136
+ s << "#{x[0]}|#{PHP.serialize(x[1])}"
137
+ else
138
+ raise TypeError, "Array is not associative"
139
+ end
140
+ end
141
+ end
142
+ else
143
+ raise TypeError, "Unable to serialize sessions with top level types other than Hash and associative Array"
144
+ end
145
+ s
146
+ end # }}}
147
+
148
+ # mixed = PHP.unserialize(string serialized, [hash classmap, [bool assoc]])
149
+ #
150
+ # Returns an object containing the reconstituted data from serialized.
151
+ #
152
+ # If a PHP array (associative; like an ordered hash) is encountered, it
153
+ # scans the keys; if they're all incrementing integers counting from 0,
154
+ # it's unserialized as an Array, otherwise it's unserialized as a Hash.
155
+ # Note: this will lose ordering. To avoid this, specify assoc=true,
156
+ # and it will be unserialized as an associative array: [[key,value],...]
157
+ #
158
+ # If a serialized object is encountered, the hash 'classmap' is searched for
159
+ # the class name (as a symbol). Since PHP classnames are not case-preserving,
160
+ # this *must* be a .capitalize()d representation. The value is expected
161
+ # to be the class itself; i.e. something you could call .new on.
162
+ #
163
+ # If it's not found in 'classmap', the current constant namespace is searched,
164
+ # and failing that, a new Struct(classname) is generated, with the arguments
165
+ # for .new specified in the same order PHP provided; since PHP uses hashes
166
+ # to represent attributes, this should be the same order they're specified
167
+ # in PHP, but this is untested.
168
+ #
169
+ # each serialized attribute is sent to the new object using the respective
170
+ # {attribute}=() method; you'll get a NameError if the method doesn't exist.
171
+ #
172
+ # Array, Hash, Fixnum, Float, True/FalseClass, NilClass and String should
173
+ # be returned identically (i.e. foo == PHP.unserialize(PHP.serialize(foo))
174
+ # for these types); Struct should be too, provided it's in the namespace
175
+ # Module.const_get within unserialize() can see, or you gave it the same
176
+ # name in the Struct.new(<structname>), otherwise you should provide it in
177
+ # classmap.
178
+ #
179
+ # Note: StringIO is required for unserialize(); it's loaded as needed
180
+ def PHP.unserialize(string, classmap = nil, assoc = false) # {{{
181
+ if classmap == true or classmap == false
182
+ assoc = classmap
183
+ classmap = {}
184
+ end
185
+ classmap ||= {}
186
+
187
+ require 'stringio'
188
+ string = StringIO.new(string)
189
+ def string.read_until(char)
190
+ val = ''
191
+ while (c = self.read(1)) != char
192
+ val << c
193
+ end
194
+ val
195
+ end
196
+
197
+ if string.string =~ /^(\w+)\|/ # session_name|serialized_data
198
+ ret = Hash.new
199
+ loop do
200
+ if string.string[string.pos, 32] =~ /^(\w+)\|/
201
+ string.pos += $&.size
202
+ ret[$1] = PHP.do_unserialize(string, classmap, assoc)
203
+ else
204
+ break
205
+ end
206
+ end
207
+ ret
208
+ else
209
+ PHP.do_unserialize(string, classmap, assoc)
210
+ end
211
+ end
212
+
213
+ private
214
+ def PHP.do_unserialize(string, classmap, assoc)
215
+ val = nil
216
+ # determine a type
217
+ type = string.read(2)[0,1]
218
+ case type
219
+ when 'a' # associative array, a:length:{[index][value]...}
220
+ count = string.read_until('{').to_i
221
+ val = vals = Array.new
222
+ count.times do |i|
223
+ vals << [do_unserialize(string, classmap, assoc), do_unserialize(string, classmap, assoc)]
224
+ end
225
+ string.read(1) # skip the ending }
226
+
227
+ # now, we have an associative array, let's clean it up a bit...
228
+ # arrays have all numeric indexes, in order; otherwise we assume a hash
229
+ array = true
230
+ i = 0
231
+ vals.each do |key,value|
232
+ if key != i # wrong index -> assume hash
233
+ array = false
234
+ break
235
+ end
236
+ i += 1
237
+ end
238
+
239
+ if array
240
+ vals.collect! do |key,value|
241
+ value
242
+ end
243
+ else
244
+ if assoc
245
+ val = vals.map {|v| v }
246
+ else
247
+ val = Hash.new
248
+ vals.each do |key,value|
249
+ val[key] = value
250
+ end
251
+ end
252
+ end
253
+
254
+ when 'O' # object, O:length:"class":length:{[attribute][value]...}
255
+ # class name (lowercase in PHP, grr)
256
+ len = string.read_until(':').to_i + 3 # quotes, seperator
257
+ klass = string.read(len)[1...-2].capitalize.intern # read it, kill useless quotes
258
+
259
+ # read the attributes
260
+ attrs = []
261
+ len = string.read_until('{').to_i
262
+
263
+ len.times do
264
+ attr = (do_unserialize(string, classmap, assoc))
265
+ attrs << [attr.intern, (attr << '=').intern, do_unserialize(string, classmap, assoc)]
266
+ end
267
+ string.read(1)
268
+
269
+ val = nil
270
+ # See if we need to map to a particular object
271
+ if classmap.has_key?(klass)
272
+ val = classmap[klass].new
273
+ elsif Struct.const_defined?(klass) # Nope; see if there's a Struct
274
+ classmap[klass] = val = Struct.const_get(klass)
275
+ val = val.new
276
+ else # Nope; see if there's a Constant
277
+ begin
278
+ classmap[klass] = val = Module.const_get(klass)
279
+
280
+ val = val.new
281
+ rescue NameError # Nope; make a new Struct
282
+ classmap[klass] = Struct.new(klass.to_s, *attrs.collect { |v| v[0].to_s })
283
+ val = val.new
284
+ end
285
+ end
286
+
287
+ attrs.each do |attr,attrassign,v|
288
+ val.__send__(attrassign, v)
289
+ end
290
+
291
+ when 's' # string, s:length:"data";
292
+ len = string.read_until(':').to_i + 3 # quotes, separator
293
+ val = string.read(len)[1...-2] # read it, kill useless quotes
294
+
295
+ when 'i' # integer, i:123
296
+ val = string.read_until(';').to_i
297
+
298
+ when 'd' # double (float), d:1.23
299
+ val = string.read_until(';').to_f
300
+
301
+ when 'N' # NULL, N;
302
+ val = nil
303
+
304
+ when 'b' # bool, b:0 or 1
305
+ val = (string.read(2)[0] == ?1 ? true : false)
306
+
307
+ else
308
+ raise TypeError, "Unable to unserialize type '#{type}'"
309
+ end
310
+
311
+ val
312
+ end # }}}
313
+ end
314
+
data/test.rb ADDED
@@ -0,0 +1,109 @@
1
+ #!/usr/local/bin/ruby
2
+
3
+ require 'test/unit'
4
+
5
+ $:.unshift "lib"
6
+ require 'php_serialize'
7
+
8
+ TestStruct = Struct.new(:name, :value)
9
+ class TestClass
10
+ attr_accessor :name
11
+ attr_accessor :value
12
+
13
+ def initialize(name = nil, value = nil)
14
+ @name = name
15
+ @value = value
16
+ end
17
+
18
+ def to_assoc
19
+ [['name', @name], ['value', @value]]
20
+ end
21
+
22
+ def ==(other)
23
+ other.class == self.class and other.name == @name and other.value == @value
24
+ end
25
+ end
26
+
27
+ ClassMap = {
28
+ TestStruct.name.capitalize.intern => TestStruct,
29
+ TestClass.name.capitalize.intern => TestClass
30
+ }
31
+
32
+ class TestPhpSerialize < Test::Unit::TestCase
33
+ def self.test(ruby, php, opts = {})
34
+ if opts[:name]
35
+ name = opts[:name]
36
+ else
37
+ name = ruby.to_s
38
+ end
39
+
40
+ define_method("test_#{name}".intern) do
41
+ assert_nothing_thrown do
42
+ serialized = PHP.serialize(ruby)
43
+ assert_equal php, serialized
44
+
45
+ unserialized = PHP.unserialize(serialized, ClassMap)
46
+ case ruby
47
+ when Symbol
48
+ assert_equal ruby.to_s, unserialized
49
+ else
50
+ assert_equal ruby, unserialized
51
+ end
52
+ end
53
+ end
54
+ end
55
+
56
+ test nil, 'N;'
57
+ test false, 'b:0;'
58
+ test true, 'b:1;'
59
+ test 42, 'i:42;'
60
+ test -42, 'i:-42;'
61
+ test 2147483647, "i:2147483647;", :name => 'Max Fixnum'
62
+ test -2147483648, "i:-2147483648;", :name => 'Min Fixnum'
63
+ test 4.2, 'd:4.2;'
64
+ test 'test', 's:4:"test";'
65
+ test :test, 's:4:"test";', :name => 'Symbol'
66
+ test "\"\n\t\"", "s:4:\"\"\n\t\"\";", :name => 'Complex string'
67
+ test [nil, true, false, 42, 4.2, 'test'], 'a:6:{i:0;N;i:1;b:1;i:2;b:0;i:3;i:42;i:4;d:4.2;i:5;s:4:"test";}',
68
+ :name => 'Array'
69
+ test({'foo' => 'bar', 4 => [5,4,3,2]}, 'a:2:{s:3:"foo";s:3:"bar";i:4;a:4:{i:0;i:5;i:1;i:4;i:2;i:3;i:3;i:2;}}', :name => 'Hash')
70
+ test TestStruct.new("Foo", 65), 'O:10:"teststruct":2:{s:4:"name";s:3:"Foo";s:5:"value";i:65;}',
71
+ :name => 'Struct'
72
+ test TestClass.new("Foo", 65), 'O:9:"testclass":2:{s:4:"name";s:3:"Foo";s:5:"value";i:65;}',
73
+ :name => 'Class'
74
+
75
+ # Verify assoc is passed down calls.
76
+ # Slightly awkward because hashes don't guarantee order.
77
+ def test_assoc
78
+ assert_nothing_raised do
79
+ ruby = {'foo' => ['bar','baz'], 'hash' => {'hash' => 'smoke'}}
80
+ ruby_assoc = [['foo', ['bar','baz']], ['hash', [['hash','smoke']]]]
81
+ phps = [
82
+ 'a:2:{s:4:"hash";a:1:{s:4:"hash";s:5:"smoke";}s:3:"foo";a:2:{i:0;s:3:"bar";i:1;s:3:"baz";}}',
83
+ 'a:2:{s:3:"foo";a:2:{i:0;s:3:"bar";i:1;s:3:"baz";}s:4:"hash";a:1:{s:4:"hash";s:5:"smoke";}}'
84
+ ]
85
+ serialized = PHP.serialize(ruby, true)
86
+ assert phps.include?(serialized)
87
+ unserialized = PHP.unserialize(serialized, true)
88
+ assert_equal ruby_assoc.sort, unserialized.sort
89
+ end
90
+ end
91
+
92
+ def test_sessions
93
+ assert_nothing_raised do
94
+ ruby = {'session_id' => 42, 'user_data' => {'uid' => 666}}
95
+ phps = [
96
+ 'session_id|i:42;user_data|a:1:{s:3:"uid";i:666;}',
97
+ 'user_data|a:1:{s:3:"uid";i:666;}session_id|i:42;'
98
+ ]
99
+ unserialized = PHP.unserialize(phps.first)
100
+ assert_equal ruby, unserialized
101
+ serialized = PHP.serialize_session(ruby)
102
+ assert phps.include?(serialized)
103
+ end
104
+ end
105
+ end
106
+
107
+ require 'test/unit/ui/console/testrunner'
108
+ Test::Unit::UI::Console::TestRunner.run(TestPhpSerialize)
109
+
metadata ADDED
@@ -0,0 +1,54 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: php-serialize
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Thomas Hurst
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-04-01 00:00:00 +01:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: "This module provides two methods: PHP.serialize() and PHP.unserialize(), both of which should be compatible with the similarly named functions in PHP. It can also serialize and unserialize PHP sessions."
17
+ email: tom@hur.st
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files: []
23
+
24
+ files:
25
+ - README
26
+ - lib/php_serialize.rb
27
+ has_rdoc: true
28
+ homepage: http://www.aagh.net/projects/ruby-php-serialize
29
+ post_install_message:
30
+ rdoc_options: []
31
+
32
+ require_paths:
33
+ - lib/
34
+ required_ruby_version: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: "0"
39
+ version:
40
+ required_rubygems_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: "0"
45
+ version:
46
+ requirements: []
47
+
48
+ rubyforge_project:
49
+ rubygems_version: 1.3.1
50
+ signing_key:
51
+ specification_version: 2
52
+ summary: Ruby analogs to PHP's serialize() and unserialize() functions
53
+ test_files:
54
+ - test.rb