Class: Knj::Web

Inherits:
Object show all
Defined in:
lib/knj/web.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Web

Returns a new instance of Web.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/knj/web.rb', line 4

def initialize(args = {})
  @args = Knj::ArrayExt.hash_sym(args)
  @db = @args[:db] if @args[:db] 
  @args[:tmp] = "/tmp" if !@args[:tmp]
  
  raise "No ID was given." if !@args[:id]
  raise "No DB was given." if !@args[:db]
  
  if @args[:cgi]
    @cgi = @args[:cgi]
  elsif $_CGI
    @cgi = $_CGI
  else
    if ENV["HTTP_HOST"] or $knj_eruby or Knj::Php.class_exists("Apache")
      @cgi = CGI.new
    end
  end
  
  $_CGI = @cgi if !$_CGI
  self.read_cgi
  
  if $_FCGI
    KnjEruby.connect("exit") do
      @session.close
      
      @post = nil
      @get = nil
      @server = nil
      @cookie = nil
      
      $_POST = nil
      $_GET = nil
      $_SERVER = nil
      $_COOKIE = nil
    end
  else
    Kernel.at_exit do
      @session.close
      
      @post = nil
      @get = nil
      @server = nil
      @cookie = nil
      
      $_POST = nil
      $_GET = nil
      $_SERVER = nil
      $_COOKIE = nil
    end
  end
end

Instance Attribute Details

#cgiObject (readonly)

Returns the value of attribute cgi.



2
3
4
# File 'lib/knj/web.rb', line 2

def cgi
  @cgi
end

#dataObject (readonly)

Returns the value of attribute data.



2
3
4
# File 'lib/knj/web.rb', line 2

def data
  @data
end

#sessionObject (readonly)

Returns the value of attribute session.



2
3
4
# File 'lib/knj/web.rb', line 2

def session
  @session
end

Class Method Details

.ahref_parse(str) ⇒ Object

Parses a string to be safe for use in <a href=“”>.



996
997
998
# File 'lib/knj/web.rb', line 996

def self.ahref_parse(str)
  return str.to_s.gsub("&", "&amp;")
end

.alert(string) ⇒ Object



381
382
383
384
385
386
# File 'lib/knj/web.rb', line 381

def self.alert(string)
  require "#{$knjpath}strings"
  @alert_sent = true
  html = "<script type=\"text/javascript\">alert(\"#{Knj::Strings.js_safe(string.to_s)}\");</script>"
  print html
end

.attr_html(attrs) ⇒ Object



454
455
456
457
458
459
460
461
462
463
# File 'lib/knj/web.rb', line 454

def self.attr_html(attrs)
  return "" if attrs.length <= 0
  
  html = ""
  attrs.each do |key, val|
    html << " #{key}=\"#{val.to_s.html}\""
  end
  
  return html
end

.backObject



406
407
408
409
# File 'lib/knj/web.rb', line 406

def self.back
  print "<script type=\"text/javascript\">history.go(-1);</script>"
  exit
end

.browser(servervar = nil) ⇒ Object



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
# File 'lib/knj/web.rb', line 778

