=begin
 * Name: SiSU information Structuring Universe - Structured information, Serialized Units
 * Author: Ralph Amissah
   * http://www.jus.uio.no/sisu
   * http://www.jus.uio.no/sisu/SiSU/download.html

 * Description: generates naive cgi search form for search of sisu database (pgsql sqlite)

 * Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Ralph Amissah

 * License: GPL 2 or later

  Summary of GPL 2

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option)
  any later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

  If you have Internet connection, the latest version of the GPL should be
  available at these locations:
    http://www.fsf.org/licenses/gpl.html
    http://www.gnu.org/copyleft/gpl.html
    http://www.jus.uio.no/sisu/gpl2.fsf

  SiSU was first released to the public on January 4th 2005

  SiSU uses:
  *  Standard SiSU markup syntax,
  *  Standard SiSU meta-markup syntax, and the
  *  Standard SiSU object citation numbering and system
  
  © Ralph Amissah 1997, current 2007.
  All Rights Reserved.

 * Ralph Amissah mailto:ralph@amissah.com
   Ralph Amissah mailto:amissah@gmail.com

=end
module  SiSU_CGI_sqlite                                                            #% database building documents
  require SiSU_lib + '/sysenv'
  require SiSU_lib + '/cgi_sql_common'
  include SiSU_CGI_sql
  class SiSU_search_sqlite < SiSU_CGI_common
    def initialize(opt,webserv)
      @opt,@webserv=opt,webserv
      @env=SiSU_Env::Info_env.new('',opt)
      @image_src="#{@env.url.webserv_cgi}/_sisu/image"
      @common=SiSU_CGI_sql::SiSU_CGI_common.new(@webserv,@opt.cmd,@image_src,@env)
    end
    def sqlite
      serve=[]
      Dir.foreach(@env.path.webserv) do |x| 
        if x !~/^\./ and FileTest.directory?("#{@env.path.webserv}/#{x}") 
          if FileTest.file?("#{@env.path.webserv}/#{x}/sisu_sqlite.db"); serve << x unless x =~/^_\S+/ 
          end
        end
      end
      serve.sort!
      f1,f2,f3=[],[],[]
      serve.each do |x|
        f1 << %{              <option value="SiSU_#{x}">#{x}</option>\n}
      end
      f2 <<  %{          selected_db=case cgi['db']\n}
      serve.each do |x|
        f2 << %{           when /SiSU_#{x}/; '<option value="SiSU_#{x}">#{x}</option>'\n}
      end
      f2 << "          end\n"
      #f3
      f3 << %{          db_name='sisu_sqlite.db'\n}
      f3 << %{          db_sqlite=case cgi['db']\n}
      serve.each do |x|
        f3 << %{          when /SiSU_#{x}/;                      "#{@env.path.webserv}/#{x}/sisu_sqlite.db"\n}
      end
      f3 << "          end\n"
      if FileTest.writable?('.') 
        output=File.open('sisu_sqlite.cgi','w')
        output << header0 << header1 << header_desc << header2 << f1 << buttons1 << buttons2 << search_request << search_statement << search_statement_common << search_query1 << @common.pages << search_query2 << @common.tail << @common.main1 << f2 << f3 << dbi_connect << @common.main2
        a=%{        generated sisu_sqlite.cgi, 
            BASED ON ALREADY CREATED sisu_sqlite.db OUTPUT, (-d) 
        }
        tell=SiSU_Screen::Ansi.new(@opt.cmd,a) 
        tell.print_grey
        c=case @webserv
        when /pwd/; ''
        else "if necessary make the directory /usr/lib/cgi-bin :
                  sudo cp -vi #{Dir.pwd}/sisu_sqlite.cgi /usr/lib/cgi-bin/. 
                  sudo chmod -v 755 /usr/lib/cgi-bin/sisu_sqlite.cgi
                  (copy sisu_sqlite.cgi to your cgi directory) and set file permissions to 755"
        end
        a=%{#{c}
                  #{@env.webserv_base_cgi}/cgi-bin/sisu_sqlite.cgi
        }
        b='(to create and populate sisu sqlite database see "man sisu" and in particular the -d flag)'
        tell=SiSU_Screen::Ansi.new(@opt.cmd,a,b)
        tell.warn
      else puts 'failed in attempt to write sisu_sqlite.cgi to present directory, is directory writable?'
      end
    end
    def header0
      <<-WOK_SQL
#!/usr/bin/env ruby
=begin
#{about}
 * Description: generates naive cgi search form for search of sisu database (sqlite)
#{gpl}
=end
      require 'cgi'
      require 'fcgi'
      require 'dbi'
      @version='sisu_sqlite'
      @image_src="#{@env.url.webserv_cgi}/_sisu/image"
      @hosturl_db="#{@env.url.webserv_base_cgi}"
      @hosturl_files="#{@env.url.webserv_files_from_db}"
      WOK_SQL
    end
    def search_statement
      <<-'WOK_SQL'
      class Dbi_search_string
        def initialize(l,t,q)
          @l,@t,@q=l,t,q
        end
        def string
          search={ :search => [] }
          search[:flag]=false
          if @t =~/\S+/ or @q =~/\S+/
            if @t =~/\S+/;     unescaped_search=CGI.unescape(@t)
            elsif @q =~/\S+/;  unescaped_search=CGI.unescape(@q)
            end
            search_construct=[]
            unescaped_search.gsub!(/\s*(AND|OR)\s*/,"%' \) \\1 #@l LIKE \( '%")
            unescaped_search.gsub!(/(.+)/,"#@l LIKE \( '%\\1%' \)")
            search_construct << unescaped_search
            search_construct=search_construct.join(' ')
            search[:search]                    << search_construct
            search[:flag]=true
            search
          end
          search
        end
      end
      WOK_SQL
    end
    def search_query1
      <<-'WOK_SQL'
          @search_text,@search_endnotes=[],[]
                                                                                 #%
          search[:text].each{|x| @search_text << "#{x} AND " }
          @search_text=@search_text.to_s.gsub!(/AND\s+$/,'')
          @search_text.gsub!(/(documents\.clean\s+LIKE\s+\(\s*'%[^']+%'\s*\)\s+(?:(?:AND|OR)\s+documents\.clean\s+LIKE\s+\(\s*'%[^']+%'\s*\))+)/,'(\1)')
          search[:endnotes].each{|x| @search_endnotes << "#{x} AND " }
          @search_endnotes=@search_endnotes.to_s.gsub!(/AND\s+$/,'')
          @search_text.gsub!(/(endnotes\.clean\s+LIKE\s+\(\s*'%[^']+%'\s*\)\s+(?:(?:AND|OR)\s+endnotes\.clean\s+LIKE\s+\(\s*'%[^']+%'\s*\))+)/,'(\1)')
        end
      WOK_SQL
    end
    def search_query2
      <<-'WOK_SQL'
        def sql_select_body
          limit ||=@@limit
          offset ||=@@offset
          @sql_statement[:body]=%{SELECT metadata.title, metadata.creator, metadata.filename, metadata.suffix, documents.body, documents.seg, documents.ocn, metadata.tid FROM documents, metadata WHERE #{@search_text} AND documents.metadata_tid = metadata.tid ORDER BY metadata.title, documents.ocn}
          @sql_statement[:range]=%{LIMIT #{limit} OFFSET #{offset} ;}
          select=@sql_statement[:body] + ' ' + @sql_statement[:range]
          select
        end
        def sql_select_endnotes
          limit ||=@@limit
          offset ||=@@offset
          @sql_statement[:endnotes]= %{SELECT metadata.title, metadata.creator, metadata.filename, endnotes.body, endnotes.nr, endnotes.ocn, endnotes.metadata_tid FROM metadata, endnotes WHERE #{@search_endnotes} AND metadata.tid = endnotes.metadata_tid ORDER BY metadata.title, endnotes.nr}
          @sql_statement[:range]=%{LIMIT #{limit} OFFSET #{offset} ;}
          select=@sql_statement[:endnotes] + ' ' + @sql_statement[:range]
          select
        end
        def sql_select_body_format
          %{<font color="#666666" size="2">#{sql_select_body}</font>} 
        end
        def sql_select_endnotes_format
          %{<font color="#666666" size="2">#{sql_select_endnotes}</font>} 
        end
        def contents
          @conn.select_all(sql_select_body)
        end
        def endnotes
          @conn.select_all(sql_select_endnotes)
        end
      end
      WOK_SQL
    end
    def dbi_connect
      <<-'WOK_SQL'
          @dbi="DBI:SQLite:#{db_sqlite}" #sqlite3 ?
          @conn=DBI.connect(@dbi) 
      WOK_SQL
    end
  end
end
__END__