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