def self.browser(servervar = nil)
  if !servervar
    begin
      servervar = _server
    rescue Exception => e
      servervar = $_SERVER
    end
  end
  
  raise "Could not figure out meta data." if !servervar
  agent = servervar["HTTP_USER_AGENT"].to_s.downcase
  
  if match = agent.index("knj:true") != nil
    browser = "bot"
    title = "Bot"
    version = "KnjHttp"
  elsif match = agent.match(/chrome\/(\d+\.\d+)/)
    browser = "chrome"
    title = "Google Chrome"
    version = match[1]
  elsif match = agent.match(/firefox\/(\d+\.\d+)/)
    browser = "firefox"
    title = "Mozilla Firefox"
    version = match[1]
  elsif match = agent.match(/msie\s*(\d+\.\d+)/)
    browser = "ie"
    title = "Microsoft Internet Explorer"
    version = match[1]
  elsif match = agent.match(/opera\/([\d+\.]+)/)
    browser = "opera"
    title = "Opera"
    version = match[1]
  elsif match = agent.match(/wget\/([\d+\.]+)/)
    browser = "bot"
    title = "Bot"
    version = "Wget #{match[1]}"
  elsif agent.index("baiduspider") != nil
    browser = "bot"
    title = "Bot"
    version = "Baiduspider"
  elsif agent.index("googlebot") != nil
    browser = "bot"
    title = "Bot"
    version = "Googlebot"
  elsif agent.index("gidbot") != nil
    browser = "bot"
    title = "Bot"
    version = "GIDBot"
  elsif match = agent.match(/android\s+([\d\.]+)/)
    browser = "android"
    title = "Android"
    version = match[1]
  elsif match = agent.match(/safari\/(\d+)/)
    browser = "safari"
    title = "Safari"
    version = match[1]
  elsif agent.index("iPad") != nil
    browser = "safari"
    title = "Safari (iPad)"
    version = "ipad"
  elsif agent.index("bingbot") != nil
    browser = "bot"
    title = "Bot"
    version = "Bingbot"
  elsif agent.index("yahoo! slurp") != nil
    browser = "bot"
    title = "Bot"
    version = "Yahoo! Slurp"
  elsif agent.index("hostharvest") != nil
    browser = "bot"
    title = "Bot"
    version = "HostHarvest"
  elsif agent.index("exabot") != nil
    browser = "bot"
    title = "Bot"
    version = "Exabot"
  elsif agent.index("dotbot") != nil
    browser = "bot"
    title = "Bot"
    version = "DotBot"
  elsif agent.index("msnbot") != nil
    browser = "bot"
    title = "Bot"
    version = "MSN bot"
  elsif agent.index("yandexbot") != nil
    browser = "bot"
    title = "Bot"
    version = "Yandex Bot"
  elsif agent.index("mj12bot") != nil
    browser = "bot"
    title = "Bot"
    version = "Majestic12 Bot"
  elsif agent.index("facebookexternalhit") != nil
    browser = "bot"
    title = "Bot"
    version = "Facebook Externalhit"
  elsif agent.index("sitebot") != nil
    browser = "bot"
    title = "Bot"
    version = "SiteBot"
  elsif match = agent.match(/java\/([\d\.]+)/)
    browser = "bot"
    title = "Java"
    version = match[1]
  elsif match = agent.match(/ezooms\/([\d\.]+)/)
    browser = "bot"
    title = "Ezooms"
    version = match[1]
  elsif match = agent.match(/ahrefsbot\/([\d\.]+)/)
    browser = "bot"
    title = "AhrefsBot"
    version = match[1]
  else
    browser = "unknown"
    title = "(unknown browser)"
    version = "(unknown version)"
  end
  
  return {
    "browser" => browser,
    "title" => title,
    "version" => version
  }
end

.checkval(value, val1, val2 = nil) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/knj/web.rb', line 411

def self.checkval(value, val1, val2 = nil)
  if val2 != nil
    if !value or value == "" or value == "false"
      return val2
    else
      return val1
    end
  else
    if !value or value == "" or value == "false"
      return val1
    else
      return value
    end
  end
end


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/knj/web.rb', line 246

def self.cookie_str(cookie_data)
  raise "Not a hash: '#{cookie_data.class.name}', '#{cookie_data}'." unless cookie_data.is_a?(Hash)
  cookiestr = "#{self.urlenc(cookie_data["name"])}=#{self.urlenc(cookie_data["value"])}"
  
  cookie_data.each do |key, val|
    next if key == "name" or key == "value"
    
    if key.to_s.downcase == "expires" and val.is_a?(Time)
      cookiestr << "; Expires=#{val.httpdate}"
    else
      cookiestr << "; #{key}=#{val}"
    end
  end
  
  return cookiestr
end

.hiddens(hidden_arr) ⇒ Object



968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
# File 'lib/knj/web.rb', line 968

def self.hiddens(hidden_arr)
  html = ""
  
  hidden_arr.each do |hidden_hash|
    if hidden_hash.is_a?(Array)
      hidden_hash = {
        :name => hidden_hash[0],
        :value => hidden_hash[1]
      }
    else
      if hidden_hash[:value].is_a?(Array)
        if !hidden_hash[:value][0]
          hidden_hash[:value] = nil
        else
          key = hidden_hash[:value][1]
          obj = hidden_hash[:value][0]
          hidden_hash[:value] = obj[key]
        end
      end
    end
    
    html << "<input type=\"hidden\" name=\"#{hidden_hash[:name].to_s.html}\" value=\"#{hidden_hash[:value].to_s.html}\" />"
  end
  
  return html
