php4r 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
data/Gemfile ADDED
@@ -0,0 +1,16 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+
6
+ gem "http2"
7
+ gem "datet"
8
+
9
+ # Add dependencies to develop your gem here.
10
+ # Include everything needed to run rake, tests, features, etc.
11
+ group :development do
12
+ gem "rspec", "~> 2.8.0"
13
+ gem "rdoc", "~> 3.12"
14
+ gem "bundler", ">= 1.0.0"
15
+ gem "jeweler", "~> 1.8.4"
16
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,35 @@
1
+ GEM
2
+ remote: http://rubygems.org/
3
+ specs:
4
+ datet (0.0.12)
5
+ diff-lcs (1.1.3)
6
+ git (1.2.5)
7
+ http2 (0.0.5)
8
+ jeweler (1.8.4)
9
+ bundler (~> 1.0)
10
+ git (>= 1.2.5)
11
+ rake
12
+ rdoc
13
+ json (1.7.4)
14
+ rake (0.9.2.2)
15
+ rdoc (3.12)
16
+ json (~> 1.4)
17
+ rspec (2.8.0)
18
+ rspec-core (~> 2.8.0)
19
+ rspec-expectations (~> 2.8.0)
20
+ rspec-mocks (~> 2.8.0)
21
+ rspec-core (2.8.0)
22
+ rspec-expectations (2.8.0)
23
+ diff-lcs (~> 1.1.2)
24
+ rspec-mocks (2.8.0)
25
+
26
+ PLATFORMS
27
+ ruby
28
+
29
+ DEPENDENCIES
30
+ bundler (>= 1.0.0)
31
+ datet
32
+ http2
33
+ jeweler (~> 1.8.4)
34
+ rdoc (~> 3.12)
35
+ rspec (~> 2.8.0)
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 Kasper Johansen
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,19 @@
1
+ = php4r
2
+
3
+ Description goes here.
4
+
5
+ == Contributing to php4r
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
9
+ * Fork the project.
10
+ * Start a feature/bugfix branch.
11
+ * Commit and push until you are happy with your contribution.
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2012 Kasper Johansen. See LICENSE.txt for
18
+ further details.
19
+
data/Rakefile ADDED
@@ -0,0 +1,49 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "php4r"
18
+ gem.homepage = "http://github.com/kaspernj/php4r"
19
+ gem.license = "MIT"
20
+ gem.summary = %Q{A lib containing various PHP-functions coded in Ruby.}
21
+ gem.description = %Q{A lib containing various PHP-functions coded in Ruby. You can either use it or use it as a reference, if you are coming from PHP to Ruby or the other way around.}
22
+ gem.email = "k@spernj.org"
23
+ gem.authors = ["Kasper Johansen"]
24
+ # dependencies defined in Gemfile
25
+ end
26
+ Jeweler::RubygemsDotOrgTasks.new
27
+
28
+ require 'rspec/core'
29
+ require 'rspec/core/rake_task'
30
+ RSpec::Core::RakeTask.new(:spec) do |spec|
31
+ spec.pattern = FileList['spec/**/*_spec.rb']
32
+ end
33
+
34
+ RSpec::Core::RakeTask.new(:rcov) do |spec|
35
+ spec.pattern = 'spec/**/*_spec.rb'
36
+ spec.rcov = true
37
+ end
38
+
39
+ task :default => :spec
40
+
41
+ require 'rdoc/task'
42
+ Rake::RDocTask.new do |rdoc|
43
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
44
+
45
+ rdoc.rdoc_dir = 'rdoc'
46
+ rdoc.title = "php4r #{version}"
47
+ rdoc.rdoc_files.include('README*')
48
+ rdoc.rdoc_files.include('lib/**/*.rb')
49
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.0
data/lib/php4r.rb ADDED
@@ -0,0 +1,1029 @@
1
+ # coding: utf-8
2
+
3
+ module Php4r
4
+ def is_numeric(n) Float n rescue false end
5
+
6
+ def call_user_func(*paras)
7
+ if paras[0].is_a?(String)
8
+ send_paras = [paras[0].to_sym]
9
+ send_paras << paras[1] if paras[1]
10
+ send(*send_paras)
11
+ elsif paras[0].is_a?(Array)
12
+ send_paras = [paras[0][1].to_sym]
13
+ send_paras << paras[1] if paras[1]
14
+ paras[0][0].send(*send_paras)
15
+ else
16
+ raise "Unknown user-func: '#{paras[0].class.name}'."
17
+ end
18
+ end
19
+
20
+ def method_exists(obj, method_name)
21
+ return obj.respond_to?(method_name.to_s)
22
+ end
23
+
24
+ def is_a(obj, classname)
25
+ classname = classname.to_s
26
+ classname = "#{classname[0..0].upcase}#{classname[1..999]}"
27
+
28
+ return true if obj.is_a?(classname)
29
+ return false
30
+ end
31
+
32
+ def print_r(argument, ret = false, count = 1)
33
+ retstr = ""
34
+ cstr = argument.class.to_s
35
+ supercl = argument.class.superclass
36
+ superstr = supercl.to_s if supercl
37
+
38
+ if argument.respond_to?(:to_hash)
39
+ argument_use = argument.to_hash
40
+
41
+ retstr << "#{argument.class.name}{\n"
42
+ argument_use.each do |key, val|
43
+ i = 0
44
+ while i < count
45
+ retstr << " "
46
+ i += 1
47
+ end
48
+
49
+ if key.is_a?(Symbol)
50
+ keystr = ":#{key.to_s}"
51
+ else
52
+ keystr = key.to_s
53
+ end
54
+
55
+ retstr << "[#{keystr}] => "
56
+ retstr << Php4r.print_r(val, true, count + 1).to_s
57
+ end
58
+
59
+ i = 0
60
+ while i < count - 1
61
+ retstr << " "
62
+ i += 1
63
+ end
64
+
65
+ retstr << "}\n"
66
+ elsif argument.is_a?(String) or argument.is_a?(Integer) or argument.is_a?(Fixnum) or argument.is_a?(Float)
67
+ retstr << "#{argument}\n"
68
+ elsif argument.is_a?(Symbol)
69
+ retstr << ":#{argument.to_s}\n"
70
+ elsif argument.is_a?(Exception)
71
+ retstr << "#\{#{argument.class.to_s}: #{argument.message}}\n"
72
+ elsif cstr == "Thread"
73
+ retstr << "#{argument.class.name} - "
74
+
75
+ hash = {}
76
+ argument.keys.each do |key|
77
+ hash[key] = argument[key]
78
+ end
79
+
80
+ retstr << Php4r.print_r(hash, true, count).to_s
81
+ elsif cstr == "Class"
82
+ retstr << "#{argument.class.to_s} - "
83
+ hash = {"name" => argument.name}
84
+ retstr << Php4r.print_r(hash, true, count).to_s
85
+ elsif cstr == "URI::Generic"
86
+ retstr << "#{argument.class.to_s}{\n"
87
+ methods = [:host, :port, :scheme, :path]
88
+ count += 1
89
+ methods.each do |method|
90
+ i_spaces = 0
91
+ while i_spaces < count - 1
92
+ retstr << " "
93
+ i_spaces += 1
94
+ end
95
+
96
+ retstr << "#{method}: #{argument.send(method)}\n"
97
+ end
98
+
99
+ count -= 1
100
+
101
+ i = 0
102
+ while i < count - 1
103
+ retstr << " "
104
+ i += 1
105
+ end
106
+
107
+ retstr << "}\n"
108
+ elsif cstr == "Time" or cstr == "Datet"
109
+ argument = argument.time if cstr == "Datet"
110
+ retstr << "#{cstr}::#{"%04d" % argument.year}-#{"%02d" % argument.month}-#{"%02d" % argument.day} #{"%02d" % argument.hour}:#{"%02d" % argument.min}:#{"%02d" % argument.sec}\n"
111
+ elsif argument.respond_to?(:to_a)
112
+ retstr << "#{argument.class.name}{\n"
113
+
114
+ arr_count = 0
115
+ argument.to_a.each do |i|
116
+ i_spaces = 0
117
+ while i_spaces < count
118
+ retstr << " "
119
+ i_spaces += 1
120
+ end
121
+
122
+ retstr << "[#{arr_count}] => "
123
+ retstr << Php4r.print_r(i, true, count + 1).to_s
124
+ arr_count += 1
125
+ end
126
+
127
+ i_spaces = 0
128
+ while i_spaces < count - 1
129
+ retstr << " "
130
+ i_spaces += 1
131
+ end
132
+
133
+ retstr << "}\n"
134
+ else
135
+ #print argument.to_s, "\n"
136
+ retstr << "Unknown class: '#{cstr}' with superclass '#{supercl}'.\n"
137
+ end
138
+
139
+ if ret.is_a?(TrueClass)
140
+ return retstr
141
+ else
142
+ print retstr
143
+ end
144
+ end
145
+
146
+ def gtext(string)
147
+ return GetText._(string)
148
+ end
149
+
150
+ def gettext(string)
151
+ return GetText._(string)
152
+ end
153
+
154
+ #Returns the number as a formatted string.
155
+ def number_format(number, precision = 2, seperator = ".", delimiter = ",")
156
+ number = number.to_f if !number.is_a?(Float)
157
+ precision = precision.to_i
158
+ return sprintf("%.#{precision.to_s}f", number).gsub(".", seperator) if number < 1 and number > -1
159
+
160
+ number = sprintf("%.#{precision.to_s}f", number).split(".")
161
+
162
+ str = ""
163
+ number[0].reverse.scan(/(.{1,3})/) do |match|
164
+ if match[0] == "-"
165
+ #This happens if the number is a negative number and we have reaches the minus-sign.
166
+ str << match[0]
167
+ else
168
+ str << delimiter if str.length > 0
169
+ str << match[0]
170
+ end
171
+ end
172
+
173
+ str = str.reverse
174
+ if precision > 0
175
+ str << "#{seperator}#{number[1]}"
176
+ end
177
+
178
+ return str
179
+ end
180
+
181
+ def ucwords(string)
182
+ return string.to_s.split(" ").select{|w| w.capitalize! or w }.join(" ")
183
+ end
184
+
185
+ def strtoupper(str)
186
+ return str.to_s.upcase
187
+ end
188
+
189
+ def strtolower(str)
190
+ return str.to_s.downcase
191
+ end
192
+
193
+ def htmlspecialchars(string)
194
+ return string.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
195
+ end
196
+
197
+ def http_build_query(obj)
198
+ return self.http_build_query_rec("", obj)
199
+ end
200
+
201
+ def http_build_query_rec(orig_key, obj, first = true)
202
+ url = ""
203
+ first_ele = true
204
+
205
+ if obj.is_a?(Array)
206
+ ele_count = 0
207
+
208
+ obj.each do |val|
209
+ orig_key_str = "#{orig_key}[#{ele_count}]"
210
+ val = "#<Model::#{val.table}::#{val.id}>" if val.respond_to?("is_knj?")
211
+
212
+ if val.is_a?(Hash) or val.is_a?(Array)
213
+ url << self.http_build_query_rec(orig_key_str, val, false)
214
+ else
215
+ url << "&" if !first or !first_ele
216
+ url << "#{Php4r.urlencode(orig_key_str)}=#{Php4r.urlencode(val)}"
217
+ end
218
+
219
+ first_ele = false if first_ele
220
+ ele_count += 1
221
+ end
222
+ elsif obj.is_a?(Hash)
223
+ obj.each do |key, val|
224
+ if first
225
+ orig_key_str = key
226
+ else
227
+ orig_key_str = "#{orig_key}[#{key}]"
228
+ end
229
+
230
+ val = "#<Model::#{val.table}::#{val.id}>" if val.respond_to?("is_knj?")
231
+
232
+ if val.is_a?(Hash) or val.is_a?(Array)
233
+ url << self.http_build_query_rec(orig_key_str, val, false)
234
+ else
235
+ url << "&" if !first or !first_ele
236
+ url << "#{Php4r.urlencode(orig_key_str)}=#{Php4r.urlencode(val)}"
237
+ end
238
+
239
+ first_ele = false if first_ele
240
+ end
241
+ else
242
+ raise "Unknown class: '#{obj.class.name}'."
243
+ end
244
+
245
+ return url
246
+ end
247
+
248
+ def isset(var)
249
+ return false if var == nil or var == false
250
+ return true
251
+ end
252
+
253
+ def strpos(haystack, needle)
254
+ return false if !haystack
255
+ return false if !haystack.to_s.include?(needle)
256
+ return haystack.index(needle)
257
+ end
258
+
259
+ def substr(string, from, to = nil)
260
+ #If 'to' is not given it should be the total length of the string.
261
+ if to == nil
262
+ to = string.length
263
+ end
264
+
265
+ #The behaviour with a negative 'to' is not the same as in PHP. Hack it!
266
+ if to < 0
267
+ to = string.length + to
268
+ end
269
+
270
+ #Cut the string.
271
+ string = "#{string[from.to_i, to.to_i]}"
272
+
273
+ #Sometimes the encoding will no longer be valid. Fix that if that is the case.
274
+ if !string.valid_encoding? and Php4r.class_exists("Iconv")
275
+ string = Iconv.conv("UTF-8//IGNORE", "UTF-8", "#{string} ")[0..-2]
276
+ end
277
+
278
+ #Return the cut string.
279
+ return string
280
+ end
281
+
282
+ def md5(string)
283
+ require "digest"
284
+ return Digest::MD5.hexdigest(string.to_s)
285
+ end
286
+
287
+ def header(headerstr)
288
+ match = headerstr.to_s.match(/(.*): (.*)/)
289
+ if match
290
+ key = match[1]
291
+ value = match[2]
292
+ else
293
+ #HTTP/1.1 404 Not Found
294
+
295
+ match_status = headerstr.to_s.match(/^HTTP\/[0-9\.]+ ([0-9]+) (.+)$/)
296
+ if match_status
297
+ key = "Status"
298
+ value = match_status[1] + " " + match_status[2]
299
+ else
300
+ raise "Couldnt parse header."
301
+ end
302
+ end
303
+
304
+ _kas.header(key, value) #This is for knjAppServer - knj.
305
+ return true
306
+ end
307
+
308
+ def nl2br(string)
309
+ return string.to_s.gsub("\n", "<br />\n")
310
+ end
311
+
312
+ def urldecode(string)
313
+ #Thanks to CGI framework
314
+ str = string.to_s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/) do
315
+ [$1.delete('%')].pack('H*')
316
+ end
317
+ end
318
+
319
+ def urlencode(string)
320
+ #Thanks to CGI framework
321
+ string.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/) do
322
+ '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
323
+ end.tr(' ', '+')
324
+ end
325
+
326
+ def file_put_contents(filepath, content)
327
+ File.open(filepath.untaint, "w") do |file|
328
+ file.write(content)
329
+ end
330
+
331
+ return true
332
+ end
333
+
334
+ def file_get_contents(filepath)
335
+ filepath = filepath.to_s
336
+
337
+ if http_match = filepath.match(/^http(s|):\/\/([A-z_\d\.]+)(|:(\d+))(\/(.+))$/)
338
+ port = http_match[4].to_i if http_match[4].to_s.length > 0
339
+
340
+ args = {
341
+ :host => http_match[2]
342
+ }
343
+
344
+ if http_match[1] == "s"
345
+ args[:ssl] = true
346
+ args[:validate] = false
347
+
348
+ if !port
349
+ port = 443
350
+ end
351
+ end
352
+
353
+ args[:port] = port if port
354
+
355
+ require "http2"
356
+ Http2.new(args) do |http|
357
+ return http.get(http_match[5]).body
358
+ end
359
+ end
360
+
361
+ return File.read(filepath.untaint)
362
+ end
363
+
364
+ def is_file(filepath)
365
+ begin
366
+ if File.file?(filepath)
367
+ return true
368
+ end
369
+ rescue
370
+ return false
371
+ end
372
+
373
+ return false
374
+ end
375
+
376
+ def is_dir(filepath)
377
+ begin
378
+ return true if File.directory?(filepath)
379
+ rescue
380
+ return false
381
+ end
382
+
383
+ return false
384
+ end
385
+
386
+ def unlink(filepath)
387
+ FileUtils.rm(filepath)
388
+ end
389
+
390
+ def file_exists(filepath)
391
+ return true if File.exists?(filepath.to_s.untaint)
392
+ return false
393
+ end
394
+
395
+ def strtotime(date_string, cur = nil)
396
+ if !cur
397
+ cur = Time.new
398
+ else
399
+ cur = Time.at(cur)
400
+ end
401
+
402
+ date_string = date_string.to_s.downcase
403
+
404
+ if date_string.match(/[0-9]+-[0-9]+-[0-9]+/i)
405
+ begin
406
+ return Time.local(*ParseDate.parsedate(date_string)).to_i
407
+ rescue
408
+ return 0
409
+ end
410
+ end
411
+
412
+ date_string.scan(/((\+|-)([0-9]+) (\S+))/) do |match|
413
+ timestr = match[3]
414
+ number = match[2].to_i
415
+ mathval = match[1]
416
+ add = nil
417
+
418
+ if timestr == "years" or timestr == "year"
419
+ add = ((number.to_i * 3600) * 24) * 365
420
+ elsif timestr == "months" or timestr == "month"
421
+ add = ((number.to_i * 3600) * 24) * 30
422
+ elsif timestr == "weeks" or timestr == "week"
423
+ add = (number.to_i * 3600) * 24 * 7
424
+ elsif timestr == "days" or timestr == "day"
425
+ add = (number.to_i * 3600) * 24
426
+ elsif timestr == "hours" or timestr == "hour"
427
+ add = number.to_i * 3600
428
+ elsif timestr == "minutes" or timestr == "minute" or timestr == "min" or timestr == "mints"
429
+ add = number.to_i * 60
430
+ elsif timestr == "seconds" or timestr == "second" or timestr == "sec" or timestr == "secs"
431
+ add = number.to_i
432
+ end
433
+
434
+ if mathval == "+"
435
+ cur += add
436
+ elsif mathval == "-"
437
+ cur -= add
438
+ end
439
+ end
440
+
441
+ return cur.to_i
442
+ end
443
+
444
+ def class_exists(classname)
445
+ begin
446
+ Kernel.const_get(classname)
447
+ return true
448
+ rescue
449
+ return false
450
+ end
451
+ end
452
+
453
+ def html_entity_decode(string)
454
+ string = Php4r.htmlspecialchars(string)
455
+ string = string.gsub("&oslash;", "ø").gsub("&aelig;", "æ").gsub("&aring;", "å").gsub("&euro;", "€").gsub("#39;", "'").gsub("&amp;", "&").gsub("&gt;", ">").gsub("&lt;", "<").gsub("&quot;", '"').gsub("&#039;", "'")
456
+ return string
457
+ end
458
+
459
+ def strip_tags(htmlstr)
460
+ htmlstr.scan(/(<([\/A-z]+).*?>)/) do |match|
461
+ htmlstr = htmlstr.gsub(match[0], "")
462
+ end
463
+
464
+ return htmlstr.gsub("&nbsp;", " ")
465
+ end
466
+
467
+ def die(msg)
468
+ print msg
469
+ exit
470
+ end
471
+
472
+ def opendir(dirpath)
473
+ res = {:files => [], :index => 0}
474
+ Dir.foreach(dirpath) do |file|
475
+ res[:files] << file
476
+ end
477
+
478
+ return res
479
+ end
480
+
481
+ def readdir(res)
482
+ ret = res[:files][res[:index]] if res[:files].index(res[:index]) != nil
483
+ return false if !ret
484
+ res[:index] += 1
485
+ return ret
486
+ end
487
+
488
+ def fopen(filename, mode)
489
+ begin
490
+ return File.open(filename, mode)
491
+ rescue
492
+ return false
493
+ end
494
+ end
495
+
496
+ def fwrite(fp, str)
497
+ begin
498
+ fp.print str
499
+ rescue
500
+ return false
501
+ end
502
+
503
+ return true
504
+ end
505
+
506
+ def fputs(fp, str)
507
+ begin
508
+ fp.print str
509
+ rescue
510
+ return false
511
+ end
512
+
513
+ return true
514
+ end
515
+
516
+ def fread(fp, length = 4096)
517
+ return fp.read(length)
518
+ end
519
+
520
+ def fgets(fp, length = 4096)
521
+ return fp.read(length)
522
+ end
523
+
524
+ def fclose(fp)
525
+ fp.close
526
+ end
527
+
528
+ def move_uploaded_file(tmp_path, new_path)
529
+ FileUtils.mv(tmp_path.untaint, new_path.untaint)
530
+ end
531
+
532
+ def utf8_encode(str)
533
+ str = str.to_s if str.respond_to?("to_s")
534
+
535
+ if str.respond_to?("encode")
536
+ begin
537
+ return str.encode("iso-8859-1", "utf-8")
538
+ rescue Encoding::InvalidByteSequenceError
539
+ #ignore - try iconv
540
+ end
541
+ end
542
+
543
+ require "iconv"
544
+
545
+ begin
546
+ return Iconv.conv("iso-8859-1", "utf-8", str.to_s)
547
+ rescue
548
+ return Iconv.conv("iso-8859-1//ignore", "utf-8", "#{str} ").slice(0..-2)
549
+ end
550
+ end
551
+
552
+ def utf8_decode(str)
553
+ str = str.to_s if str.respond_to?(:to_s)
554
+ require "iconv" if RUBY_PLATFORM == "java" #This fixes a bug in JRuby where Iconv otherwise would not be detected.
555
+
556
+ if str.respond_to?(:encode)
557
+ begin
558
+ return str.encode("utf-8", "iso-8859-1")
559
+ rescue Encoding::InvalidByteSequenceError
560
+ #ignore - try iconv
561
+ end
562
+ end
563
+
564
+ require "iconv"
565
+
566
+ begin
567
+ return Iconv.conv("utf-8", "iso-8859-1", str.to_s)
568
+ rescue
569
+ return Iconv.conv("utf-8//ignore", "iso-8859-1", str.to_s)
570
+ end
571
+ end
572
+
573
+ def setcookie(cname, cvalue, expire = nil, domain = nil)
574
+ args = {
575
+ "name" => cname,
576
+ "value" => cvalue,
577
+ "path" => "/"
578
+ }
579
+ args["expires"] = Time.at(expire) if expire
580
+ args["domain"] = domain if domain
581
+
582
+ _kas.cookie(args)
583
+ return status
584
+ end
585
+
586
+ #This method is only here for convertion support - it doesnt do anything.
587
+ def session_start
588
+
589
+ end
590
+
591
+ def explode(expl, strexp)
592
+ return strexp.to_s.split(expl)
593
+ end
594
+
595
+ def dirname(filename)
596
+ File.dirname(filename)
597
+ end
598
+
599
+ def chdir(dirname)
600
+ Dir.chdir(dirname)
601
+ end
602
+
603
+ def include_once(filename)
604
+ require filename
605
+ end
606
+
607
+ def require_once(filename)
608
+ require filename
609
+ end
610
+
611
+ def echo(string)
612
+ print string
613
+ end
614
+
615
+ def count(array)
616
+ return array.length
617
+ end
618
+
619
+ def json_encode(obj)
620
+ if Php4r.class_exists("Rho")
621
+ return Rho::JSON.generate(obj)
622
+ elsif Php4r.class_exists("JSON")
623
+ return JSON.generate(obj)
624
+ else
625
+ raise "Could not figure out which JSON lib to use."
626
+ end
627
+ end
628
+
629
+ def json_decode(data, as_array = false)
630
+ #FIXME: Should be able to return as object, which will break all projects using it without second argument...
631
+ raise "String was not given to 'Php4r.json_decode'." if !data.is_a?(String)
632
+
633
+ if Php4r.class_exists("Rho")
634
+ return Rho::JSON.parse(data)
635
+ elsif Php4r.class_exists("JSON")
636
+ return JSON.parse(data)
637
+ else
638
+ raise "Could not figure out which JSON lib to use."
639
+ end
640
+ end
641
+
642
+ def time
643
+ return Time.now.to_i
644
+ end
645
+
646
+ def microtime(get_as_float = false)
647
+ microtime = Time.now.to_f
648
+
649
+ return microtime if get_as_float
650
+
651
+ splitted = microtime.to_s.split(",")
652
+ return "#{splitted[0]} #{splitted[1]}"
653
+ end
654
+
655
+ def mktime(hour = nil, min = nil, sec = nil, date = nil, month = nil, year = nil, is_dst = -1)
656
+ cur_time = Time.new
657
+
658
+ hour = cur_time.hour if hour == nil
659
+ min = cur_time.min if min == nil
660
+ sec = cur_time.sec if sec == nil
661
+ date = cur_time.day if date == nil
662
+ month = cur_time.month if month == nil
663
+ year = cur_time.year if year == nil
664
+
665
+ new_time = Datet.in("#{year.to_s}-#{month.to_s}-#{date.to_s} #{hour.to_s}:#{min.to_s}:#{sec.to_s}")
666
+ return new_time.to_i
667
+ end
668
+
669
+ def date(date_format, date_input = nil)
670
+ if date_input == nil
671
+ date_object = Time.now
672
+ elsif Php4r.is_numeric(date_input)
673
+ date_object = Time.at(date_input.to_i)
674
+ elsif date_input.is_a?(Datet)
675
+ date_object = date_input.time
676
+ elsif date_input.is_a?(Time)
677
+ date_object = date_input
678
+ else
679
+ raise "Unknown date given: '#{date_input}', '#{date_input.class.name}'."
680
+ end
681
+
682
+ date_format = date_format.gsub("Y", "%Y").gsub("y", "%y").gsub("m", "%m").gsub("d", "%d").gsub("H", "%H").gsub("i", "%M").gsub("s", "%S")
683
+ return date_object.strftime(date_format)
684
+ end
685
+
686
+ def basename(filepath)
687
+ splitted = filepath.to_s.split("/").last
688
+ return false if !splitted
689
+
690
+ ret = splitted.split(".")
691
+ ret.delete(ret.last)
692
+ return ret.join(".")
693
+ end
694
+
695
+ def base64_encode(str)
696
+ #The strict-encode wont do corrupt newlines...
697
+ if Base64.respond_to?("strict_encode64")
698
+ return Base64.strict_encode64(str.to_s)
699
+ else
700
+ return Base64.encode64(str.to_s)
701
+ end
702
+ end
703
+
704
+ def base64_decode(str)
705
+ return Base64.decode64(str.to_s)
706
+ end
707
+
708
+ def pathinfo(filepath)
709
+ filepath = filepath.to_s
710
+
711
+ dirname = File.dirname(filepath)
712
+ dirname = "" if dirname == "."
713
+
714
+ return {
715
+ "dirname" => dirname,
716
+ "basename" => self.basename(filepath),
717
+ "extension" => filepath.split(".").last,
718
+ "filename" => filepath.split("/").last
719
+ }
720
+ end
721
+
722
+ def realpath(pname)
723
+ require "pathname"
724
+
725
+ begin
726
+ return Pathname.new(pname.to_s).realpath.to_s
727
+ rescue => e
728
+ return false
729
+ end
730
+ end
731
+
732
+ # Returns the scripts current memory usage.
733
+ def memory_get_usage
734
+ # FIXME: This only works on Linux at the moment, since we are doing this by command line - knj.
735
+ memory_usage = `ps -o rss= -p #{Process.pid}`.to_i * 1024
736
+ return memory_usage
737
+ end
738
+
739
+ # Should return the peak usage of the running script, but I have found no way to detect this... Instead returns the currently memory usage.
740
+ def memory_get_peak_usage
741
+ return self.memory_get_usage
742
+ end
743
+
744
+ def ip2long(ip)
745
+ return IPAddr.new(ip).to_i
746
+ end
747
+
748
+ # Execute an external program and display raw output.
749
+ def passthru(cmd)
750
+ if RUBY_ENGINE == "jruby"
751
+ IO.popen4(cmd) do |pid, stdin, stdout, stderr|
752
+ tout = Thread.new do
753
+ begin
754
+ stdout.sync = true
755
+ stdout.each do |str|
756
+ $stdout.print str
757
+ end
758
+ rescue => e
759
+ $stderr.puts e.inspect
760
+ $stderr.puts e.backtrace
761
+ end
762
+ end
763
+
764
+ terr = Thread.new do
765
+ begin
766
+ stderr.sync = true
767
+ stderr.each do |str|
768
+ $stderr.print str
769
+ end
770
+ rescue => e
771
+ $stderr.puts e.inspect
772
+ $stderr.puts e.backtrace
773
+ end
774
+ end
775
+
776
+ tout.join
777
+ terr.join
778
+ end
779
+ else
780
+ require "open3"
781
+ Open3.popen3(cmd) do |stdin, stdout, stderr|
782
+ tout = Thread.new do
783
+ begin
784
+ stdout.sync = true
785
+ stdout.each do |str|
786
+ $stdout.print str
787
+ end
788
+ rescue => e
789
+ $stderr.puts e.inspect
790
+ $stderr.puts e.inspect
791
+ end
792
+ end
793
+
794
+ terr = Thread.new do
795
+ begin
796
+ stderr.sync = true
797
+ stderr.each do |str|
798
+ $stderr.print str
799
+ end
800
+ rescue => e
801
+ $stderr.puts e.inspect
802
+ $stderr.puts e.backtrace
803
+ end
804
+ end
805
+
806
+ tout.join
807
+ terr.join
808
+ end
809
+ end
810
+
811
+ return nil
812
+ end
813
+
814
+ # Thanks to this link for the following functions: http://snippets.dzone.com/posts/show/4509
815
+ def long2ip(long)
816
+ ip = []
817
+ 4.times do |i|
818
+ ip.push(long.to_i & 255)
819
+ long = long.to_i >> 8
820
+ end
821
+
822
+ ip.reverse.join(".")
823
+ end
824
+
825
+ def gzcompress(str, level = 3)
826
+ require "zlib"
827
+
828
+ zstream = Zlib::Deflate.new
829
+ gzip_str = zstream.deflate(str.to_s, Zlib::FINISH)
830
+ zstream.close
831
+
832
+ return gzip_str
833
+ end
834
+
835
+ def gzuncompress(str, length = 0)
836
+ require "zlib"
837
+
838
+ zstream = Zlib::Inflate.new
839
+ plain_str = zstream.inflate(str.to_s)
840
+ zstream.finish
841
+ zstream.close
842
+
843
+ return plain_str.to_s
844
+ end
845
+
846
+ #Sort methods.
847
+ def ksort(hash)
848
+ nhash = hash.sort do |a, b|
849
+ a[0] <=> b[0]
850
+ end
851
+
852
+ newhash = {}
853
+ nhash.each do |val|
854
+ newhash[val[0]] = val[1][0]
855
+ end
856
+
857
+ return newhash
858
+ end
859
+
860
+ #Foreach emulator.
861
+ def foreach(element, &block)
862
+ raise "No or unsupported block given." if !block.respond_to?(:call) or !block.respond_to?(:arity)
863
+ arity = block.arity
864
+ cname = element.class.name.to_s
865
+
866
+ if element.is_a?(Array) or cname == "Array_enumerator"
867
+ element.each_index do |key|
868
+ if arity == 2
869
+ block.call(key, element[key])
870
+ elsif arity == 1
871
+ block.call(element[key])
872
+ else
873
+ raise "Unknown arity: '#{arity}'."
874
+ end
875
+ end
876
+ elsif element.is_a?(Hash)
877
+ element.each do |key, val|
878
+ if arity == 2
879
+ block.call(key, val)
880
+ elsif arity == 1
881
+ block.call(val)
882
+ else
883
+ raise "Unknown arity: '#{arity}'."
884
+ end
885
+ end
886
+ else
887
+ raise "Unknown element: '#{element.class.name}'."
888
+ end
889
+ end
890
+
891
+ #Array-function emulator.
892
+ def array(*ele)
893
+ return {} if ele.length <= 0
894
+
895
+ if ele.length == 1 and ele.first.is_a?(Hash)
896
+ return ele.first
897
+ end
898
+
899
+ return ele
900
+ end
901
+
902
+ def array_key_exists(key, arr)
903
+ if arr.is_a?(Hash)
904
+ return arr.key?(key)
905
+ elsif arr.is_a?(Array)
906
+ return true if arr.index(key) != nil
907
+ return false
908
+ else
909
+ raise "Unknown type of argument: '#{arr.class.name}'."
910
+ end
911
+ end
912
+
913
+ def empty(obj)
914
+ if obj.respond_to?("empty?")
915
+ return obj.empty?
916
+ elsif obj == nil
917
+ return true
918
+ else
919
+ raise "Dont know how to handle object on 'empty': '#{obj.class.name}'."
920
+ end
921
+ end
922
+
923
+ def trim(argument)
924
+ return argument.to_s.strip
925
+ end
926
+
927
+ def serialize(argument)
928
+ require "php_serialize" #gem: php-serialize
929
+ return PHP.serialize(argument)
930
+ end
931
+
932
+ def unserialize(argument)
933
+ require "php_serialize" #gem: php-serialize
934
+ return PHP.unserialize(argument.to_s)
935
+ end
936
+
937
+ def parse_str(str, hash)
938
+ str.to_s.split("&").each do |value|
939
+ pos = value.index("=")
940
+
941
+ if pos != nil
942
+ name = value[0..pos-1]
943
+ valuestr = value.slice(pos+1..-1)
944
+ parse_str_name(hash, name, valuestr)
945
+ end
946
+ end
947
+
948
+ return hash
949
+ end
950
+
951
+ private
952
+
953
+ def self.parse_str_name(seton, varname, value)
954
+ if value.respond_to?(:filename) and value.filename
955
+ realvalue = value
956
+ else
957
+ realvalue = Php4r.urldecode(value.to_s)
958
+ end
959
+
960
+ if varname and varname.index("[") != nil and match = varname.match(/\[(.*?)\]/)
961
+ namepos = varname.index(match[0])
962
+ name = varname.slice(0..namepos - 1)
963
+ seton[name] = {} if !seton.key?(name)
964
+
965
+ secname, secname_empty = parse_str_secname(seton[name], match[1])
966
+
967
+ valuefrom = namepos + secname.to_s.length + 2
968
+ restname = varname.slice(valuefrom..-1)
969
+
970
+ if restname and restname.index("[") != nil
971
+ seton[name][secname] = {} if !seton[name].key?(secname)
972
+ parse_str_name_second(seton[name][secname], restname, value)
973
+ else
974
+ seton[name][secname] = realvalue
975
+ end
976
+ else
977
+ seton[varname] = realvalue
978
+ end
979
+ end
980
+
981
+ def self.parse_str_secname(seton, secname)
982
+ secname_empty = false
983
+ if secname.length <= 0
984
+ secname_empty = true
985
+ try = 0
986
+
987
+ loop do
988
+ if !seton.key?(try.to_s)
989
+ break
990
+ else
991
+ try += 1
992
+ end
993
+ end
994
+
995
+ secname = try.to_s
996
+ end
997
+
998
+ return [secname, secname_empty]
999
+ end
1000
+
1001
+ def self.parse_str_name_second(seton, varname, value)
1002
+ if value.respond_to?(:filename) and value.filename
1003
+ realvalue = value
1004
+ else
1005
+ realvalue = value.to_s
1006
+ end
1007
+
1008
+ match = varname.match(/^\[(.*?)\]/)
1009
+ if match
1010
+ namepos = varname.index(match[0])
1011
+ name = match[1]
1012
+ secname, secname_empty = parse_str_secname(seton, match[1])
1013
+
1014
+ valuefrom = namepos + match[1].length + 2
1015
+ restname = varname.slice(valuefrom..-1)
1016
+
1017
+ if restname and restname.index("[") != nil
1018
+ seton[secname] = {} if !seton.key?(secname)
1019
+ parse_str_name_second(seton[secname], restname, value)
1020
+ else
1021
+ seton[secname] = realvalue
1022
+ end
1023
+ else
1024
+ seton[varname] = realvalue
1025
+ end
1026
+ end
1027
+
1028
+ module_function(*instance_methods)
1029
+ end