# Copyright CrazySpence 2004
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#NOTES: the regsubs that alter the irc wildcards to mysql are Copyright (C) 2003 BarkerJr
#and the checkarg function is from quoteme 1.3 by k-rist (k-rist@rsn.hk-r.se)

namespace eval SpenceQuote {
#MySQL server stuff
set quotedatabase "pet"
set quotehost ""
set quoteuser ""
set quotepass ""
set quotetable "quotes"

#time in seconds where if nothing is said to stop doing 60 minute quote
set silentrun 300

#code starts here
mysql_connect $quotedatabase $quotehost $quoteuser $quotepass 

# Make sure the table exists
mysql_query "CREATE TABLE IF NOT EXISTS $quotetable (
              `id` INT NOT NULL AUTO_INCREMENT ,
              `nick` VARCHAR( 32 ) NOT NULL ,
              `chan` VARCHAR( 32 ) NOT NULL ,
              `quote` BLOB NOT NULL ,
              `added` DATE NOT NULL ,
              PRIMARY KEY ( `id` )
              )"
bind join - * SpenceQuote::joinquote

proc joinquote {nick uhost hand chan} {
     global quotetable
     set query "SELECT channel_id,quote FROM $SpenceQuote::quotetable WHERE chan='$chan' AND UPPER(quote) LIKE UPPER('[concat %$nick%]') ORDER BY RAND() LIMIT 1"
     set result [mysql_query $query]
     unset query
     set row [lindex $result 0]     
     set number [lindex $row 0]
     set punchline [lindex $row 1]
     if {$punchline != ""} {
          putserv "PRIVMSG $chan :($number) [join $punchline]"
     }
     return 0
}

bind pub - !quote SpenceQuote::requestquote

proc requestquote {nick uhost hand chan arg} {
     global quotetable
     if {$arg != "" } {
          set numcheck [checkarg $arg]
          if {$numcheck != "" } {
               set query "SELECT channel_id,quote FROM $SpenceQuote::quotetable WHERE chan='$chan' AND channel_id='$numcheck'"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    putserv "PRIVMSG $chan :($number) $punchline"
                    return 0
               }
          }
          # Replace IRC wildcards (*,?) with SQL wildcards (%,_).  If there are any, we
          # will use LIKE rather than = in the MySQL statement.
          set query $arg
          set wildcnt 0
          incr wildcnt [regsub -all {[*]} [mysql_escape $query] "%" query]
          #regsub -all {\\} $query {\\\\} query
          regsub -all _ $query {\\_} query
          incr wildcnt [regsub -all {[?]} $query _ query]
          if {$wildcnt} {
               set query "SELECT channel_id,quote FROM $SpenceQuote::quotetable WHERE chan='$chan' AND UPPER(quote) LIKE UPPER('$query') ORDER BY RAND() LIMIT 1"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    putserv "PRIVMSG $chan :($number) $punchline"
                    return 0
               }     
          } else {
               set query "SELECT channel_id,quote FROM $SpenceQuote::quotetable WHERE chan='$chan' AND UPPER(quote) LIKE UPPER('%$query%') ORDER BY RAND() LIMIT 1"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    putserv "PRIVMSG $chan :($number) $punchline"
                    return 0
               }
          }
     } else {
          set query "SELECT channel_id,quote FROM $SpenceQuote::quotetable WHERE chan='$chan' ORDER BY RAND() LIMIT 1"
          set result [mysql_query $query]
          unset query
          if {$result != ""} {
               set row [lindex $result 0]
               set number [lindex $row 0]
               set punchline [lindex $row 1]
               putserv "PRIVMSG $chan :($number) $punchline"
               return 0
          }
     }
}

bind pub - !globquote SpenceQuote::globrequestquote