end

.html(string) ⇒ Object

Escapes HTML-characters in a string.



1017
1018
1019
# File 'lib/knj/web.rb', line 1017

def self.html(string)
  return string.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
end

.html_args(h) ⇒ Object



1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/knj/web.rb', line 1021

def self.html_args(h)
  str = ""
  h.each do |key, val|
    str << "&#{Knj::Php.urlencode(key)}=#{Knj::Php.urlencode(val)}"
  end
  
  return str
end

.input(args) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/knj/web.rb', line 465

def self.input(args)
  Knj::ArrayExt.hash_sym(args)
  
  if args.key?(:value)
    if args[:value].is_a?(Array) and args[:value].first.is_a?(NilClass)
      value = nil
    elsif args[:value].is_a?(Array)
      if !args[:value][2] or args[:value][2] == :key
        value = args[:value].first[args[:value][1]]
      elsif args[:value][2] == :callb
        value = args[:value].first.send(args[:value][1])
      else
        value = args[:value]
      end
    elsif args[:value].is_a?(String) or args[:value].is_a?(Integer)
      value = args[:value].to_s
    else
      value = args[:value]
    end
  end
  
  args[:value_default] = args[:default] if args[:default]
  
  if value.is_a?(NilClass) and args[:value_default]
    value = args[:value_default]
  elsif value.is_a?(NilClass)
    value = ""
  end
  
  if value and args.key?(:value_func) and args[:value_func]
    cback = args[:value_func]
    
    if cback.is_a?(Method)
      value = cback.call(value)
    elsif cback.is_a?(Array)
      value = Knj::Php.call_user_func(args[:value_func], value)
    elsif cback.is_a?(Proc)
      value = cback.call(value)
    else
      raise "Unknown class: #{cback.class.name}."
    end
  end
  
  value = args[:values] if args[:values]
  args[:id] = args[:name] if !args[:id]
  
  if !args[:type]
    if args[:opts]
      args[:type] = :select
    elsif args[:name] and args[:name].to_s[0..2] == "che"
      args[:type] = :checkbox
    elsif args[:name] and args[:name].to_s[0..3] == "file"
      args[:type] = :file
    else
      args[:type] = :text
    end
  else
    args[:type] = args[:type].to_sym
  end
  
  attr = {
    "name" => args[:name],
    "id" => args[:id],
    "type" => args[:type],
    "class" => "input_#{args[:type]}"
  }
  attr.merge!(args[:attr]) if args[:attr]
  attr["disabled"] = "disabled" if args[:disabled]
  
  raise "No name given to the Web::input()-method." if !args[:name] and args[:type] != :info and args[:type] != :textshow and args[:type] != :plain and args[:type] != :spacer and args[:type] != :headline
  
  css = {}
  css["text-align"] = args[:align] if args.key?(:align)
  css.merge!(args[:css]) if args.key?(:css)
  
  attr_keys = [:onchange]
  attr_keys.each do |tag|
    if args.key?(tag)
      attr[tag] = args[tag]
    end
  end
  
  classes_tr = []
  classes_tr += args[:classes_tr] if args[:classes_tr]
  
  if !classes_tr.empty?
    classes_tr_html = " class=\"#{classes_tr.join(" ")}\""
  else
    classes_tr_html = ""
  end
  
  html = ""
  
  classes = ["input_#{args[:type]}"]
  classes = classes | args[:classes] if args.key?(:classes)
  attr["class"] = classes.join(" ")
  
  if args[:type] == :checkbox
    attr["value"] = args[:value_active] if args.key?(:value_active)
    attr["checked"] = "checked" if value.is_a?(String) and value == "1" or value.to_s == "1" or value.to_s == "on" or value.to_s == "true"
    attr["checked"] = "checked" if value.is_a?(TrueClass)
    
    html << "<tr#{classes_tr_html}>"
    html << "<td colspan=\"2\" class=\"tdcheck\">"
    html << "<input#{self.attr_html(attr)} />"
    html << "<label for=\"#{args[:id].html}\">#{args[:title].html}</label>"
    html << "</td>"
    html << "</tr>"
  elsif args[:type] == :headline
    html << "<tr#{classes_tr_html}><td colspan=\"2\"><h2 class=\"input_headline\">#{args[:title].html}</h2></td></tr>"
  elsif args[:type] == :spacer
    html << "<tr#{classes_tr_html}><td colspan=\"2\">&nbsp;</td></tr>"
  else
    html << "<tr#{classes_tr_html}>"
    html << "<td class=\"tdt\">"
    html << args[:title].to_s.html
    html << "</td>"
    html << "<td#{self.style_html(css)} class=\"tdc\">"
    
    if args[:type] == :textarea
      if args.key?(:height)
        if Knj::Php.is_numeric(args[:height])
          css["height"] = "#{args[:height]}px"
        else
          css["height"] = args[:height]
        end
      end
      
      html << "<textarea#{self.style_html(css)} class=\"input_textarea\" name=\"#{args[:name].html}\" id=\"#{args[:id].html}\">#{value}</textarea>"
      html << "</td>"
    elsif args[:type] == :fckeditor
      args[:height] = 400 if !args[:height]
      
      require "/usr/share/fckeditor/fckeditor.rb"
      fck = FCKeditor.new(args[:name])
      fck.Height = args[:height].to_i
      fck.Value = value
      html << fck.CreateHtml
      
      html << "</td>"
    elsif args[:type] == :select
      attr["multiple"] = "multiple" if args[:multiple]
      attr["size"] = args["size"] if args[:size]
      
      html << "<select#{self.attr_html(attr)}>"
      html << Knj::Web.opts(args[:opts], value, args[:opts_args])
      html << "</select>"
      html << "</td>"
    elsif args[:type] == :imageupload
      html << "<table class=\"designtable\"><tr#{classes_tr_html}><td style=\"width: 100%;\">"
      html << "<input type=\"file\" name=\"#{args[:name].html}\" class=\"input_file\" />"
      html << "</td><td style=\"padding-left: 5px;\">"
      
      raise "No path given for imageupload-input." if !args.key?(:path)
      raise "No value given in arguments for imageupload-input." if !args.key?(:value)
      
      path = args[:path].gsub("%value%", value.to_s).untaint
      if File.exists?(path)
        html << "<img src=\"image.rhtml?path=#{self.urlenc(path).html}&smartsize=100&rounded_corners=10&border_color=black&force=true&ts=#{Time.new.to_f}\" alt=\"Image\" />"
        
        if args[:dellink]
          dellink = args[:dellink].gsub("%value%", value.to_s)
          html << "<div style=\"text-align: center;\">(<a href=\"javascript: if (confirm('#{_("Do you want to delete the image?")}')){location.href='#{dellink}';}\">#{_("delete")}</a>)</div>"
        end
      end
      
      html << "</td></tr></table>"
      html << "</td>"
    elsif args[:type] == :file
      html << "<input type=\"#{args[:type].to_s}\" class=\"input_#{args[:type].to_s}\" name=\"#{args[:name].html}\" /></td>"
    elsif args[:type] == :textshow or args[:type] == :info
      html << "#{value}</td>"
    elsif args[:type] == :plain
      html << "#{Knj::Php.nl2br(Knj::Web.html(value))}"
    elsif args[:type] == :editarea
      css["width"] = "100%"
      css["height"] = args[:height] if args.key?(:height)
      html << "<textarea#{self.attr_html(attr)}#{self.style_html(css)} id=\"#{args[:id]}\" name=\"#{args[:name]}\">#{value}</textarea>"
      
      jshash = {
        "id" => args[:id],
        "start_highlight" => true
      }
      
      pos_keys = [:skip_init, :allow_toggle, :replace_tab_by_spaces, :toolbar, :syntax]
      pos_keys.each do |key|
        jshash[key.to_s] = args[key] if args.key?(key)
      end
      
      html << "<script type=\"text/javascript\">"
      html << "function knj_web_init_#{args[:name]}(){"
      html << "editAreaLoader.init(#{Knj::Php.json_encode(jshash)});"
      html << "}"
      html << "</script>"
    else
      attr[:value] = value
      html << "<input#{self.attr_html(attr)} /></td>"
      html << "</td>"
    end
    
    html << "</tr>"
  end
  
  html << "<tr#{classes_tr_html}><td colspan=\"2\" class=\"tdd\">#{args[:descr]}</td></tr>" if args[:descr]
  return html
