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