%
# vim:set ts=2 sts=2 sw=2 bs=2 ai si et nu ff=dos ft=ruby:
# $Id$
$KCODE = "utf"
ERuby::charset = "utf-8"
_lib = File::dirname(ENV["SCRIPT_FILENAME"].split(/\/html\//)[1]).untaint
load "../../cgi-bin/#{_lib}/loader.rb".untaint
load "../../cgi-bin/#{_lib}/lib/ssi2.rb".untaint
load "../../cgi-bin/#{_lib}/lib/counter.rb".untaint
# カウンター
def make_counter(eb, counter, order, off = false)
  counter.total=order[:total]
  counter.start=order[:start]
  off_counter = 0
  counter.format.each do |_i,_j|
    if _i != counter.now
      order[:counter] << sprintf(
        %[%s ], 
        _j, 
        order[:argv].size.nonzero? ? "&" + order[:argv].join("&") : "",
        _i
      )
    else
      order[:counter] << sprintf(%[%s ], _i)
    end
    off_counter += 1
  end
  if off and off_counter == 1
    order[:counter] = ""
  end
  if counter.now != 1 and counter.count.nonzero?
    order[:prev] = sprintf(
      %[前へ ], 
      counter.now - 2,
      order[:argv].size.nonzero? ? "&" + order[:argv].join("&") : ""
    )
  end
  if counter.now != counter.count
    order[:next] = sprintf(
      %[次へ ], 
      counter.now,
      order[:argv].size.nonzero? ? "&" + order[:argv].join("&") : ""
    )
  end
  order
end
def make_cal(eb, date, days = [], selected = 0)
  cal = Array::new
  _today = Date::today
  cal << %[
]
  (0..6).each do |_i|
    _class = ""
    _class = "sunday" if _i == 0
    _class = "saturday" if _i == 6
    cal << %[| #{Date::jwday(_i)}]
  end
  cal << %[ | 
]
  if (_b = (date.week_beginning.wday)) > 0
    cal << %[]
    _b.times do
      cal << %[| ]
    end
    if _b == 6
      cal << %[ | 
]
    end
  end
  date.each_day do |_d|
    if _d.to_s == selected.to_s
      _str = %[#{_d.day}]
    else
      if days.index(_d.day)
        _str = %[#{_d.day}]
      else
        _str = _d.day
      end
    end
    _class = []
    if _d == _today
      _class << "today"
    end
    #if _d.holiday?
    #  _class << "holiday"
    #end
    case _d.wday
    when 0
      _class << "sunday"
      cal << %[| #{_str}]
    when 6
      _class << "saturday"
      cal << %[ | #{_str} | 
]
    else
      cal << %[#{_str}]
    end
  end
  if (_b = (date.week_end.wday)) < 6
    if _b == 0
      cal << %[ | ]
    end
    _b.times do
      cal << %[| ]
    end
    cal << %[ | 
]
  end
  cal << %[
]
  <<-EOS
  
  
#{_today.strftime("%Y/%m")}
  #{cal.join("\n")}
  
  EOS
end
eb = EasyBLOG::new
params = eb.params
counter = Counter::new
counter.limit = eb.config.limit
order = Hash::new
order[:argv] = Array::new
order[:prev] = ""
order[:next] = ""
order[:counter] = ""
order[:start] = 0
order[:total] = 0
dbsafe = Hash::new
safe = Hash::new
safe[:q] = Hash::new
where = Hash::new
where[:blog] = ["not blg_invisible"]
websafe = Hash::new
websafe[:q] = Hash::new
websafe[:main] = Array::new
websafe[:category] = Array::new
websafe[:date] = Array::new
websafe[:day] = Array::new
websafe[:recent] = Array::new
websafe[:title] = ""
websafe[:blog_title] = eb.config.title.escapeHTML
websafe[:category_name] = ""
category_all = nil
category = nil
category_design = {
  :mode => nil,
  :html => nil,
}
blog = Array::new
mode = nil
today = Date::today
date = DateMonth::new(today.year, today.month)
if params.key?(:c) and params[:c].first =~ /^\d{1,7}$/
  dbsafe[:blg_oid] = $&
  dbsafe[:cat_oid] = ""
  dbsafe[:date] = ""
  where[:blog] = ["blg_oid = #{dbsafe[:blg_oid]}", "not blg_invisible"]
  category_all = true
  if params.key?(:md) and params[:md].first =~ /^[s]$/
    mode = dbsafe[:blg_oid]
  end
elsif params.key?(:a) and params[:a].first =~ /^\w{1,20}$/
  dbsafe[:blg_alias] = eb.dbquote($&)
  dbsafe[:cat_oid] = ""
  dbsafe[:date] = ""
  where[:blog] = ["blg_alias = '#{dbsafe[:blg_alias]}'", "not blg_invisible"]
  category_all = true
else
  # カウンター関係
  if params.key?(:start) and params[:start].first =~ /^\d{1,3}$/
    order[:start] = params[:start].first.to_i
  end
  if params.key?(:cat_oid) and params[:cat_oid].first =~ /^\d{1,7}$/
    dbsafe[:cat_oid] = $&
  else
    dbsafe[:cat_oid] = ""
  end
  if params.key?(:search)
    if params.key?(:word) and params[:word].first != ""
      safe[:search] = "t"
      safe[:tg] = ""
      dbsafe[:word] = eb.dbquote(params[:word].first)
      if params.key?(:p)
        safe[:p] = true
        order[:argv] << "p=t"
      end
      if params.key?(:tg) and params[:tg].first =~ /^[tks]+$/i
        _tmp = $&
        _where = Array::new
        if _tmp[/t/]
          safe[:tg] << "t"
          _where << "blg_title like '%#{dbsafe[:word]}%'"
        end
        if _tmp[/k/]
          safe[:tg] << "k"
          _where << "blg_keyword like '%#{dbsafe[:word]}%'"
        end
        if _tmp[/s/]
          safe[:tg] << "s"
          _where << "blg_string like '%#{dbsafe[:word]}%'"
        end
        where[:blog] << _where.join(" or ")
        websafe[:tg] = safe[:tg]
        order[:argv] << "tg=#{websafe[:tg]}"
      else
        where[:blog] << "(blg_title like '%#{dbsafe[:word]}%' or blg_keyword like '%#{dbsafe[:word]}%' or blg_string like '%#{dbsafe[:word]}%')"
      end
      websafe[:word] = params[:word].first.escapeHTML
      order[:argv] << "search=t"
      order[:argv] << "word=#{websafe[:word]}"
      #category_all = true
    else
      safe[:search] = nil
    end
  end
  if params.key?(:date) and params[:date].first =~ /^20\d\d\-(0[1-9]|1[120])(\-\d\d)?$/
    if $2
      if dbsafe[:day] = DateMonth::date?($&, true)
        where[:blog] << "blg_entry = '#{dbsafe[:day].to_s}'"
      end
    else
      dbsafe[:date] = $&
    end
    category_all = true
  else
    dbsafe[:date] = ""
  end
end
def make_menu_recent(eb, conn)
  _recent = Array::new
  conn.execute(<<-EOS) do |r|
    select blg_oid, blg_entry, blg_title, blg_html, blg_keyword, null, null, blg_modify, blg_alias
    from tbl_blog
    where not blg_invisible
    order by blg_entry desc, blg_modify desc
    limit #{eb.config.recent_limit} offset 0;
    EOS
    if r[8] and r[8] != ""
      pam = "a=#{r[8]}"
    else
      pam = "c=#{r[0]}"
    end
    _recent << %[#{r[2].escapeHTML}]
  end
  eb.config.recent_template.sub(/%%recent%%/){_recent.join("\n")}
end
def make_menu_category(eb, conn, selected, category_all)
  #fields = [ :cat_oid, :cat_name, :cat_description, :cat_priority, ]
  _category_count = 0
  _category = Array::new
  conn.execute(<<-EOS) do |r|
    select cat_oid, cat_name, count(cat_oid) from tbl_category
    join tbl_category_list on cat_oid = cal_cat_oid join tbl_blog on blg_oid = cal_blg_oid
    where not blg_invisible
    group by cat_oid, cat_name
    order by cat_priority, cat_name;
    EOS
    if r[0] != selected
      _category << %[#{r[1].escapeHTML}(#{r[2]})]
    else
      _category << %[#{r[1].escapeHTML}(#{r[2]})]
      category_all = true
    end
  end
  conn.execute(<<-EOS) do |r|
    select count(blg_oid)
    from tbl_blog
    where not blg_invisible;
    EOS
    _category_count = r[0]
  end
  if category_all
    _category.unshift(%[全て表示(#{_category_count})])
  else
    _category.unshift(%[全て表示(#{_category_count})])
  end
  eb.config.category_template.sub(/%%category%%/){_category.join("\n")}
end
def make_menu_date(date, eb)
  eb.config.archive_template.sub(/%%archive%%/){date.join("\n")}
end
def make_days(conn, date)
  _days = Array::new
  conn.execute(<<-EOS) do |r|
    select distinct strftime('%d', blg_entry) from tbl_blog
    where strftime('%Y-%m', blg_entry) = '#{date.strftime('%Y-%m')}'
    EOS
    _days << r[0].to_i
  end
  _days
end
eb.session do |conn|
  conn.execute(<<-EOS, dbsafe[:cat_oid]) do |r|
    select cat_oid, cat_name, cat_design_mode, cat_design_html from tbl_category where cat_oid = ?;
    EOS
    safe[:q][:cat_oid] = r[0]
    order[:argv] << "cat_oid=#{r[0].escape}"
    #where[:blog] << "blg_cat_oid = #{safe[:q][:cat_oid]}"
    if not safe[:q][:cat_oid].empty?
      where[:blog] << "cal_cat_oid = #{safe[:q][:cat_oid]}"
    end
    if r[1] and r[1] != ""
      websafe[:category_name] = r[1].escapeHTML
    end
    if dbsafe[:cat_oid] != "" and dbsafe[:cat_oid] == r[0]
      category_design[:mode] = r[2]
      category_design[:html] = r[3]
    end
  end
  archive_limit = eb.config.archive_limit
  conn.execute(<<-EOS) do |r|
    select strftime('%Y-%m', blg_entry), count(blg_entry) from tbl_blog
    where not blg_invisible
    group by strftime('%Y-%m', blg_entry)
    order by blg_entry desc;
    EOS
    (_y,_m) = r[0].split(/\-/)
    if eb.config.archive_label_format
      _date = eb.config.archive_label_format \
        .sub(/%Y/){_y}.sub(/%y/){_y[/\d\d$/]} \
        .sub(/%M/){_m}.sub(/%m/){_m.to_i.to_s} \
        .sub(/%J/){
          Date::jyear(_y.to_i).sub(/^[HSTM]/){
            case $&
            when "H"
              "平成"
            when "S"
              "昭和"
            when "T"
              "大正"
            when "M"
              "明治"
            else
              $&
            end
          }
        }
    else
      _date = r[0]
    end
    _attr = ""
    if archive_limit
      if websafe[:date].size == archive_limit
        if dbsafe[:date] != "" and "#{_y}#{_m}".to_i >= dbsafe[:date].sub(/\-/, "").to_i
          archive_limit += 1
        else
          websafe[:date] << %[[以前のリスト]]
          _hidden = true
        end
      elsif websafe[:date].size > archive_limit
        _hidden = true
      end
      if _hidden
        _attr = %[class="EasyBLOG_menu_archive" style="display: none;"]
      end
    end
    if dbsafe[:date] != r[0]
      websafe[:date] << %[#{_date}(#{r[1]})]
    else
      websafe[:date] << %[#{_date}(#{r[1]})]
      where[:blog] << "strftime('%Y-%m', blg_entry) = '#{dbsafe[:date]}'"
      order[:argv] << "date=#{r[0].escape}"
    end
  end
  websafe[:recent] = make_menu_recent(eb, conn)
  websafe[:category] = make_menu_category(eb, conn, safe[:q][:cat_oid], category_all)
  websafe[:date] = make_menu_date(websafe[:date], eb)
  websafe[:day] = make_days(conn, today)
  category = Hash::new
  if dbsafe[:blg_oid] or dbsafe[:blg_alias]
    blog = conn.execute(<<-EOS)
      select blg_oid, blg_entry, blg_title, blg_html, blg_keyword, null, null, blg_modify, blg_alias
      from tbl_blog
      where #{where[:blog].join(" and ")}
    EOS
    websafe[:count] = 1
    order[:total] = websafe[:count]
    if eb.config.history_back and eb.config.history_back != ""
      websafe[:history_back] = eb.config.history_back
    else
      websafe[:history_back] = ""
    end
    if eb.config.next_page_tag and eb.config.next_page_tag != ""
      blog = blog.collect{|a|
        a[3].sub!(/#{Regexp::quote(eb.config.next_page_tag)}/, "")
        a
      }
    end
  else
    websafe[:history_back] = ""
    if dbsafe[:cat_oid] != ""
      conn.execute(<<-EOS) do |r|
        select count(blg_oid)
        from tbl_blog join tbl_category_list on blg_oid = cal_blg_oid join tbl_category on cat_oid = cal_cat_oid
        where #{where[:blog].join(" and ")}
        EOS
        websafe[:count] = r[0].to_i
        order[:total] = websafe[:count]
      end
      blog = conn.execute(<<-EOS)
        select blg_oid, blg_entry, blg_title, blg_html, blg_keyword, cat_oid, cat_name, blg_modify, blg_string, blg_alias
        from tbl_blog join tbl_category_list on blg_oid = cal_blg_oid join tbl_category on cat_oid = cal_cat_oid
        where #{where[:blog].join(" and ")}
        order by blg_entry #{eb.config.date_order}, blg_modify #{eb.config.date_order}
        limit #{eb.config.limit} offset #{order[:start]*eb.config.limit};
      EOS
    else
      conn.execute(<<-EOS) do |r|
        select count(blg_oid)
        from tbl_blog
        where #{where[:blog].join(" and ")}
        EOS
        websafe[:count] = r[0].to_i
        order[:total] = websafe[:count]
      end
      blog = conn.execute(<<-EOS)
        select blg_oid, blg_entry, blg_title, blg_html, blg_keyword, null, null, blg_modify, blg_string, blg_alias
        from tbl_blog
        where #{where[:blog].join(" and ")}
        order by blg_entry #{eb.config.date_order}, blg_modify #{eb.config.date_order}
        limit #{eb.config.limit} offset #{order[:start]*eb.config.limit};
      EOS
    end
    if eb.config.next_page_tag and eb.config.next_page_tag != ""
      blog = blog.collect{|a|
        if a[9] and a[9] != ""
          pam = "a=#{a[9]}"
        else
          pam = "c=#{a[0]}"
        end
        if pos = a[3].index(eb.config.next_page_tag)
          a[3] = a[3][0..(pos-1)]
          if eb.config.next_page_button and eb.config.next_page_button != ""
            a[3] << eb.config.next_page_button.sub(/href=\"[^\"]*\"/){%[href="#{eb.filename}?#{pam}"]}
          else
            a[3] << %[[続きを読む]
]
          end
        end
        a
      }
    end
  end
  blog_oid = blog.collect{|a| a[0]}.uniq
  conn.execute(<<-EOS) do |r|
      select blg_oid, cat_oid, cat_name
      from tbl_blog join tbl_category_list on blg_oid = cal_blg_oid join tbl_category on cat_oid = cal_cat_oid
      where blg_oid in(#{blog_oid.join(", ")});
    EOS
    unless category.key?(r[0])
      category[r[0]] = Array::new
    end
    category[r[0]] << [r[1], r[2]]
  end
  blog.each do |r|
    if r[9] and r[9] != ""
      pam = "a=#{r[9]}"
    else
      pam = "c=#{r[0]}"
    end
    if dbsafe[:blg_oid] or dbsafe[:blg_alias]
      _title = %[#{r[2].escapeHTML}]
      websafe[:title] = _title
    else
      _title = %[#{r[2].escapeHTML}]
    end
    __title = r[2]
    __uri = "http://#{ENV["SERVER_NAME"]}/#{_lib}/#{eb.filename}?#{pam}"
    _category = Array::new
    if category.key?(r[0])
      category[r[0]].each do |v|
        _category << %[#{v[1].escapeHTML}]
      end
      _category = _category.join(", ")
    else
      _category = %[]
    end
    _body = eb.swap(r[3])
    if not safe[:search] or (safe[:search] and safe[:p])
      if eb.config.buttons
        _buttons = %[]
        eb.config.button_order.each do |_r|
          _buttons << (eb.config.button[_r] || "").sub(/%%URI%%/){__uri.escapeHTML}.sub(/%%TITLE%%/){__title.escapeHTML}
        end
        _buttons << %[
]
        unless websafe[:buttons_script]
          websafe[:buttons_script] = ""
          eb.config.button_order.each do |_r|
            websafe[:buttons_script] << eb.config.button["#{_r}_script".intern]||""
          end
        end
      end
      if mode
        websafe[:main] << eb.config.blog_template \
          .sub(/%%title%%/){_title} \
          .sub(/%%body%%/){_body} \
          .sub(/%%buttons%%/){_buttons||""} \
          .sub(/%%date%%/){r[1].escapeHTML}
        #websafe[:main] << <<-EOS
        #  #{_title}
        #  #{_body}
        #  #{_buttons||""}
        #EOS
      else
        websafe[:main] << eb.config.blog_template \
          .sub(/%%title%%/){_title} \
          .sub(/%%body%%/){_body} \
          .sub(/%%buttons%%/){_buttons||""} \
          .sub(/%%date%%/){r[1].escapeHTML}
        #websafe[:main] << <<-EOS
        #  #{_title}
        #  #{_body}
        #  #{_buttons||""}
        #EOS
      end
    else
      websafe[:main] << <<-EOS
        #{r[2].escapeHTML}
        #{r[8].cut(0,80).escapeHTML} … [
続きを読む]
]
  print websafe[:main]
  print %[
]
else
  websafe[:cal] = make_cal(eb, date, websafe[:day], dbsafe[:day])
  order = make_counter(eb, counter, order, true)
  if order[:counter] != ""
    navi = %[#{order[:prev]} #{order[:counter]} #{order[:next]}
]
  else
    navi = ""
  end
  html = <<-EOS
    
    #{websafe[:history_back]}
    #{websafe[:main].join("\n")}
    #{navi}
    
    #{websafe[:buttons_script]||""}
  EOS
  case category_design[:mode].to_i
  when 1, 5
    if category_design[:mode].to_i == 5 and counter.now > 1
      category_design[:html] = ""
    end
    websafe[:main] = <<-EOS
    #{category_design[:html]}
    #{html}
    EOS
  when 2, 6
    if category_design[:mode].to_i == 6 and counter.now > 1
      category_design[:html] = ""
    end
    websafe[:main] = <<-EOS
    #{html}
    #{category_design[:html]}
    EOS
  when 3, 7
    if category_design[:mode].to_i == 7 and counter.now > 1
      websafe[:main] = html
    else
      websafe[:main] = category_design[:html].sub(/(?:<(?:p|div)>\s*)?@@記事@@(?:\s*<\/(?:p|div)>)?/){html}
    end
  else
    websafe[:main] = html
  end
  ERuby::import("./html.rhtml")
end
%>