end

.inputs(arr) ⇒ Object



427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/knj/web.rb', line 427

def self.inputs(arr)
  html = ""
  arr.each do |args|
    if RUBY_ENGINE == "rbx"
      html << self.input(args).to_s.encode(html.encoding)
    else
      html << self.input(args)
    end
  end
  
  return html
end

.locale(args = {}) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/knj/web.rb', line 903

def self.locale(args = {})
  begin
    servervar = _server
  rescue Exception
    servervar = $_SERVER
  end
  
  if !servervar
    raise "Could not figure out meta data."
  end
  
  ret = {
    :recommended => [],
    :browser => []
  }
  
  alangs = servervar["HTTP_ACCEPT_LANGUAGE"].to_s
  if alangs.length > 0
    alangs.split(/\s*,\s*/).each do |alang|
      if qmatch = alang.match(/;\s*q=([\d\.]+)/)
        alang.gsub!(/;\s*q=([\d\.]+)/, "")
        q = qmatch[1].to_f
      else
        q = 1.0
      end
      
      if match = alang.match(/^([A-z]+)-([A-z]+)$/)
        locale = match[1]
        sublocale = match[2]
      else
        locale = alang
        sublocale = false
      end
      
      ret[:browser] << {
        :locale => locale,
        :sublocale => sublocale,
        :q => q
      }
    end
  end
  
  if args[:supported] and ret[:browser]
    ret[:browser].each do |locale|
      args[:supported].each do |supported_locale|
        if match = supported_locale.match(/^([A-z]+)_([A-z]+)$/)
          if match[1] == locale[:locale]
            if !locale[:sublocale]
              ret[:recommended] << supported_locale if ret[:recommended].index(supported_locale) == nil
            elsif locale[:sublocale] == match[1]
              ret[:recommended] << supported_locale if ret[:recommended].index(supported_locale) == nil
            end
          end
        end
      end
    end
  end
  
  if args[:default]
    ret[:recommended] << args[:default] if ret[:recommended].index(args[:default]) == nil
  end
  
  return ret