proc globrequestquote {nick uhost hand chan arg} {
     global quotetable
     if {$arg != "" } {
          set numcheck [checkarg $arg]
          if {$numcheck != "" } {
               set query "SELECT id,quote,chan FROM $SpenceQuote::quotetable WHERE id='$numcheck'"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    set fromchan [lindex $row 2]
                    putserv "PRIVMSG $chan :($fromchan $number) $punchline"
                    return 0
               }
          }
          # Replace IRC wildcards (*,?) with SQL wildcards (%,_).  If there are any, we
          # will use LIKE rather than = in the MySQL statement.
          set query $arg
          set wildcnt 0
          incr wildcnt [regsub -all {[*]} [mysql_escape $query] "%" query]
          #regsub -all {\\} $query {\\\\} query
          regsub -all _ $query {\\_} query
          incr wildcnt [regsub -all {[?]} $query _ query]
          if {$wildcnt} {
               set query "SELECT id,quote,chan FROM $SpenceQuote::quotetable WHERE UPPER(quote) LIKE UPPER('$query') ORDER BY RAND() LIMIT 1"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    set fromchan [lindex $row 2]
                    putserv "PRIVMSG $chan :($fromchan $number) $punchline"
                    return 0
               }     
          } else {
               set query "SELECT id,quote,chan FROM $SpenceQuote::quotetable WHERE UPPER(quote) LIKE UPPER('%$query%') ORDER BY RAND() LIMIT 1"
               set result [mysql_query $query]
               unset query
               if {$result != ""} {
                    set row [lindex $result 0]
                    set number [lindex $row 0]
                    set punchline [lindex $row 1]
                    set fromchan [lindex $row 2]
                    putserv "PRIVMSG $chan :($fromchan $number) $punchline"
                    return 0
               }
          }
     } else {
          set query "SELECT id,quote,chan FROM $SpenceQuote::quotetable ORDER BY RAND() LIMIT 1"
          set result [mysql_query $query]
          unset query
          if {$result != ""} {
               set row [lindex $result 0]
               set number [lindex $row 0]
               set punchline [lindex $row 1]
               set fromchan [lindex $row 2]
               putserv "PRIVMSG $chan :($fromchan $number) $punchline"
               return 0
          }
     }
}

bind pub -|o !addquote SpenceQuote::addquote

proc addquote {nick uhost hand chan arg} {
     #Got to grab the highest possible channel_id because we don't want duplicate channel_id's AND 
     #we dont want to number them by id because then #somechan would have like quote #1 through 20 then
     #someotherchan would have 51-100 etc... channel_id keeps things sane for the average bear
     global table
     set query "SELECT channel_id FROM $SpenceQuote::quotetable WHERE chan='$chan' ORDER BY channel_id DESC LIMIT 1"
     set result [mysql_query $query]
     set numquotes [lindex $result 0]
     unset query
     if {$numquotes == ""} {
          set numquotes 0
     }     
     set query "INSERT INTO $SpenceQuote::quotetable (nick,chan,quote,added,channel_id) VALUES ('$nick','$chan','[mysql_escape $arg]',NOW(),'[expr "$numquotes + 1 "]')"
     set result [mysql_query $query]
     putserv "NOTICE $nick :Quote added ([expr "$numquotes + 1 "])"
     return 0
}

bind pub -|n !delquote SpenceQuote::delquote

proc delquote {nick uhost hand chan arg} {
     global table
     if {$arg != "" } {
          set numcheck [checkarg $arg]
          if {$numcheck != "" } {
               set query "DELETE FROM $SpenceQuote::quotetable WHERE chan='$chan' AND channel_id='$numcheck'"
               set result [mysql_query $query]
               if {$result != ""} {
                    putserv "NOTICE $nick :Delete failed for quote $numcheck"
                    return 1
               } else {
                    putserv "NOTICE $nick :Quote $numcheck deleted"
                    return 0
               }
          }
     }
     putserv "NOTICE $nick :SYNTAX !delquote #"
     return 0       
}

# Checks if an arg is numeric (truncates the arg to first character)
# arg  - the arg to check
# return the new arg if arg is ok, "" if it failed
proc checkarg {arg} {
    set arg [lindex $arg 0]
    if {[regexp "^\[0-9\]+$" $arg]} {
	return $arg
    }
    return ""
}

}

