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