end

.opts(opthash, curvalue = nil, opts_args = {}) ⇒ Object



672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/knj/web.rb', line 672

def self.opts(opthash, curvalue = nil, opts_args = {})
  opts_args = {} if !opts_args
  opts_args.each do |key, value|
    if !key.is_a?(Symbol)
      opts_args[key.to_sym] = value
      opts_args.delete(key)
    end
  end
  
  return "" if !opthash
  cname = curvalue.class.name
  curvalue = curvalue.id if (cname == "Knj::Db_row" or cname == "Knj::Datarow")
  
  html = ""
  addsel = " selected=\"selected\"" if !curvalue
  
  html << "<option#{addsel} value=\"\">#{_("Add new")}</option>" if opts_args and (opts_args[:add] or opts_args[:addnew])
  html << "<option#{addsel} value=\"\">#{_("Choose")}</option>" if opts_args and opts_args[:choose]
  html << "<option#{addsel} value=\"\">#{_("None")}</option>" if opts_args and opts_args[:none]
  html << "<option#{addsel} value=\"\">#{_("All")}</option>" if opts_args and opts_args[:all]
  
  if opthash.is_a?(Hash) or opthash.class.to_s == "Dictionary"
    opthash.each do |key, value|
      html << "<option"
      
      sel = false
      
      if curvalue.is_a?(Array) and curvalue.index(key) != nil
        sel = true
      elsif curvalue.to_s == key.to_s
        sel = true
      elsif curvalue and curvalue.respond_to?(:is_knj?) and curvalue.id.to_s == key.to_s
        sel = true
      end
      
      html << " selected=\"selected\"" if sel
      html << " value=\"#{Knj::Web.html(key)}\">#{Knj::Web.html(value)}</option>"
    end
  elsif opthash.is_a?(Array)
    opthash.each_index do |key|
      if opthash[key.to_i] != nil
        html << "<option"
        html << " selected=\"selected\"" if curvalue.to_i == key.to_i
        html << " value=\"#{key.to_s}\">#{opthash[key].to_s}</option>"
      end
    end
  end
  
  return html
end

.osObject



750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/knj/web.rb', line 750

