chiark / gitweb /
Bugfixes.
[ircbot] / bot.tcl
1 # Actual IRC bot code
2
3 set helpfile helpinfos
4
5 source irccore.tcl
6 source parsecmd.tcl
7 source stdhelp.tcl
8
9 defset marktime_min 300
10 defset marktime_join_startdelay 5000
11
12 proc privmsg_unlogged {prefix ischan params} {
13     if {!$ischan ||
14         [regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
15         return 0
16     }
17     # on-channel message, ignore
18     set chan [lindex $params 0]
19     upvar #0 chan_lastactivity([irctolower $chan]) la
20     set la [clock seconds]
21     catch_logged { recordlastseen_p $prefix "talking on $chan" 2 }
22     return 1
23 }
24
25 proc showintervalsecs {howlong abbrev} {
26     return [showintervalsecs/[opt timeformat] $howlong $abbrev]
27 }
28
29 proc showintervalsecs/ks {howlong abbrev} {
30     if {$howlong < 1000} {
31         return "${howlong}s"
32     } else {
33         if {$howlong < 1000000} {
34             set pfx k
35             set scale 1000
36         } else {
37             set pfx M
38             set scale 1000000
39         }
40         set value [expr "$howlong.0 / $scale"]
41         foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
42             if {$value < $min} continue
43             return [format "$format${pfx}s" $value]
44         }
45     }
46 }
47
48 proc format_qty {qty unit abbrev} {
49     set o $qty
50     if {$abbrev} {
51         append o [string range $unit 0 0]
52     } else {
53         append o " "
54         append o $unit
55         if {$qty != 1} { append o s }
56     }
57     return $o
58 }
59
60 proc showintervalsecs/hms {qty abbrev} {
61     set ul {second 60 minute 60 hour 24 day 7 week}
62     set remainv 0
63     while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
64         set remainu [lindex $ul 0]
65         set remainv [expr {$qty % $uv}]
66         set qty [expr {($qty-$remainv)/$uv}]
67         set ul [lreplace $ul 0 1]
68     }
69     set o [format_qty $qty [lindex $ul 0] $abbrev]
70     if {$remainv} {
71         if {!$abbrev} { append o " " }
72         append o [format_qty $remainv $remainu $abbrev]
73     }
74     return $o
75 }
76
77 proc showinterval {howlong} {
78     if {$howlong <= 0} {
79         return {just now}
80     } else {
81         return "[showintervalsecs $howlong 0] ago"
82     }
83 }
84
85 proc showtime {when} {
86     return [showinterval [expr {[clock seconds] - $when}]]
87 }
88
89 proc parse_interval {specified min} {
90     if {![regexp {^([0-9]+)([a-z]+)$} $specified dummy value unit]} {
91         error "invalid syntax for interval"
92     }
93     switch -exact $unit {
94         s { set u 1 }
95         ks { set u 1000 }
96         m { set u 60 }
97         h { set u 3600 }
98         default { error "unknown unit of time $unit" }
99     }
100     if {$value > 86400*21/$u} { error "interval too large" }
101     set result [expr {$value*$u}]
102     if {$result < $min} { error "interval too small (<${min}s)" }
103     return $result
104 }
105
106 proc def_msgproc {name argl body} {
107     proc msg_$name "varbase $argl" "\
108     upvar #0 msg/\$varbase/dest d\n\
109     upvar #0 msg/\$varbase/str s\n\
110     upvar #0 msg/\$varbase/accum a\n\
111 $body"
112 }
113
114 def_msgproc begin {dest str} {
115     set d $dest
116     set s $str
117     set a {}
118 }
119
120 def_msgproc append {str} {
121     set ns "$s$str"
122     if {[string length $s] && [string length $ns] > 65} {
123         msg__sendout $varbase
124         set s " [string trimleft $str]"
125     } else {
126         set s $ns
127     }
128 }
129
130 def_msgproc finish {} {
131     msg__sendout $varbase
132     unset s
133     unset d
134     return $a
135 }
136
137 def_msgproc _sendout {} {
138     lappend a [string trimright $s]
139     set s {}
140 }
141
142 proc looking_whenwhere {when where} {
143     set str [showtime [expr {$when-1}]]
144     if {[string length $where]} { append str " on $where" }
145     return $str
146 }
147
148 proc tell_event {nl event} {
149     # For `act' we *haven't* yet done the 750ms delay; we implement
150     # that here.  Also, here we turn `talk' into `talk' now and `act'
151     # later.  We also support the psuedo-event `none'.  The del msg
152     # and new msg events are handled by the command procedures, not here.
153     global calling_nick
154     if {[info exists calling_nick] { set save $calling_nick }
155     switch -exact $event {
156         none { }
157         talk {
158             tell_event_core $nl talk
159             tell_event $nl act
160         }
161         act {
162             after 750 [list tell_event_core $nl $event]
163         }
164         ident - msgsarrive {
165             tell_event_core $nl $event
166         }
167         default {
168             error "tell_event $nl $event"
169         }
170     }
171     if {[info exists save]} { set calling_nick $save }
172 }
173
174 proc tell_getcstate {} {
175     # uses nl from caller's context
176     # imports telling (as the nick_telling) and u
177     # sets stt, telling_when
178     uplevel 1 {
179         upvar #0 nick_telling($nl) telling
180         upvar #0 nick_unique($nl) u
181
182         if {[info exists telling]} {
183             manyset $telling u_last stt telling_when
184             if {![info exists u] || "$u_last" != "$u"} {
185                 unset telling; unset stt; unset telling_when
186             }
187         }
188
189         if {![info exists stt]} {
190             set stt norecord
191             set telling_when $now
192         }
193     }
194 }
195
196 proc tell_event_core {nl event} {
197     # event is `talk', `act', `ident' or `msgsarrive'
198     # When user talks we actually get talk now and act later
199     global calling_nick
200     set calling_nick $nl
201     set iml [msgdb_get $nl inbound]
202     if {![llength $iml]} return
203
204     set ago [expr {$now - $telling_when}]
205
206     # Now we have the components of a telling state
207     #   u     - nick_unique (unset if not visible)
208     #   stt   - state: norecord, mentioned, passede
209     #   ago   - how long ago since we did anything
210
211     # We compute an evstate to dispatch on as follows:
212
213     # evstate is string of letters
214     #   current state
215     #      n   NORECORD (MESSAGES)
216     #      m   MENTIONED
217     #      p   PASSED
218     #   event
219     #      t   talk
220     #      a   act
221     #      i   ident
222     #      m   msgsarrive
223     #   security level and timing
224     #      ii  Insecure
225     #      ss  Secure and soon (before interval)
226     #      sl  Secure and late (after interval)
227     #   current identification
228     #      i   Identified
229     #      u   Unidentified
230     #   reliability and timing
231     #      uu  Unreliable
232     #      rv  Remind, very soon (before within-interval)
233     #      rs  Remind, soon (between)
234     #      rl  Remind, late (after every-interval)
235     #      ps  Pester, soon (before interval)
236     #      pl  Pester, late (after interval)
237
238     set evstate {}
239
240     append evstate [string range $stt 0 0]
241     append evstate [string range $event 0 0]
242
243     manyset [tell_effective_sec $n] sec secwhen
244     switch -exact $sec {
245         insecure { append evstate ii }
246         secure { append evstate [expr {$ago<$secwhen ? "sl" : "ss"}] }
247         default { append evstate "#$sec#" }
248     }
249
250     upvar #0 nick_username($nl) nu
251     if {[info exists nu] && "$nu" == "[nickdb_get $nl username]"} {
252         append evstate i
253     } else {
254         append evstate u
255     }
256     
257     manyset [nickdb_set $n tellrel] rel relint relwithin
258     switch -exact $rel {
259         unreliable { append evstate uu }
260         remind { append evstate [expr {
261             $ago<$relwithin ? "rv" : $ago<$relint ? "rs" : "rl"
262         }]}
263         pester { append evstate [expr {$ago<$relint ? "ps" : "pl"}] }
264         default { append evstate "#$rel#" }
265     }
266
267     switch -glob $evstate {
268         pt???rv {
269             # consider delivered:
270             #  (very recently passed, and the user talks)
271             tell_delete_msgs {} $nl
272             return
273         }
274         pm????? {
275             # oops, messages passed are now out of date
276             catch { unset telling }
277             return
278         }
279         ?m????? {
280             # ignore new msgs if we haven't passed yet
281             return
282         }
283         nt????? - mt????? -
284         pt???uu - pt???rs - pt???rl - pt???p? {
285             # ignore (any other `talk's) - act handles these
286             return
287         }
288         ni????? - naii??? - nas?i?? - mi????? - pa????l {
289             # pass and then stuff
290             if {[length $iml] == 3} {
291                 manyset $iml sender sentwhen msg
292                 sendprivmsg $nl \
293  "$sender asked me [showintervalsecs [expr {$now-$sentwhen}] 0]\
294  to tell you: $msg"
295             } else {
296                 sendprivmsg $nl \
297  "Here are the [expr {[llength $iml]/3}] messages there are for you:"
298                 while {[llength $iml] >= 3} {
299                     manyset [lrange $iml 0 2] sender sentwhen msg
300                     set iml [lrange $iml 3 end]
301                     sendprivmsg $nl \
302  " [showintervalsecs [expr {$now-$sentwhen}] 1] <$sender> $msg"
303                 }
304             }
305             if {"$rel" == "unreliable"} {
306                 tell_delete_msgs {} $nl
307                 return
308             }
309             set stt passed
310         }
311         nas?u?? {
312             sendprivmsg $nl {You have messages (so identify yourself please).}]
313             set stt mentioned
314         }
315         masl??? {
316             sendprivmsg $nl {Don't forget about your messages.}]
317         }
318         pi????? {
319             return
320         }
321         mass??? - pa????v - pa????s {
322             # too soon
323             return
324         }
325         * {
326             error "tell_event_core nl=$nl evstate=$evstate ?"
327         }
328     }
329     if {![info exists u]} {
330         catch { unset telling }
331     } else {
332         set telling [list $u $stt $now]
333     }
334 }
335
336 proc recordlastseen_n {n how here} {
337     # here is:
338     #   0 - nick was seen leaving (or changing to another nicks or some such)
339     #   1 - nick was seen doing something else
340     #   2 - nick was seen talking on channel
341     global lastseen lookedfor
342     set nl [irctolower $n]
343     set now [clock seconds]
344     set lastseen($nl) [list $n $now $how]
345
346     if {!$here} return
347
348     tell_event $nl [lindex {none act talk} $here]
349
350     upvar #0 lookedfor($nl) lf
351     if {[info exists lf]} {
352         switch -exact [llength $lf] {
353             0 {
354                 set ml {}
355             }
356             1 {
357                 manyset [lindex $lf 0] when who where
358                 set ml [list \
359  "FYI, $who was looking for you [looking_whenwhere $when $where]."]
360             }
361             default {
362                 msg_begin tosend $n "FYI, people have been looking for you:"
363                 set i 0
364                 set fin ""
365                 foreach e $lf {
366                     incr i
367                     if {$i == 1} {
368                         msg_append tosend " "
369                     } elseif {$i == [llength $lf]} {
370                         msg_append tosend " and "
371                         set fin .
372                     } else {
373                         msg_append tosend ", "
374                     }
375                     manyset $e when who where
376                     msg_append tosend \
377                             "$who ([looking_whenwhere $when $where])$fin"
378                 }
379                 set ml [msg_finish tosend]
380             }
381         }
382         unset lf
383         msendprivmsg_delayed 1000 $n $ml
384     }
385 }
386
387 proc note_topic {showoff whoby topic} {
388     set msg "FYI, $whoby has changed the topic on $showoff"
389     if {[string length $topic] < 160} {
390         append msg " to $topic"
391     } else {
392         append msg " but it is too long to reproduce here !"
393     }
394     set showoff [irctolower $showoff]
395     set tell [chandb_get $showoff topictell]
396     if {[lsearch -exact $tell *] >= 0} {
397         set tryspies [chandb_list]
398     } else {
399         set tryspies $tell
400     }
401     foreach spy $tryspies {
402         set see [chandb_get $spy topicsee]
403         if {[lsearch -exact $see $showoff] >= 0 || \
404                 ([lsearch -exact $see *] >= 0 && \
405                 [lsearch -exact $tell $spy] >= 0)} {
406             sendprivmsg $spy $msg
407         }
408     }
409 }
410
411 proc recordlastseen_p {p how here} {
412     prefix_nick
413     recordlastseen_n $n $how $here
414 }
415
416 proc chanmode_arg {} {
417     upvar 2 args cm_args
418     set rv [lindex $cm_args 0]
419     set cm_args [lreplace cm_args 0 0]
420     return $rv
421 }
422
423 proc chanmode_o1 {m g p chan} {
424     global nick chan_initialop
425     prefix_nick
426     set who [chanmode_arg]
427     recordlastseen_n $n "being nice to $who" 1
428     if {"[irctolower $who]" == "[irctolower $nick]"} {
429         set nlower [irctolower $n]
430         upvar #0 nick_unique($nlower) u
431         if {[chandb_exists $chan]} {
432             sendprivmsg $n Thanks.
433         } elseif {![info exists u]} {
434             sendprivmsg $n {Op me while not on the channel, why don't you ?}
435         } else {
436             set chan_initialop([irctolower $chan]) $u
437             sendprivmsg $n \
438  "Thanks.  You can use `channel manager ...' to register this channel."
439             if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
440                 sendprivmsg $n \
441  "(But to do that you must register your nick securely first.)"
442             }
443         }
444     }
445 }
446
447 proc chanmode_o0 {m g p chan} {
448     global nick chandeop
449     prefix_nick
450     set who [chanmode_arg]
451     recordlastseen_p $p "being mean to $who" 1
452     if {"[irctolower $who]" == "[irctolower $nick]"} {
453         set chandeop($chan) [list [clock seconds] $p]
454     }
455 }
456
457 proc msg_MODE {p c dest modelist args} {
458     if {![ischan $dest]} return
459     if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
460         set give 0
461     } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
462         set give 1
463     } else {
464         error "invalid modelist"
465     }
466     foreach m [split $modelist] {
467         set procname chanmode_$m$give
468         if {[catch { info body $procname }]} {
469             recordlastseen_p $p "fiddling with $dest" 1
470         } else {
471             $procname $m $give  $p $dest
472         }
473     }
474 }
475
476 proc leaving {lchan} {
477     foreach luser [array names nick_onchans] {
478         upvar #0 nick_onchans($luser) oc
479         set oc [grep tc {"$tc" != "$lchan"} $oc]
480     }
481     upvar #0 chan_nicks($lchan) nlist
482     unset nlist
483     upvar #0 chan_lastactivity($lchan) la
484     catch { unset la }
485 }
486
487 proc doleave {lchan} {
488     sendout PART $lchan
489     leaving $lchan
490 }
491
492 proc dojoin {lchan} {
493     global chan_nicks
494     sendout JOIN $lchan
495     set chan_nicks($lchan) {}
496 }
497
498 proc check_justme {lchan} {
499     global nick
500     upvar #0 chan_nicks($lchan) nlist
501     if {[llength $nlist] != 1} return
502     if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
503     if {[chandb_exists $lchan]} {
504         set mode [chandb_get $lchan mode]
505         if {"$mode" != "*"} {
506             sendout MODE $lchan $mode
507         }
508         set topic [chandb_get $lchan topicset]
509         if {[string length $topic]} {
510             sendout TOPIC $lchan $topic
511         }
512     } else {
513         doleave $lchan
514     }
515 }
516
517 proc process_kickpart {chan user} {
518     global nick
519     check_nick $user
520     set luser [irctolower $user]
521     set lchan [irctolower $chan]
522     if {![ischan $chan]} { error "not a channel" }
523     if {"$luser" == "[irctolower $nick]"} {
524         leaving $lchan
525     } else {
526         upvar #0 nick_onchans($luser) oc
527         upvar #0 chan_nicks($lchan) nlist
528         set oc [grep tc {"$tc" != "$lchan"} $oc]
529         set nlist [grep tn {"$tn" != "$luser"} $nlist]
530         nick_case $user
531         if {![llength $oc]} {
532             nick_forget $luser
533         } else {
534             check_justme $lchan
535         }
536     }
537 }
538
539 proc msg_TOPIC {p c dest topic} {
540     prefix_nick
541     if {![ischan $dest]} return
542     recordlastseen_n $n "changing the topic on $dest" 1
543     note_topic [irctolower $dest] $n $topic
544 }
545
546 proc msg_KICK {p c chans users comment} {
547     set chans [split $chans ,]
548     set users [split $users ,]
549     if {[llength $chans] > 1} {
550         foreach chan $chans user $users { process_kickpart $chan $user }
551     } else {
552         foreach user $users { process_kickpart [lindex $chans 0] $user }
553     }
554 }
555
556 proc msg_KILL {p c user why} {
557     nick_forget $user
558 }
559
560 set nick_counter 0
561 set nick_arys {onchans username unique}
562 # nick_onchans($luser) -> [list ... $lchan ...]
563 # nick_username($luser) -> <securely known local username>
564 # nick_unique($luser) -> <includes-counter>
565 # nick_case($luser) -> $user  (valid even if no longer visible)
566 # nick_markid($luser) -> <after id for marktime>
567 # nick_telling($luser) -> <unique> mentioned|passed <when>
568
569 # chan_nicks($lchan) -> [list ... $luser ...]
570 # chan_lastactivity($lchan) -> [clock seconds]
571
572 proc lnick_forget {luser} {
573     global nick_arys chan_nicks
574     lnick_marktime_cancel $luser
575     foreach ary $nick_arys {
576         upvar #0 nick_${ary}($luser) av
577         catch { unset av }
578     }
579     foreach lch [array names chan_nicks] {
580         upvar #0 chan_nicks($lch) nlist
581         set nlist [grep tn {"$tn" != "$luser"} $nlist]
582         check_justme $lch
583     }
584 }
585
586 proc nick_forget {user} {
587     global nick_arys chan_nicks
588     lnick_forget [irctolower $user]
589     nick_case $user
590 }
591
592 proc nick_case {user} {
593     global nick_case
594     set nick_case([irctolower $user]) $user
595 }
596
597 proc msg_NICK {p c newnick} {
598     global nick_arys nick_case calling_nick
599     prefix_nick
600     recordlastseen_n $n "changing nicks to $newnick" 0
601     set calling_nick $newnick
602     recordlastseen_n $newnick "changing nicks from $n" 1
603     set luser [irctolower $n]
604     lnick_marktime_cancel $luser
605     set lusernew [irctolower $newnick]
606     foreach ary $nick_arys {
607         upvar #0 nick_${ary}($luser) old
608         upvar #0 nick_${ary}($lusernew) new
609         if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
610         if {[info exists old]} { set new $old; unset old }
611     }
612     upvar #0 nick_onchans($lusernew) oc
613     foreach ch $oc {
614         upvar #0 chan_nicks($ch) nlist
615         set nlist [grep tn {"$tn" != "$luser"} $nlist]
616         lappend nlist $lusernew
617     }
618     lnick_marktime_start $lusernew "Hi." 500 1
619     nick_case $newnick
620 }
621
622 proc nick_ishere {n} {
623     global nick_counter
624     upvar #0 nick_unique([irctolower $n]) u
625     if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
626     nick_case $n
627 }
628
629 proc msg_JOIN {p c chan} {
630     prefix_nick
631     nick_ishere $n
632     recordlastseen_n $n "joining $chan" 1
633     set nl [irctolower $n]
634     set lchan [irctolower $chan]
635     upvar #0 nick_onchans($nl) oc
636     upvar #0 chan_nicks($lchan) nlist
637     if {![info exists oc]} {
638         global marktime_join_startdelay
639         lnick_marktime_start $nl "Welcome." $marktime_join_startdelay 1
640     }
641     lappend oc $lchan
642     lappend nlist $nl
643 }
644 proc msg_PART {p c chan args} {
645     prefix_nick
646     set msg "leaving $chan"
647     if {[llength $args]} {
648         set why [lindex $args 0]
649         if {"[irctolower $why]" != "[irctolower $n]"} { append msg " ($why)" }
650     }
651     recordlastseen_n $n $msg 1
652     process_kickpart $chan $n
653 }
654 proc msg_QUIT {p c why} {
655     prefix_nick
656     recordlastseen_n $n "leaving ($why)" 0
657     nick_forget $n
658 }
659
660 proc msg_PRIVMSG {p c dest text} {
661     global errorCode
662     
663     prefix_nick
664     if {[ischan $dest]} {
665         recordlastseen_n $n "invoking me in $dest" 1
666         set output $dest
667     } else {
668         recordlastseen_n $n "talking to me" 1
669         set output $n
670     }
671     nick_case $n
672
673     execute_usercommand $p $c $n $output $dest $text
674 }
675
676 proc msg_INVITE {p c n chan} {
677     after 1000 [list dojoin [irctolower $chan]]
678 }
679
680 proc grep {var predicate list} {
681     set o {}
682     upvar 1 $var v
683     foreach v $list {
684         if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
685     }
686     return $o
687 }
688
689 proc msg_353 {p c dest type chan nicklist} {
690     global names_chans nick_onchans
691     set lchan [irctolower $chan]
692     upvar #0 chan_nicks($lchan) nlist
693     lappend names_chans $lchan
694     if {![info exists nlist]} {
695         # We don't think we're on this channel, so ignore it !
696         # Unfortunately, because we don't get a reply to PART,
697         # we have to remember ourselves whether we're on a channel,
698         # and ignore stuff if we're not, to avoid races.  Feh.
699         return
700     }
701     set nlist_new {}
702     foreach user [split $nicklist { }] {
703         regsub {^[@+]} $user {} user
704         if {![string length $user]} continue
705         check_nick $user
706         set luser [irctolower $user]
707         upvar #0 nick_onchans($luser) oc
708         lappend oc $lchan
709         lappend nlist_new $luser
710         nick_ishere $user
711     }
712     set nlist $nlist_new
713 }
714
715 proc msg_366 {p c args} {
716     global names_chans nick_onchans
717     set lchan [irctolower $c]
718     foreach luser [array names nick_onchans] {
719         upvar #0 nick_onchans($luser) oc
720         if {[llength names_chans] > 1} {
721             set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
722         }
723         if {![llength $oc]} { lnick_forget $n }
724     }
725     unset names_chans
726 }
727
728 proc check_username {target} {
729     if {
730         [string length $target] > 8 ||
731         [regexp {[^-0-9a-z]} $target] ||
732         ![regexp {^[a-z]} $target]
733     } { error "invalid username" }
734 }
735
736 proc somedb__head {} {
737     uplevel 1 {
738         set idl [irctolower $id]
739         upvar #0 ${nickchan}db($idl) ndbe
740         binary scan $idl H* idh
741         set idfn $fprefix$idh
742         if {![info exists iddbe] && [file exists $idfn]} {
743             set f [open $idfn r]
744             try_except_finally { set newval [read $f] } {} { close $f }
745             if {[llength $newval] % 2} { error "invalid length" }
746             set iddbe $newval
747         }
748     }
749 }
750
751 proc def_somedb {name arglist body} {
752     foreach {nickchan fprefix} {
753         nick users/n
754         chan chans/c
755         msgs users/m
756     } {
757         proc ${nickchan}db_$name $arglist \
758             "set nickchan $nickchan; set fprefix $fprefix; $body"
759     }
760 }
761
762 def_somedb list {} {
763     set list {}
764     foreach path [glob -nocomplain -path $fprefix *] {
765         binary scan $path "A[string length $fprefix]A*" afprefix thinghex
766         if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
767         lappend list [binary format H* $thinghex]
768     }
769     return $list
770 }
771
772 proc def_somedb_id {name arglist body} {
773     def_somedb $name [concat id $arglist] "somedb__head; $body"
774 }
775
776 def_somedb_id exists {} {
777     return [info exists iddbe]
778 }
779
780 def_somedb_id delete {} {
781     catch { unset iddbe }
782     file delete $idfn
783 }
784
785 set default_settings_nick {
786     timeformat ks
787     marktime off
788     tellsec {secure 600}
789     tellrel {remind 3600 30}
790 }
791
792 set default_settings_chan {
793     autojoin 1
794     mode *
795     userinvite pub
796     topicset {}
797     topicsee {}
798     topictell {}
799 }
800
801 set default_settings_msgs {
802     inbound {}
803     outbound {}
804 }
805 # inbound -> [<nick> <time_t> <message>] ...
806 # outbound -> [<nick> <time_t(earliest)> <count>] ...
807 #   neither are sorted particularly; only one entry per recipient in
808 #   output; both sender and recipient are cased
809
810 def_somedb_id set {args} {
811     upvar #0 default_settings_$nickchan def
812     if {![info exists iddbe]} { set iddbe $def }
813     foreach {key value} [concat $iddbe $args] { set a($key) $value }
814     set newval {}
815     foreach {key value} [array get a] { lappend newval $key $value }
816     set f [open $idfn.new w]
817     try_except_finally {
818         puts $f $newval
819         close $f
820         file rename -force $idfn.new $idfn
821     } {
822     } {
823         catch { close $f }
824     }
825     set iddbe $newval
826 }
827
828 def_somedb_id get {key} {
829     upvar #0 default_settings_$nickchan def
830     if {[info exists iddbe]} {
831         set l [concat $iddbe $def]
832     } else {
833         set l $def
834     }
835     foreach {tkey value} $l {
836         if {"$tkey" == "$key"} { return $value }
837     }
838     error "unset setting $key"
839 }
840
841 proc opt {key} {
842     global calling_nick
843     if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
844     return [nickdb_get $n $key]
845 }
846
847 proc check_notonchan {} {
848     upvar 1 dest dest
849     if {[ischan $dest]} { usererror "That command must be sent privately." }
850 }
851
852 proc nick_securitycheck {strict} {
853     upvar 1 n n
854     if {![nickdb_exists $n]} {
855         usererror "You are unknown to me, use `register'."
856     }
857     set wantu [nickdb_get $n username]
858     if {![string length $wantu]} {
859         if {$strict} {
860             usererror "That feature is only available to secure users, sorry."
861         } else {
862             return
863         }
864     }
865     set luser [irctolower $n]
866     upvar #0 nick_username($luser) nu
867     if {![info exists nu]} {
868         usererror "Nick $n is secure, you must identify yourself first."
869     }
870     if {"$wantu" != "$nu"} {
871         usererror "You are the wrong user -\
872                 the nick $n belongs to $wantu, not $nu."
873     }
874 }
875
876 proc channel_ismanager {channel n} {
877     set mgrs [chandb_get $channel managers]
878     return [expr {[lsearch -exact [irctolower $mgrs] [irctolower $n]] >= 0}]
879 }
880
881 proc channel_securitycheck {channel} {
882     upvar n n
883     if {![channel_ismanager $channel $n]} {
884         usererror "You are not a manager of $channel."
885     }
886     nick_securitycheck 1
887 }
888
889 proc def_chancmd {name body} {
890     proc channel/$name {} \
891             "    upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
892 }
893
894 proc ta_listop {findnow procvalue} {
895     # findnow and procvalue are code fragments which will be executed
896     # in the caller's level.  findnow should set ta_listop_ev to
897     # the current list, and procvalue should treat ta_listop_ev as
898     # a proposed value in the list and check and possibly modify
899     # (canonicalise?) it.  After ta_listop, ta_listop_ev will
900     # be the new value of the list.
901     upvar 1 ta_listop_ev exchg
902     upvar 1 text text
903     set opcode [ta_word]
904     switch -exact _$opcode {
905         _= { }
906         _+ - _- {
907             uplevel 1 $findnow
908             foreach item $exchg { set array($item) 1 }
909         }
910         default {
911             error "list change opcode must be one of + - ="
912         }
913     }
914     foreach exchg [split $text " "] {
915         if {![string length $exchg]} continue
916         uplevel 1 $procvalue
917         if {"$opcode" != "-"} {
918             set array($exchg) 1
919         } else {
920             catch { unset array($exchg) }
921         }
922     }
923     set exchg [lsort [array names array]]
924 }
925
926 def_chancmd manager {
927     ta_listop {
928         if {[chandb_exists $chan]} {
929             set ta_listop_ev [chandb_get $chan managers]
930         } else {
931             set ta_listop_ev [list [irctolower $n]]
932         }
933     } {
934         check_nick $ta_listop_ev
935         set ta_listop_ev [irctolower $ta_listop_ev]
936     }
937     if {[llength $ta_listop_ev]} {
938         chandb_set $chan managers $ta_listop_ev
939         ucmdr "Managers of $chan: $ta_listop_ev" {}
940     } else {
941         chandb_delete $chan
942         ucmdr {} {} "forgets about managing $chan." {}
943     }
944 }
945
946 def_chancmd autojoin {
947     set yesno [ta_word]
948     switch -exact [string tolower $yesno] {
949         no { set nv 0 }
950         yes { set nv 1 }
951         default { error "channel autojoin must be `yes' or `no' }
952     }
953     chandb_set $chan autojoin $nv
954     ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
955             "I won't join $chan when I'm restarted "}] {}
956 }
957
958 def_chancmd userinvite {
959     set nv [string tolower [ta_word]]
960     switch -exact $nv {
961         pub { set txt "!invite will work for $chan, but it won't work by /msg" }
962         here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
963         all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
964         none { set txt "I will not invite anyone to $chan." }
965         default {
966             error "channel userinvite must be `pub', `here', `all' or `none'
967         }
968     }
969     chandb_set $chan userinvite $nv
970     ucmdr $txt {}
971 }
972
973 def_chancmd topic {
974     set what [ta_word]
975     switch -exact $what {
976         leave {
977             ta_nomore
978             chandb_set $chan topicset {}
979             ucmdr "I won't ever change the topic of $chan." {}
980         }
981         set {
982             set t [string trim $text]
983             if {![string length $t]} {
984                 error "you must specific the topic to set"
985             }
986             chandb_set $chan topicset $t
987             ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
988         }
989         see - tell {
990             ta_listop {
991                 set ta_listop_ev [chandb_get $chan topic$what]
992             } {
993                 if {"$ta_listop_ev" != "*"} {
994                     if {![ischan $ta_listop_ev]} {
995                         error "bad channel \`$ta_listop_ev' in topic $what"
996                     }
997                     set ta_listop_ev [irctolower $ta_listop_ev]
998                 }
999             }
1000             chandb_set $chan topic$what $ta_listop_ev
1001             ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1002         }
1003         default {
1004             usererror "Unknown channel topic subcommand - see help channel."
1005         }
1006     }
1007 }
1008
1009 def_chancmd mode {
1010     set mode [ta_word]
1011     if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1012         error {channel mode must be * or match ([-+][imnpst]+)+}
1013     }
1014     chandb_set $chan mode $mode
1015     if {"$mode" == "*"} {
1016         ucmdr "I won't ever change the mode of $chan." {}
1017     } else {
1018         ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
1019     }
1020 }
1021
1022 def_chancmd show {
1023     if {[chandb_exists $chan]} {
1024         set l "Settings for $chan: autojoin "
1025         append l [lindex {no yes} [chandb_get $chan autojoin]]
1026         append l ", mode " [chandb_get $chan mode]
1027         append l ", userinvite " [chandb_get $chan userinvite] "."
1028         append l "\nManagers: "
1029         append l [join [chandb_get $chan managers] " "]
1030         foreach {ts sep} {see "\n" tell "  "} {
1031             set t [chandb_get $chan topic$ts]
1032             append l $sep
1033             if {[llength $t]} {
1034                 append l "Topic $ts list: $t."
1035             } else {
1036                 append l "Topic $ts list is empty."
1037             }
1038         }
1039         append l "\n"
1040         set t [chandb_get $chan topicset]
1041         if {[string length $t]} {
1042             append l "Topic to set: $t"
1043         } else {
1044             append l "I will not change the topic."
1045         }
1046         ucmdr {} $l
1047     } else {
1048         ucmdr {} "The channel $chan is not managed."
1049     }
1050 }
1051
1052 proc channelmgr_monoop {} {
1053     upvar 1 dest dest
1054     upvar 1 text text
1055     upvar 1 n n
1056     upvar 1 p p
1057     upvar 1 target target
1058     global chan_nicks
1059
1060     prefix_nick
1061
1062     if {[ischan $dest]} { set target $dest }
1063     if {[ta_anymore]} { set target [ta_word] }
1064     ta_nomore
1065     if {![info exists target]} {
1066         usererror "You must specify, or invoke me on, the relevant channel."
1067     }
1068     if {![info exists chan_nicks([irctolower $target])]} {
1069         usererror "I am not on $target."
1070     }
1071     if {![ischan $target]} { error "not a valid channel" }
1072
1073     if {![chandb_exists $target]} {
1074         usererror "$target is not a managed channel."
1075     }
1076     channel_securitycheck $target
1077 }
1078
1079 def_ucmd op {
1080     channelmgr_monoop
1081     sendout MODE $target +o $n
1082 }
1083
1084 def_ucmd leave {
1085     channelmgr_monoop
1086     doleave $target
1087 }
1088
1089 def_ucmd invite {
1090     global chan_nicks errorCode errorInfo
1091     prefix_nick
1092     
1093     if {[ischan $dest]} {
1094         set target $dest
1095         set onchan 1
1096     } else {
1097         set target [ta_word]
1098         set onchan 0
1099     }
1100     set ltarget [irctolower $target]
1101     if {![ischan $target]} { error "$target is not a channel" }
1102     if {![info exists chan_nicks($ltarget)]} {
1103         usererror "I am not on $target."
1104     }
1105     set ui [chandb_get $ltarget userinvite]
1106     if {[catch {
1107         if {"$ui" == "pub" && !$onchan} {
1108             usererror "Invitations to $target must be made there with !invite."
1109         }
1110         if {"$ui" != "all"} {
1111             if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1112                 usererror "Invitations to $target may only be made\
1113                         by a user on the channel."
1114             }
1115         }
1116         if {"$ui" == "none"} {
1117             usererror "Sorry, I've not been authorised\
1118                     to invite people to $target."
1119         }
1120     } emsg]} {
1121         if {"$errorCode" == "BLIGHT USER" && [channel_ismanager $target $n]} {
1122             if {[catch {
1123                 nick_securitycheck 1
1124             } emsg2]} {
1125                 if {"$errorCode" == "BLIGHT USER"} {
1126                     usererror "$emsg2  Therefore you can't use your\
1127                             channel manager privilege.  $emsg"
1128                 } else {
1129                     error $error $errorInfo $errorCode
1130                 }
1131             }
1132         } else {
1133             error $emsg $errorInfo $errorCode
1134         }
1135     }
1136     if {![ta_anymore]} {
1137         usererror "You have to say who to invite."
1138     }
1139     set invitees {}
1140     while {[ta_anymore]} {
1141         set invitee [ta_word]
1142         check_nick $invitee
1143         lappend invitees $invitee
1144     }
1145     foreach invitee $invitees {
1146         sendout INVITE $invitee $ltarget
1147     }
1148     set who [lindex $invitees 0]
1149     switch -exact llength $invitees {
1150         0 { error "zero invitees" }
1151         1 { }
1152         2 { append who " and [lindex $invitees 1]" }
1153         * {
1154             set who [join [lreplace $invitees end end] ", "]
1155             append who " and [lindex $invitees [llength $invitees]]"
1156         }
1157     }
1158     ucmdr {} {} {} "invites $who to $target."
1159 }
1160
1161 def_ucmd channel {
1162     if {[ischan $dest]} { set target $dest }
1163     if {![ta_anymore]} {
1164         set subcmd show
1165     } else {
1166         set subcmd [ta_word]
1167     }
1168     if {[ischan $subcmd]} {
1169         set target $subcmd
1170         if {![ta_anymore]} {
1171             set subcmd show
1172         } else {
1173             set subcmd [ta_word]
1174         }
1175     }
1176     if {![info exists target]} { error "privately, you must specify a channel" }
1177     set procname channel/$subcmd
1178     if {"$subcmd" != "show"} {
1179         if {[catch { info body $procname }]} {
1180             usererror "unknown channel setting $subcmd."
1181         }
1182         prefix_nick
1183         if {[chandb_exists $target]} {
1184             channel_securitycheck $target
1185         } else {
1186             nick_securitycheck 1
1187             upvar #0 chan_initialop([irctolower $target]) io
1188             upvar #0 nick_unique([irctolower $n]) u
1189             if {![info exists io]} {
1190                 usererror "$target is not a managed channel."
1191             }
1192             if {"$io" != "$u"} {
1193                 usererror "You are not the interim manager of $target."
1194             }
1195             if {"$subcmd" != "manager"} {
1196                 usererror "Please use `channel manager' first."
1197             }
1198         }
1199     }
1200     channel/$subcmd
1201 }
1202
1203 proc tell_effective_sec {n} {
1204     set l [nickdb_get $n tellsec]
1205     set u [nickdb_get $n username]
1206     if {"[lindex $l 0]" == "secure" && ![string length $u]} { set l insecure }
1207     return $l
1208 }
1209
1210 proc tell_peernicks {text} {
1211     set text [irctolower [string trim $text]]
1212     set senders [split $text " "]
1213     foreach sender $senders {
1214         if {[catch { check_nick $sender } emsg]} {
1215             error "invalid sender nick `$sender': $emsg" $errorInfo $errorCode
1216         }
1217     }
1218     return $senders
1219 }
1220
1221 proc msgsdb_set_maydelete {n key l otherkey} {
1222     msgsdb_set $n $key $l
1223     if {[llength $l]} return
1224     if {[llength [msgsdb_get $n $otherkey]]} return
1225     msgsdb_delete $n
1226 }
1227
1228 proc tell_delete_msgs {lsenders lrecip} {
1229     set ninbound {}
1230     set ndel 0
1231     foreach {s t m} [msgsdb_get $recip inbound] {
1232         if {[llength $senders]} {
1233             if {[lsearch -exact $senders [irctolower $s]] == -1} {
1234                 lappend ninbound $s $t $m
1235                 continue
1236             }
1237         }
1238         set rsenders($s) 1
1239         incr ndel
1240     }
1241     msgsdb_set_maydelete $recip inbound $ninbound outbound
1242     if {![llength $ninbound]} {
1243         upvar #0 nick_telling($lrecip) telling
1244         catch { unset telling }
1245     }
1246     foreach s [array names rsenders] {
1247         set noutbound {}
1248         foreach {r t c} [msgsdb_get $s outbound] {
1249             if {"[irctolower $r]" == "$lrecip"} continue
1250             lappend noutbound $r $t $c
1251         }
1252         msgsdb_set_maydelete $s outbound $noutbound inbound
1253     }
1254     return $ndel
1255 }
1256
1257 def_ucmd untell {
1258     prefix_nick
1259     check_notonchan
1260     nick_securitycheck 0
1261     set recipients [tell_peernicks $text]
1262     if {![llength $recipients]} {
1263         usererror "You must say which recipients' messages from you to forget."
1264     }
1265     set ndel 0
1266     foreach recip $recipients {
1267         incr ndel [tell_delete_msgs [irctolower $n] $recip]
1268     }
1269     ucmdr "Removed $ndel as yet undelivered message(s)." {}
1270 }
1271
1272 def_ucmd delmsg {
1273     global errorInfo errorCode
1274     prefix_nick
1275     set nl [irctolower $n]
1276     check_notonchan
1277     manyset [tell_effective_sec $n] sec secwhen
1278     switch -exact $sec {
1279         insecure { }
1280         refuse - mailto {
1281             usererror \
1282  "There are no messages to delete\
1283  because your message disposition prevents them from being left."
1284         }
1285         secure {
1286             nick_securitycheck 1
1287         }
1288         default {
1289             error "delmsg sec $sec"
1290         }
1291     }
1292     tell_getcstate
1293     if {"$stt" != "passed"} {
1294         usererror \
1295  "There are message(s) you've not yet seen; I'll deliver them to you now.\
1296   If you actually want to delete them, just tell me `delmsg' again."
1297     }
1298     set senders [tell_peernicks $text]
1299     set ndel [tell_delete_msgs [irctolower $senders] [irctolower $n]]
1300     if {!$ndel} {
1301         if {[llength $senders]} {
1302             ucmdr "No relevant incoming messages to delete." {}
1303         } else {
1304             ucmdr "No incoming messages to delete." {}
1305         }
1306     }
1307     switch -exact [llength $senders] {
1308         0 { ucmdr {} {} "deletes your $ndel message(s)." }
1309         1 { ucmdr {} {} "deletes your $ndel message(s) from $senders." }
1310         default {
1311             ucmdr {} {} "deletes your $ndel message(s) from\
1312  [lreplace $senders end end] and [lindex $senders end]."
1313         }
1314     }
1315 }
1316
1317 def_ucmd tell {
1318     global nick_case ownmailaddr ownfullname
1319     
1320     prefix_nick
1321     set target [ta_word]
1322     if {![string length $text]} { error "tell them what?" }
1323     if {[string length $text] > 400} { error "message too long" }
1324
1325     set ltarget [irctolower $target]
1326     set ctarget $target
1327     if {[info exists nick_case($ltarget)]} { set ctarget $nick_case($ltarget) }
1328
1329     manyset [tell_effective_sec $target] sec mailtoint mailwhy
1330     manyset [nickdb_get $target tellrel] rel relint relwithin
1331     switch -exact $sec {
1332         insecure - secure {
1333             set now [clock seconds]
1334             set inbound [msgsdb_get $ltarget inbound]
1335             lappend inbound $n $now $text
1336             msgsdb_set $ltarget inbound $inbound
1337
1338             set outbound [msgsdb_get $n outbound]
1339             set noutbound {}
1340             set found 0
1341             foreach {recip time count} $outbound {
1342                 if {"[irctolower $recip]" == "$ltarget"} {
1343                     incr count
1344                     set recip $ctarget
1345                     set found 1
1346                 }
1347                 lappend noutbound $recip $time $count
1348             }
1349             if {!$found} {
1350                 lappend noutbound $ctarget $now 1
1351             }
1352             msgsdb_set $n outbound $noutbound
1353             set msg "OK, I'll tell $ctarget"
1354             if {$found} { append msg " that too" }
1355             append msg ", "
1356             if {"$sec" != "secure"} {
1357                 switch -exact $rel {
1358                     unreliable { append msg "neither reliably nor securely" }
1359                     remind { append msg "pretty reliably, but not securely" }
1360                     pester { append msg "reliably but not securely" }
1361                 }
1362             } else {
1363                 switch -exact $rel {
1364                     unreliable { append msg "securely but not reliably" }
1365                     remind { append msg "securely and pretty reliably" }
1366                     pester { append msg "reliably and securely" }
1367                 }
1368             }
1369             append msg .
1370             tell_event $ltarget msgsarrive
1371             ucmdr $msg {}
1372         }
1373         mailto {
1374             set fmtmsg [exec fmt << " $text"]
1375             exec /usr/sbin/sendmail -odb -oi -t -oee -f $mailwhy \
1376                     > /dev/null << \
1377  "From: $ownmailaddr ($ownfullname)
1378 To: $mailtoint
1379 Subject: IRC tell from $n
1380
1381 $n asked me[expr {[ischan $dest] ? " on $dest" : ""}] to tell you:
1382 [exec fmt << " $text"]
1383
1384 (This message was for your nick $ctarget; your account $mailwhy
1385  arranged for it to be forwarded to $mailtoint.)
1386 "
1387             ucmdr \
1388  "I've mailed $ctarget, which is what they prefer." \
1389                 {}
1390         }
1391         refuse {
1392             usererror "Sorry, $ctarget does not want me to take messages."
1393         }
1394         default {
1395             error "bad tellsec $sec"
1396         }
1397     }
1398 }
1399
1400 def_ucmd who {
1401     if {[ta_anymore]} {
1402         set target [ta_word]; ta_nomore
1403         set myself 1
1404     } else {
1405         prefix_nick
1406         set target $n
1407         set myself [expr {"$target" != "$n"}]
1408     }
1409     set ltarget [irctolower $target]
1410     upvar #0 nick_case($ltarget) ctarget
1411     set nshow $target
1412     if {[info exists ctarget]} {
1413         upvar #0 nick_onchans($ltarget) oc
1414         upvar #0 nick_username($ltarget) nu
1415         if {[info exists oc]} { set nshow $ctarget }
1416     }
1417     if {![nickdb_exists $ltarget]} {
1418         set ol "$nshow is not a registered nick."
1419     } elseif {[string length [set username [nickdb_get $target username]]]} {
1420         set ol "The nick $nshow belongs to the user $username."
1421     } else {
1422         set ol "The nick $nshow is registered (but not to a username)."
1423     }
1424     if {![info exists ctarget] || ![info exists oc]} {
1425         if {$myself} {
1426             append ol "\nI can't see $nshow on anywhere."
1427         } else {
1428             append ol "\nYou aren't on any channels with me."
1429         }
1430     } elseif {![info exists nu]} {
1431         append ol "\n$nshow has not identified themselves."
1432     } elseif {![info exists username]} {
1433         append ol "\n$nshow has identified themselves as the user $nu."
1434     } elseif {"$nu" != "$username"} {
1435         append ol "\nHowever, $nshow is being used by the user $nu."
1436     } else {
1437         append ol "\n$nshow has identified themselves to me."
1438     }
1439     ucmdr {} $ol
1440 }
1441
1442 def_ucmd register {
1443     prefix_nick
1444     check_notonchan
1445     set old [nickdb_exists $n]
1446     if {$old} { nick_securitycheck 0 }
1447     set luser [irctolower $n]
1448     switch -exact [string tolower [string trim $text]] {
1449         {} {
1450             upvar #0 nick_username($luser) nu
1451             if {![info exists nu]} {
1452                 ucmdr {} \
1453  "You must identify yourself before using `register'.  See `help identify', or use `register insecure'."
1454             }
1455             nickdb_set $n username $nu
1456             ucmdr {} {} "makes a note of your username." {}
1457         }
1458         delete {
1459             nickdb_delete $n
1460             ucmdr {} {} "forgets your nickname." {}
1461         }
1462         insecure {
1463             nickdb_set $n username {}
1464             if {$old} {
1465                 ucmdr {} "Security is now disabled for your nickname !"
1466             } else {
1467                 ucmdr {} "This is fine, but bear in mind that people will be able to mess with your settings.  Channel management features need a secure registration." "makes an insecure registration for your nick."
1468             }
1469         }
1470         default {
1471             error "you mean register / register delete / register insecure"
1472         }
1473     }
1474 }
1475
1476 proc timeformat_desc {tf} {
1477     switch -exact $tf {
1478         ks { return "Times will be displayed in seconds or kiloseconds." }
1479         hms { return "Times will be displayed in hours, minutes, etc." }
1480         default { error "invalid timeformat: $v" }
1481     }
1482 }
1483
1484 set settings {}
1485 proc def_setting {opt show_body set_body} {
1486     global settings
1487     lappend settings $opt
1488     proc set_show/$opt {} "
1489         upvar 1 n n
1490         set opt $opt
1491         $show_body"
1492     if {![string length $set_body]} return
1493     proc set_set/$opt {} "
1494         upvar 1 n n
1495         upvar 1 text text
1496         set opt $opt
1497         $set_body"
1498 }
1499
1500 proc tellme_sec_desc {v n} {
1501     manyset $v sec mailtoint
1502     switch -exact $sec {
1503         insecure {
1504             return "I'll tell you your messages whenever I see you."
1505         }
1506         secure {
1507             if {[string length [nickdb_get $n username]]} {
1508                 return \
1509  "I'll keep the bodies of your messages private until you identify yourself, reminding you every [showintervalsecs $mailtoint 1]."
1510             } else {
1511                 return \
1512  "I'll tell you your messages whenever I see you.\
1513   (Secure message delivery is enabled, but your nick is not registered\
1514  securely.  See `help register'.)"
1515             }
1516         }
1517         refuse {
1518             return "I shan't accept messages for you."
1519         }
1520         mailto {
1521             return "I'll forward your messages by email to $mailtoint."
1522         }
1523         default {
1524             error "bad tellsec $sec"
1525         }
1526     }
1527 }
1528
1529 proc tellme_rel_desc {v} {
1530     manyset $v rel every within
1531     switch -exact $rel {
1532         unreliable {
1533             return "As soon as I've told you, I'll forget the message - note that this means messages can get lost !"
1534         }
1535         pester {
1536             set u {}
1537         }
1538         remind {
1539             set u ", or talk on channel within [showintervalsecs $within 1] of me having told you"
1540         }
1541         default {
1542             error "bad tellrel $rel"
1543         }
1544     }
1545     return "I'll remind you every [showintervalsecs $every 1] until you say delmsg$u."
1546 }
1547
1548 def_setting timeformat {
1549     set tf [nickdb_get $n timeformat]
1550     return "$tf: [timeformat_desc $tf]"
1551 } {
1552     set tf [string tolower [ta_word]]
1553     ta_nomore
1554     set desc [timeformat_desc $tf]
1555     nickdb_set $n timeformat $tf
1556     ucmdr {} $desc
1557 }
1558
1559 proc marktime_desc {mt} {
1560     if {"$mt" == "off"} {
1561         return "I will not send you periodic messages."
1562     } elseif {"$mt" == "once"} {
1563         return "I will send you one informational message when I see you."
1564     } else {
1565         return "I'll send you a message every [showintervalsecs $mt 0]."
1566     }
1567 }
1568
1569 def_setting marktime {
1570     set mt [nickdb_get $n marktime]
1571     set p $mt
1572     if {[string match {[0-9]*} $mt]} { append p s }
1573     append p ": "
1574     append p [marktime_desc $mt]
1575     return $p
1576 } {
1577     global marktime_min
1578     set mt [string tolower [ta_word]]
1579     ta_nomore
1580
1581     if {"$mt" == "off" || "$mt" == "once"} {
1582     } else {
1583         set mt [parse_interval $mt $marktime_min]
1584     }
1585     nickdb_set $n marktime $mt
1586     lnick_marktime_start [irctolower $n] "So:" 500 0
1587     ucmdr {} [marktime_desc $mt]
1588 }
1589
1590 def_setting security {
1591     set s [nickdb_get $n username]
1592     if {[string length $s]} {
1593         return "Your nick, $n, is controlled by the user $s."
1594     } else {
1595         return "Your nick, $n, is not secure."
1596     }
1597 } {}
1598
1599 proc tellme_setting_sec_simple {} {
1600     uplevel 1 {
1601         ta_nomore
1602         set sr sec
1603         set v $setting
1604     }
1605 }
1606
1607 proc tellme_setting_neednomsgs {} {
1608     uplevel 1 {
1609         if {[llength [msgsdb_get $n inbound]]} {
1610             usererror "You must delete the messages you have, first."
1611         }
1612     }
1613 }
1614
1615 def_setting tellme {
1616     set secv [nickdb_get $n tellsec]
1617     set ms [tellme_sec_desc $secv $n]
1618     manyset $secv sec
1619     switch -exact $sec {
1620         insecure - secure {
1621             set mr [tellme_rel_desc [nickdb_get $n tellrel]]
1622             return "$ms  $mr"
1623         }
1624         refuse - mailto {
1625             return $ms
1626         }
1627     }
1628 } {
1629     set setting [string tolower [ta_word]]
1630     switch -exact $setting {
1631         insecure {
1632             tellme_setting_sec_simple
1633         }
1634         secure {
1635             set every [ta_interval_optional 60 600]
1636             ta_nomore
1637             set sr sec
1638             set v [list secure $every]
1639         }
1640         refuse {
1641             telling_setting_neednomsgs
1642             telling_setting_sec_simple
1643         }
1644         mailto {
1645             telling_setting_neednomsgs
1646             set u [nickdb_get $n username]
1647             if {[string length $u]} {
1648                 usererror \
1649  "Sorry, you must register securely to have your messages mailed\
1650  (to prevent the use of this feature for spamming).  See `help register'."
1651             }
1652             set sr sec
1653             set v [list mailto [ta_word] $u]
1654         }
1655         unreliable - pester - remind {
1656             manyset [nickdb_get $n tellsec] sec
1657             switch -exact $sec {
1658                 refuse - mailto {
1659                     usererror \
1660  "You can't change your message delivery conditions when\
1661  your message disposition prevents messages from being left."
1662                 }
1663             }
1664             set sr rel
1665             set v $setting
1666             if {"$setting" != "unreliable"} {
1667                 set every [parse_interval_optional 300 3600]
1668                 lappend v $every
1669             }
1670             if {"$setting" == "remind"} {
1671                 set within [ta_interval_optional 5 30]
1672                 if {$within > $every} {
1673                     error "remind interval must be at least time to respond"
1674                 }
1675                 lappend v $within
1676             }
1677             ta_nomore
1678         }
1679         default {
1680             error "invalid tellme setting $setting"
1681         }
1682     }
1683     nickdb_set $n tell$sr $v
1684     ucmdr [tellme_${sr}_desc $v] {}
1685 }
1686
1687 proc lnick_checktold {luser} {
1688     set ml [msgsdb_get $luser outbound]
1689     if {![llength $ml]} return
1690     set is1 [expr {[llength $ml]==3}]
1691     set m1 "FYI, I haven't yet passed on your"
1692     set ol {}
1693     set now [clock seconds]
1694     while {[llength $ml]} {
1695         manyset $ml r t n
1696         set ml [lreplace $ml 0 2]
1697         set td [expr {$now-$t}]
1698         if {$n == 1} {
1699             set iv [showinterval $td]
1700             set ifo "$r, $iv"
1701             set if1 "message to $r, $iv."
1702         } else {
1703             set iv [showintervalsecs $td 0]
1704             set ifo "$r, $n messages, oldest $iv"
1705             set if1 "$n messages to $r, oldest $iv."
1706         }
1707         if {$is1} {
1708             sendprivmsg $luser "$m1 $if1"
1709             return
1710         } else {
1711             lappend ol " to $ifo[expr {[llength $ml] ? ";" : "."}]"
1712         }
1713     }
1714     sendprivmsg $luser "$m1 messages:"
1715     msendprivmsg $luser $ol
1716 }
1717
1718 def_ucmd set {
1719     global settings
1720     prefix_nick
1721     check_notonchan
1722     if {![nickdb_exists $n]} {
1723         ucmdr {} "You are unknown to me and so have no settings.  (Use `register'.)"
1724     }
1725     if {![ta_anymore]} {
1726         set ol {}
1727         foreach opt $settings {
1728             lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1729         }
1730         ucmdr {} [join $ol "\n"]
1731     } else {
1732         set opt [ta_word]
1733         if {[catch { info body set_show/$opt }]} {
1734             error "no setting $opt"
1735         }
1736         if {![ta_anymore]} {
1737             ucmdr {} "$opt: [set_show/$opt]"
1738         } else {
1739             nick_securitycheck 0
1740             if {[catch { info body set_set/$opt }]} {
1741                 error "setting $opt cannot be set with `set'"
1742             }
1743             set_set/$opt
1744         }
1745     }
1746 }
1747
1748 def_ucmd identpass {
1749     set username [ta_word]
1750     set passmd5 [md5sum "[ta_word]\n"]
1751     ta_nomore
1752     prefix_nick
1753     check_notonchan
1754     set luser [irctolower $n]
1755     upvar #0 nick_onchans($luser) onchans
1756     if {![info exists onchans] || ![llength $onchans]} {
1757         ucmdr "You must be on a channel with me to identify yourself." {}
1758     }
1759     check_username $username
1760     exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1761             irc-identpass $n
1762     upvar #0 nick_username($luser) rec_username
1763     set rec_username $username
1764     ucmdr "Pleased to see you, $username." {}
1765     tell_event $luser ident
1766 }
1767
1768 def_ucmd summon {
1769     set target [ta_word]
1770     ta_nomore
1771     check_username $target
1772     prefix_nick
1773
1774     upvar #0 lastsummon($target) ls
1775     set now [clock seconds]
1776     if {[info exists ls]} {
1777         set interval [expr {$now - $ls}]
1778         if {$interval < 30} {
1779             ucmdr {} \
1780  "Please be patient; $target was summoned only [showinterval $interval]."
1781         }
1782     }
1783     regsub {^[^!]*!} $p {} path
1784     if {[catch {
1785         exec userv --timeout 3 $target irc-summon $n $path \
1786                 [expr {[ischan $dest] ? "$dest" : ""}] \
1787                 < /dev/null
1788     } rv]} {
1789         regsub -all "\n" $rv { / } rv
1790         error $rv
1791     }
1792     if {[regexp {^problem (.*)} $rv dummy problem]} {
1793         ucmdr {} "The user `$target' $problem."
1794     } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1795         set idletime [expr {$now - $idlesince}]
1796         set ls $now
1797         ucmdr {} {} {} "invites $target ($tty[expr {
1798             $idletime > 10 ? ", idle for [showintervalsecs $idletime 0]" : ""
1799         }]) to [expr {
1800             [ischan $dest] ? "join us here" : "talk to you"
1801         }]."
1802     } else {
1803         error "unexpected response from userv service: $rv"
1804     }
1805 }
1806
1807 proc md5sum {value} { exec md5sum << $value }
1808
1809 def_ucmd seen {
1810     global lastseen nick
1811     prefix_nick
1812     set ncase [ta_nick]
1813     set nlower [irctolower $ncase]
1814     ta_nomore
1815     set now [clock seconds]
1816     if {"$nlower" == "[irctolower $nick]"} {
1817         usererror "I am not self-aware."
1818     } elseif {![info exists lastseen($nlower)]} {
1819         set rstr "I've never seen $ncase."
1820     } else {
1821         manyset $lastseen($nlower) realnick time what
1822         set howlong [expr {$now - $time}]
1823         set string [showinterval $howlong]
1824         set rstr "I last saw $realnick $string, $what."
1825     }
1826     if {[ischan $dest]} {
1827         set where $dest
1828     } else {
1829         set where {}
1830     }
1831     upvar #0 lookedfor($nlower) lf
1832     if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1833     set lf [list [list $now $n $where]]
1834     foreach v $oldvalue {
1835         if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1836         lappend lf $v
1837     }
1838     ucmdr {} $rstr
1839 }
1840
1841 proc lnick_marktime_cancel {luser} {
1842     upvar #0 nick_markid($luser) mi
1843     if {![info exists mi]} return
1844     catch { after cancel $mi }
1845     catch { unset mi }
1846 }
1847
1848 proc lnick_marktime_doafter {luser why ms mentiontold} {
1849     lnick_marktime_cancel $luser
1850     upvar #0 nick_markid($luser) mi
1851     set mi [after $ms [list lnick_marktime_now $luser $why 0]]
1852 }
1853
1854 proc lnick_marktime_reset {luser} {
1855     set mt [nickdb_get $luser marktime]
1856     if {"$mt" == "off" || "$mt" == "once"} return
1857     lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}] 0
1858 }
1859
1860 proc lnick_marktime_start {luser why ms mentiontold} {
1861     set mt [nickdb_get $luser marktime]
1862     if {"$mt" == "off"} {
1863         lnick_marktime_cancel $luser
1864         if {$mentiontold} { after $ms [list lnick_checktold $luser] }
1865     } else {
1866         lnick_marktime_doafter $luser $why $ms $mentiontold
1867     }
1868 }
1869
1870 proc lnick_marktime_now {luser why mentiontold} {
1871     upvar #0 nick_onchans($luser) oc
1872     global calling_nick
1873     set calling_nick $luser
1874     sendprivmsg $luser [lnick_pingstring $why $oc ""]
1875     if {$mentiontold} { lnick_checktold $luser }
1876     lnick_marktime_reset $luser
1877 }    
1878
1879 proc lnick_pingstring {why oc apstring} {
1880     global nick_onchans
1881     catch { exec uptime } uptime
1882     set nnicks [llength [array names nick_onchans]]
1883     if {[regexp \
1884  {^ *([0-9:apm]+) +up.*, +(\d+) users?, +load average: +([0-9., ]+) *$} \
1885             $uptime dummy time users load]} {
1886         regsub -all , $load {} load
1887         set uptime "$time  $nnicks/$users  $load"
1888     } else {
1889         append uptime ", $nnicks nicks"
1890     }
1891     if {[llength $oc]} {
1892         set best_la 0
1893         set activity quiet
1894         foreach ch $oc {
1895             upvar #0 chan_lastactivity($ch) la
1896             if {![info exists la]} continue
1897             if {$la <= $best_la} continue
1898             set since [showintervalsecs [expr {[clock seconds]-$la}] 1]
1899             set activity "$ch $since"
1900             set best_la $la
1901         }
1902     } else {
1903         set activity unseen
1904     }
1905     set str $why
1906     append str "  " $uptime "  " $activity
1907     if {[string length $apstring]} { append str "  " $apstring }
1908     return $str
1909 }
1910
1911 def_ucmd ping {
1912     prefix_nick
1913     set ln [irctolower $n]
1914     if {[ischan $dest]} {
1915         set oc [irctolower $dest]
1916     } else {
1917         global nick_onchans
1918         if {[info exists nick_onchans($ln)]} {
1919             set oc $nick_onchans($ln)
1920         } else {
1921             set oc {}
1922         }
1923         if {[llength $oc]} { lnick_marktime_reset $ln }
1924     }
1925     lnick_checktold $ln
1926     ucmdr {} [lnick_pingstring "Pong!" $oc $text]
1927 }
1928
1929 proc ensure_globalsecret {} {
1930     global globalsecret
1931     
1932     if {[info exists globalsecret]} return
1933     set gsfile [open /dev/urandom r]
1934     fconfigure $gsfile -translation binary
1935     set globalsecret [read $gsfile 32]
1936     binary scan $globalsecret H* globalsecret
1937     close $gsfile
1938     unset gsfile
1939 }
1940
1941 proc connected {} {
1942     foreach chan [chandb_list] {
1943         if {[chandb_get $chan autojoin]} { dojoin $chan }
1944     }
1945 }
1946
1947 ensure_globalsecret
1948 loadhelp
1949 ensure_connecting