def self.os
  begin
    servervar = _server
  rescue Exception
    servervar = $_SERVER
  end
  
  if !servervar
    raise "Could not figure out meta data."
  end
  
  agent = servervar["HTTP_USER_AGENT"].to_s.downcase
  
  if agent.index("(windows;") != nil or agent.index("windows nt") != nil
    return {
      "os" => "win",
      "title" => "Windows"
    }
  elsif agent.index("linux") != nil
    return {
      "os" => "linux",
      "title" => "Linux"
    }
  end
  
  raise "Unknown OS: #{agent}"
end

.parse_cookies(str) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/knj/web.rb', line 211

def self.parse_cookies(str)
  ret = {}
  
  str.split(/;\s*/).each do |cookie_str|
    if !match = cookie_str.match(/^(.*?)=\"(.*)\"$/)
      match = cookie_str.match(/^(.*?)=(.*)$/)
    end
    
    ret[self.urldec(match[1])] = self.urldec(match[2]) if match
  end
  
  return ret
end

.parse_name(seton, varname, value, args = {}) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/knj/web.rb', line 300

def self.parse_name(seton, varname, value, args = {})
  if value.respond_to?(:filename) and value.filename
    realvalue = value
  else
    realvalue = value.to_s
    realvalue = self.urldec(realvalue) if args[:urldecode]
    realvalue = realvalue.force_encoding("utf-8") if args[:force_utf8] if realvalue.respond_to?(:force_encoding)
  end
  
  if varname and varname.index("[") != nil and match = varname.match(/\[(.*?)\]/)
    namepos = varname.index(match[0])
    name = varname.slice(0..namepos - 1)
    name = name.to_sym if args[:syms]
    seton[name] = {} if !seton.key?(name)
    
    secname, secname_empty = Knj::Web.parse_secname(seton[name], match[1], args)
    
    valuefrom = namepos + secname.to_s.length + 2
    restname = varname.slice(valuefrom..-1)
    
    if restname and restname.index("[") != nil
      seton[name][secname] = {} if !seton[name].key?(secname)
      Knj::Web.parse_name_second(seton[name][secname], restname, value, args)
    else
      seton[name][secname] = realvalue
    end
  else
    seton[varname] = realvalue
  end
end

.parse_name_second(seton, varname, value, args = {}) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/knj/web.rb', line 331

def self.parse_name_second(seton, varname, value, args = {})
  if value.respond_to?(:filename) and value.filename
    realvalue = value
  else
    realvalue = value.to_s
    realvalue = realvalue.force_encoding("utf-8") if args[:force_utf8]
  end
  
  match = varname.match(/^\[(.*?)\]/)
  if match
    namepos = varname.index(match[0])
    name = match[1]
    secname, secname_empty = Knj::Web.parse_secname(seton, match[1], args)
    
    valuefrom = namepos + match[1].length + 2
    restname = varname.slice(valuefrom..-1)
    
    if restname and restname.index("[") != nil
      seton[secname] = {} if !seton.key?(secname)
      Knj::Web.parse_name_second(seton[secname], restname, value, args)
    else
      seton[secname] = realvalue
    end
  else
    seton[varname] = realvalue
  end
end

.parse_secname(seton, secname, args) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/knj/web.rb', line 279

def self.parse_secname(seton, secname, args)
  secname_empty = false
  if secname.length <= 0
    secname_empty = true
    try = 0
    
    loop do
      if !seton.key?(try.to_s)
        break
      else
        try += 1
      end
    end
    
    secname = try.to_s
  end
  
  secname = secname.to_sym if args[:syms] and secname.is_a?(String) and !Knj::Php.is_numeric(secname)
  return [secname, secname_empty]
end

.parse_set_cookies(str) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/knj/web.rb', line 225

def self.parse_set_cookies(str)
  str = String.new(str.to_s)
  return [] if str.length <= 0
  args = {}
  cookie_start_regex = /^(.+?)=(.*?)(;\s*|$)/
  
  match = str.match(cookie_start_regex)
  raise "Could not match cookie: '#{str}'." if !match
  str.gsub!(cookie_start_regex, "")
  
  args["name"] = self.urldec(match[1].to_s)
  args["value"] = self.urldec(match[2].to_s)
  
  while match = str.match(/(.+?)=(.*?)(;\s*|$)/)
    str = str.gsub(match[0], "")
    args[match[1].to_s.downcase] = match[2].to_s
  end
  
  return [args]
end

.parse_urlquery(querystr, args = {}) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/knj/web.rb', line 263

def self.parse_urlquery(querystr, args = {})
  get = {}
  querystr.to_s.split("&").each do |value|
    pos = value.index("=")
    
    if pos != nil
      name = value[0..pos-1]
      name = name.to_sym if args[:syms]
      valuestr = value.slice(pos+1..-1)
      Knj::Web.parse_name(get, self.urldec(name), valuestr, args)
    end
  end
  
  return get
end

.redirect(string, args = {}) ⇒ Object



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/knj/web.rb', line 388

def self.redirect(string, args = {})
  do_js = true
  
  #Header way
  if !@alert_sent
    if args[:perm]
      Knj::Php.header("Status: 301 Moved Permanently")
    else
      Knj::Php.header("Status: 303 See Other")
    end
    
    Knj::Php.header("Location: #{string}")
  end
  
  print "<script type=\"text/javascript\">location.href=\"#{string}\";</script>" if do_js
  exit
end

.rendering_engineObject



723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'lib/knj/web.rb', line 723

def self.rendering_engine
  begin
    servervar = _server
  rescue Exception
    servervar = $_SERVER
  end
  
  if !servervar
    raise "Could not figure out meta data."
  end
  
  agent = servervar["HTTP_USER_AGENT"].to_s.downcase
  
  if agent.index("webkit") != nil
    return "webkit"
  elsif agent.index("gecko") != nil
    return "gecko"
  elsif agent.index("msie") != nil
    return "msie"
  elsif agent.index("w3c") != nil or agent.index("baiduspider") != nil or agent.index("googlebot") != nil
    return "bot"
  else
    #print "Unknown agent: #{agent}"
    return false
  end
end

.require_eruby(filepath) ⇒ Object



375
376
377
378
379
# File 'lib/knj/web.rb', line 375

def self.require_eruby(filepath)
  cont = File.read(filepath).untaint
  parse = Erubis.Eruby.new(cont)
  eval(parse.src.to_s)
end

.style_html(css) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/knj/web.rb', line 440

def self.style_html(css)
  return "" if css.length <= 0
  
  str = " style=\""
  
  css.each do |key, val|
    str << "#{key}: #{val};"
  end
  
  str << "\""
  
  return str
end

.url(args = {}) ⇒ Object

Calculates the URL from meta hash.



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# File 'lib/knj/web.rb', line 1031

def self.url(args = {})
  if args[:meta]
    meta = args[:meta]
  else
    meta = _meta
  end
  
  url = ""
  
  if meta["HTTP_SSL_ENABLED"] == "1"
    url << "https://"
  else
    url << "http://"
  end
  
  url << meta["HTTP_HOST"]
  url << meta["REQUEST_URI"] if !args.key?(:uri) or args[:uri]
  
  return url
end

.urldec(string) ⇒ Object

URL-decodes a string.



1009
1010
1011
1012
1013
1014
# File 'lib/knj/web.rb', line 1009

def self.urldec(string)
  #Thanks to CGI framework
  str = string.to_s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/) do
    [$1.delete('%')].pack('H*')
  end
end

.urlenc(string) ⇒ Object

URL-encodes a string.



1001
1002
1003
1004
1005
1006
# File 'lib/knj/web.rb', line 1001

def self.urlenc(string)
  #Thanks to CGI framework
  string.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/) do
    '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
  end.tr(' ', '+')
end

Instance Method Details

#[](key) ⇒ Object



203
204
205
# File 'lib/knj/web.rb', line 203

def [](key)
  return @session[key.to_sym]
end

#[]=(key, value) ⇒ Object



207
208
209
# File 'lib/knj/web.rb', line 207

def []=(key, value)
  return @session[key.to_sym] = value
end

#destroyObject



367
368
369
370
371
372
373
# File 'lib/knj/web.rb', line 367

def destroy
  @cgi = nil
  @post = nil
  @get = nil
  @session = nil
  @args = nil
end

#global_paramsObject



359
360
361
362
363
364
365
# File 'lib/knj/web.rb', line 359

def global_params
  $_POST = @post
  $_GET = @get
  $_COOKIE = @cookie
  $_FILES = @files
  $_SERVER = @server
end

#read_cgi(args = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/knj/web.rb', line 56

def read_cgi(args = {})
  args.each do |key, value|
    if key == :cgi
      @cgi = value
    else
      raise "No such key: #{key.to_s}"
    end
  end
  
  if $_FCGI_COUNT and $_FCGI and $_CGI
    @server = {}
    $_CGI.env_table.each do |key, value|
      @server[key] = value
    end
  elsif $_CGI and ENV["HTTP_HOST"] and ENV["REMOTE_ADDR"]
    @server = {}
    ENV.each do |key, value|
      @server[key] = value
    end
  elsif Knj::Php.class_exists("Apache")
    @server = {
      "HTTP_HOST" => Apache.request.hostname,
      "HTTP_USER_AGENT" => Apache.request.headers_in["User-Agent"],
      "REMOTE_ADDR" => Apache.request.remote_host(1),
      "REQUEST_URI" => Apache.request.unparsed_uri
    }
  else
    @server = {}
  end
  
  @files = {}
  @post = {}
  if @cgi and @cgi.request_method == "POST"
    @cgi.params.each do |pair|
      do_files = false
      isstring = true
      varname = pair[0]
      stringparse = nil
      
      if pair[1][0].class.name == "Tempfile"
        if varname[0..3] == "file"
          isstring = false
          do_files = true
          
          if pair[1][0].size > 0
            stringparse = {
              "name" => pair[1][0].original_filename,
              "tmp_name" => pair[1][0].path,
              "size" => pair[1][0].size,
              "error" => 0
            }
            
            stringparse["name"] = pair[1][0].original_filename if pair[1][0].respond_to?("original_filename")
          end
        else
          stringparse = File.read(pair[1][0].path)
        end
      elsif pair[1][0].is_a?(StringIO)
        if varname[0..3] == "file"
          tmpname = @args[:tmp] + "/knj_web_upload_#{Time.now.to_f.to_s}_#{rand(1000).to_s.untaint}"
          isstring = false
          do_files = true
          cont = pair[1][0].string
          Knj::Php.file_put_contents(tmpname, cont.to_s)
          
          if cont.length > 0
            stringparse = {
              "tmp_name" => tmpname,
              "size" => cont.length,
              "error" => 0
            }
            
            stringparse["name"] = pair[1][0].original_filename if pair[1][0].respond_to?("original_filename")
          end
        else
          stringparse = pair[1][0].string
        end
      else
        stringparse = pair[1][0]
      end
      
      if stringparse
        if !do_files
          if isstring
            Knj::Web.parse_name(@post, varname, stringparse)
          else
            @post[varname] = stringparse
          end
        else
          if isstring
            Knj::Web.parse_name(@files, varname, stringparse)
          else
            @files[varname] = stringparse
          end
        end
      end
    end
  end
  
  
  if @cgi and @cgi.query_string
    @get = Knj::Web.parse_urlquery(@cgi.query_string)
  else
    @get = {}
  end
  
  @cookie = {}
  if @cgi
    @cgi.cookies.each do |key, value|
      @cookie[key] = value[0]
    end
  end
  
  self.global_params if @args[:globals]
  
  if @cookie[@args[:id]] and (sdata = @args[:db].single(:sessions, :id => @cookie[@args[:id]]))
    @data = Knj::ArrayExt.hash_sym(sdata)
    
    if @data
      if @data[:user_agent] != @server["HTTP_USER_AGENT"] or @data[:ip] != @server["REMOTE_ADDR"]
        @data = nil
      else
        @db.update(:sessions, {"last_url" => @server["REQUEST_URI"].to_s, "date_active" => Time.new}, {"id" => @data[:id]})
        session_id = @args[:id] + "_" + @data[:id]
      end
    end
  end
  
  if !@data or !session_id
    @db.insert(:sessions,
      :date_start => Time.new,
      :date_active => Time.new,
      :user_agent => @server["HTTP_USER_AGENT"],
      :ip => @server["REMOTE_ADDR"],
      :last_url => @server["REQUEST_URI"].to_s
    )
    
    @data = Knj::ArrayExt.hash_sym(@db.single(:sessions, :id => @db.last_id))
    session_id = @args[:id] + "_" + @data[:id]
    Knj::Php.setcookie(@args[:id], @data[:id])
  end
  
  require "cgi/session"
  require "cgi/session/pstore"
  @session = CGI::Session.new(@session, "database_manager" => CGI::Session::PStore, "session_id" => session_id, "session_path" => @args[:tmp])
end