chiark / gitweb /
Use correct settings when Time passes. regsub away *all* the ,s in load.
[ircbot] / bot.tcl
CommitLineData
e58e51a8 1# Core bot code
9bc33297 2
e58e51a8
IJ
3proc defset {varname val} {
4 upvar #0 $varname var
5 if {![info exists var]} { set var $val }
6}
7
8# must set host
9defset port 6667
10
11defset nick testbot
12defset ownfullname "testing bot"
13defset ownmailaddr test-irc-bot@example.com
e1ba63be 14
e58e51a8
IJ
15defset musthaveping_ms 10000
16defset out_maxburst 6
17defset out_interval 2100
18defset out_lag_lag 5000
19defset out_lag_very 25000
7818b6af 20
ebbae0a9
IJ
21defset marktime_min 300
22defset marktime_join_startdelay 5000
23
20087363
IJ
24proc manyset {list args} {
25 foreach val $list var $args {
26 upvar 1 $var my
27 set my $val
28 }
29}
30
7a70431a
IJ
31proc try_except_finally {try except finally} {
32 global errorInfo errorCode
33 set er [catch { uplevel 1 $try } emsg]
34 if {$er} {
35 set ei $errorInfo
36 set ec $errorCode
37 if {[catch { uplevel 1 $except } emsg3]} {
38 append ei "\nALSO ERROR HANDLING ERROR:\n$emsg3"
39 }
40 }
41 set er2 [catch { uplevel 1 $finally } emsg2]
42 if {$er} {
43 if {$er2} {
44 append ei "\nALSO ERROR CLEANING UP:\n$emsg2"
45 }
46 return -code $er -errorinfo $ei -errorcode $ec $emsg
47 } elseif {$er2} {
48 return -code $er2 -errorinfo $errorInfo -errorcode $errorCode $emsg2
49 } else {
50 return $emsg
51 }
52}
53
7818b6af
IJ
54proc out__vars {} {
55 uplevel 1 {
56 global out_queue out_creditms out_creditat out_interval out_maxburst
57 global out_lag_lag out_lag_very
58#set pr [lindex [info level 0] 0]
59#puts $pr>[clock seconds]|$out_creditat|$out_creditms|[llength $out_queue]<
60 }
61}
62
63proc out_lagged {} {
64 out__vars
65 if {[llength $out_queue]*$out_interval > $out_lag_very} {
66 return 2
67 } elseif {[llength $out_queue]*$out_interval > $out_lag_lag} {
68 return 1
69 } else {
70 return 0
71 }
72}
73
74proc out_restart {} {
75 out__vars
76
77 set now [clock seconds]
78 incr out_creditms [expr {($now - $out_creditat) * 1000}]
79 set out_creditat $now
80 if {$out_creditms > $out_maxburst*$out_interval} {
81 set out_creditms [expr {$out_maxburst*$out_interval}]
82 }
83 out_runqueue $now
84}
85
86proc out_runqueue {now} {
cc2d31de 87 global sock
7818b6af
IJ
88 out__vars
89
90 while {[llength $out_queue] && $out_creditms >= $out_interval} {
91#puts rq>$now|$out_creditat|$out_creditms|[llength $out_queue]<
92 manyset [lindex $out_queue 0] orgwhen msg
93 set out_queue [lrange $out_queue 1 end]
94 if {[llength $out_queue]} {
95 append orgwhen "+[expr {$now - $orgwhen}]"
dce9eb94 96 append orgwhen "([llength $out_queue])"
7818b6af
IJ
97 }
98 puts "$orgwhen -> $msg"
99 puts $sock $msg
100 incr out_creditms -$out_interval
101 }
102 if {[llength $out_queue]} {
103 after $out_interval out_nextmessage
104 }
105}
106
107proc out_nextmessage {} {
108 out__vars
109 set now [clock seconds]
110 incr out_creditms $out_interval
111 set out_creditat $now
112 out_runqueue $now
113}
114
115proc sendout_priority {priority command args} {
116 global sock out_queue
9bc33297
IJ
117 if {[llength $args]} {
118 set la [lindex $args end]
119 set args [lreplace $args end end]
120 foreach i $args {
121 if {[regexp {[: ]} $i]} {
cc2d31de 122 error "bad argument in output $i ($command $args)"
9bc33297
IJ
123 }
124 }
cc2d31de 125 lappend args :$la
9bc33297
IJ
126 }
127 set args [lreplace $args 0 -1 $command]
cc2d31de 128 set string [join $args { }]
7818b6af
IJ
129 set now [clock seconds]
130 set newe [list $now $string]
131 if {$priority} {
132 set out_queue [concat [list $newe] $out_queue]
133 } else {
134 lappend out_queue $newe
135 }
136 if {[llength $out_queue] == 1} {
137 out_restart
138 }
9bc33297 139}
9bc33297 140
7818b6af
IJ
141proc sendout {command args} { eval sendout_priority [list 0 $command] $args }
142
9bc33297
IJ
143proc log {data} {
144 puts $data
145}
146
147proc logerror {data} {
148 log $data
cc2d31de
IJ
149}
150
151proc saveeic {} {
152 global saveei saveec errorInfo errorCode
153
154 set saveei $errorInfo
155 set saveec $errorCode
156
157 puts ">$saveec|$saveei<"
158}
159
160proc bgerror {msg} {
161 global save
162 logerror $msg
163 saveeic
164}
9bc33297
IJ
165
166proc onread {args} {
17bfe24c 167 global sock nick calling_nick errorInfo errorCode
9bc33297 168
28c8ab78 169 if {[gets $sock line] == -1} { fail "EOF/error on input" }
cc2d31de 170 regsub -all "\[^ -\176\240-\376\]" $line ? line
9bc33297 171 set org $line
17bfe24c
IJ
172
173 set ei $errorInfo
174 set ec $errorCode
a4a1f396 175 catch { unset calling_nick }
17bfe24c
IJ
176 set errorInfo $ei
177 set errorCode $ec
178
9bc33297
IJ
179 if {[regexp -nocase {^:([^ ]+) (.*)} $line dummy prefix remain]} {
180 set line $remain
a4a1f396
IJ
181 if {[regexp {^([^!]+)!} $prefix dummy maybenick]} {
182 set calling_nick $maybenick
183 if {"[irctolower $maybenick]" == "[irctolower $nick]"} return
184 }
9bc33297
IJ
185 } else {
186 set prefix {}
187 }
cc2d31de 188 if {![string length $line]} { return }
9bc33297
IJ
189 if {![regexp -nocase {^([0-9a-z]+) *(.*)} $line dummy command line]} {
190 log "bad command: $org"
191 return
192 }
cc2d31de 193 set command [string toupper $command]
9bc33297 194 set params {}
cc2d31de 195 while {[regexp {^([^ :]+) *(.*)} $line dummy thisword line]} {
9bc33297
IJ
196 lappend params $thisword
197 }
198 if {[regexp {^:(.*)} $line dummy thisword]} {
199 lappend params $thisword
200 } elseif {[string length $line]} {
201 log "junk at end: $org"
202 return
203 }
cc2d31de
IJ
204 if {"$command" == "PRIVMSG" &&
205 [regexp {^[&#+!]} [lindex $params 0]] &&
cf6ea4de 206 ![regexp {^![a-z][-a-z]*[a-z]( .*)?$} [lindex $params 1]]} {
cc2d31de 207 # on-channel message, ignore
ebbae0a9
IJ
208 set chan [lindex $params 0]
209 upvar #0 chan_lastactivity([irctolower $chan]) la
210 set la [clock seconds]
211 catch { recordlastseen_p $prefix "talking on $chan" 1 }
cc2d31de
IJ
212 return
213 }
83dd1224 214 log "[clock seconds] <- $org"
9bc33297 215 set procname msg_$command
cc2d31de 216 if {[catch { info body $procname }]} { return }
9bc33297
IJ
217 if {[catch {
218 eval [list $procname $prefix $command] $params
219 } emsg]} {
220 logerror "error: $emsg ($prefix $command $params)"
cc2d31de 221 saveeic
9bc33297
IJ
222 }
223}
224
7ce72032 225proc sendprivmsg {dest l} {
20087363
IJ
226 foreach v [split $l "\n"] {
227 sendout [expr {[ischan $dest] ? "PRIVMSG" : "NOTICE"}] $dest $v
228 }
83dd1224 229}
7818b6af
IJ
230proc sendaction_priority {priority dest what} {
231 sendout_priority $priority PRIVMSG $dest "\001ACTION $what\001"
232}
7ce72032
IJ
233proc msendprivmsg {dest ll} { foreach l $ll { sendprivmsg $dest $l } }
234proc msendprivmsg_delayed {delay dest ll} { after $delay [list msendprivmsg $dest $ll] }
83dd1224 235
cc2d31de
IJ
236proc prefix_none {} {
237 upvar 1 p p
9bc33297 238 if {[string length $p]} { error "prefix specified" }
cc2d31de 239}
9bc33297 240
cc2d31de 241proc msg_PING {p c s1} {
28c8ab78 242 global musthaveping_after
cc2d31de
IJ
243 prefix_none
244 sendout PONG $s1
534e26a9 245 if {[info exists musthaveping_after]} connected
9bc33297
IJ
246}
247
cc2d31de
IJ
248proc check_nick {n} {
249 if {[regexp -nocase {[^][\\`_^{|}a-z0-9-]} $n]} { error "bad char in nick" }
250 if {[regexp {^[-0-9]} $n]} { error "bad nick start" }
251}
252
422f52e4
IJ
253proc ischan {dest} {
254 return [regexp {^[&#+!]} $dest]
255}
256
257proc irctolower {v} {
258 foreach {from to} [list "\\\[" "{" \
259 "\\\]" "}" \
260 "\\\\" "|" \
261 "~" "^"] {
262 regsub -all $from $v $to v
263 }
264 return [string tolower $v]
265}
266
cc2d31de
IJ
267proc prefix_nick {} {
268 global nick
269 upvar 1 p p
270 upvar 1 n n
271 if {![regexp {^([^!]+)!} $p dummy n]} { error "not from nick" }
272 check_nick $n
a056c4bd
IJ
273 if {"[irctolower $n]" == "[irctolower $nick]"} {
274 error "from myself" {} {}
275 }
422f52e4
IJ
276}
277
7ce72032 278proc showintervalsecs {howlong} {
d83fb8db
IJ
279 return [showintervalsecs/[opt timeformat] $howlong]
280}
281
282proc showintervalsecs/ks {howlong} {
7ce72032
IJ
283 if {$howlong < 1000} {
284 return "${howlong}s"
83dd1224
IJ
285 } else {
286 if {$howlong < 1000000} {
287 set pfx k
288 set scale 1000
289 } else {
290 set pfx M
291 set scale 1000000
292 }
293 set value [expr "$howlong.0 / $scale"]
294 foreach {min format} {100 %.0f 10 %.1f 1 %.2f} {
295 if {$value < $min} continue
7ce72032 296 return [format "$format${pfx}s" $value]
83dd1224
IJ
297 }
298 }
299}
300
d83fb8db
IJ
301proc format_qty {qty unit} {
302 set o $qty
303 append o " "
304 append o $unit
305 if {$qty != 1} { append o s }
306 return $o
307}
308
309proc showintervalsecs/hms {qty} {
310 set ul {second 60 minute 60 hour 24 day 7 week}
311 set remainv 0
312 while {[llength $ul] > 1 && $qty >= [set uv [lindex $ul 1]]} {
313 set remainu [lindex $ul 0]
314 set remainv [expr {$qty % $uv}]
315 set qty [expr {($qty-$remainv)/$uv}]
316 set ul [lreplace $ul 0 1]
317 }
318 set o [format_qty $qty [lindex $ul 0]]
319 if {$remainv} {
320 append o " "
321 append o [format_qty $remainv $remainu]
322 }
323 return $o
324}
325
7ce72032
IJ
326proc showinterval {howlong} {
327 if {$howlong <= 0} {
328 return {just now}
329 } else {
330 return "[showintervalsecs $howlong] ago"
331 }
332}
333
83dd1224
IJ
334proc showtime {when} {
335 return [showinterval [expr {[clock seconds] - $when}]]
336}
337
338proc def_msgproc {name argl body} {
339 proc msg_$name "varbase $argl" "\
340 upvar #0 msg/\$varbase/dest d\n\
341 upvar #0 msg/\$varbase/str s\n\
342 upvar #0 msg/\$varbase/accum a\n\
343$body"
344}
345
346def_msgproc begin {dest str} {
347 set d $dest
348 set s $str
349 set a {}
350}
351
352def_msgproc append {str} {
353 set ns "$s$str"
354 if {[string length $s] && [string length $ns] > 65} {
355 msg__sendout $varbase
356 set s " [string trimleft $str]"
357 } else {
358 set s $ns
359 }
360}
361
362def_msgproc finish {} {
363 msg__sendout $varbase
364 unset s
365 unset d
366 return $a
367}
368
369def_msgproc _sendout {} {
370 lappend a [string trimright $s]
371 set s {}
372}
373
374proc looking_whenwhere {when where} {
375 set str [showtime [expr {$when-1}]]
376 if {[string length $where]} { append str " on $where" }
377 return $str
378}
379
380proc recordlastseen_n {n how here} {
381 global lastseen lookedfor
422f52e4 382 set lastseen([irctolower $n]) [list $n [clock seconds] $how]
83dd1224
IJ
383 if {!$here} return
384 upvar #0 lookedfor([irctolower $n]) lf
385 if {[info exists lf]} {
386 switch -exact [llength $lf] {
387 0 {
388 set ml {}
389 }
390 1 {
391 manyset [lindex $lf 0] when who where
392 set ml [list \
393 "FYI, $who was looking for you [looking_whenwhere $when $where]."]
394 }
395 default {
396 msg_begin tosend $n "FYI, people have been looking for you:"
397 set i 0
398 set fin ""
399 foreach e $lf {
400 incr i
401 if {$i == 1} {
402 msg_append tosend " "
403 } elseif {$i == [llength $lf]} {
404 msg_append tosend " and "
405 set fin .
406 } else {
407 msg_append tosend ", "
408 }
409 manyset $e when who where
410 msg_append tosend \
411 "$who ([looking_whenwhere $when $where])$fin"
412 }
413 set ml [msg_finish tosend]
414 }
415 }
416 unset lf
417 msendprivmsg_delayed 1000 $n $ml
418 }
422f52e4 419}
281b5f05
IJ
420
421proc note_topic {showoff whoby topic} {
35e19219 422 set msg "FYI, $whoby has changed the topic on $showoff"
281b5f05
IJ
423 if {[string length $topic] < 160} {
424 append msg " to $topic"
425 } else {
426 append msg " but it is too long to reproduce here !"
427 }
428 set showoff [irctolower $showoff]
429 set tell [chandb_get $showoff topictell]
430 if {[lsearch -exact $tell *] >= 0} {
431 set tryspies [chandb_list]
432 } else {
433 set tryspies $tell
434 }
281b5f05
IJ
435 foreach spy $tryspies {
436 set see [chandb_get $spy topicsee]
281b5f05
IJ
437 if {[lsearch -exact $see $showoff] >= 0 || \
438 ([lsearch -exact $see *] >= 0 && \
439 [lsearch -exact $tell $spy] >= 0)} {
440 sendprivmsg $spy $msg
441 }
442 }
443}
444
83dd1224 445proc recordlastseen_p {p how here} {
422f52e4 446 prefix_nick
83dd1224 447 recordlastseen_n $n $how $here
422f52e4
IJ
448}
449
450proc chanmode_arg {} {
451 upvar 2 args cm_args
452 set rv [lindex $cm_args 0]
453 set cm_args [lreplace cm_args 0 0]
454 return $rv
455}
456
83dd1224 457proc chanmode_o1 {m g p chan} {
20087363 458 global nick chan_initialop
83dd1224
IJ
459 prefix_nick
460 set who [chanmode_arg]
461 recordlastseen_n $n "being nice to $who" 1
462 if {"[irctolower $who]" == "[irctolower $nick]"} {
534e26a9
IJ
463 set nlower [irctolower $n]
464 upvar #0 nick_unique($nlower) u
20087363
IJ
465 if {[chandb_exists $chan]} {
466 sendprivmsg $n Thanks.
467 } elseif {![info exists u]} {
468 sendprivmsg $n {Op me while not on the channel, why don't you ?}
469 } else {
470 set chan_initialop([irctolower $chan]) $u
471 sendprivmsg $n \
472 "Thanks. You can use `channel manager ...' to register this channel."
473 if {![nickdb_exists $n] || ![string length [nickdb_get $n username]]} {
474 sendprivmsg $n \
475 "(But to do that you must register your nick securely first.)"
476 }
477 }
83dd1224
IJ
478 }
479}
480
422f52e4
IJ
481proc chanmode_o0 {m g p chan} {
482 global nick chandeop
483 prefix_nick
484 set who [chanmode_arg]
83dd1224 485 recordlastseen_p $p "being mean to $who" 1
422f52e4
IJ
486 if {"[irctolower $who]" == "[irctolower $nick]"} {
487 set chandeop($chan) [list [clock seconds] $p]
488 }
cc2d31de 489}
9bc33297 490
422f52e4
IJ
491proc msg_MODE {p c dest modelist args} {
492 if {![ischan $dest]} return
493 if {[regexp {^\-(.+)$} $modelist dummy modelist]} {
494 set give 0
495 } elseif {[regexp {^\+(.+)$} $modelist dummy modelist]} {
496 set give 1
497 } else {
498 error "invalid modelist"
499 }
500 foreach m [split $modelist] {
501 set procname chanmode_$m$give
502 if {[catch { info body $procname }]} {
83dd1224 503 recordlastseen_p $p "fiddling with $dest" 1
422f52e4
IJ
504 } else {
505 $procname $m $give $p $dest
506 }
507 }
508}
509
534e26a9
IJ
510proc leaving {lchan} {
511 foreach luser [array names nick_onchans] {
512 upvar #0 nick_onchans($luser) oc
513 set oc [grep tc {"$tc" != "$lchan"} $oc]
514 }
515 upvar #0 chan_nicks($lchan) nlist
516 unset nlist
ebbae0a9
IJ
517 upvar #0 chan_lastactivity($lchan) la
518 catch { unset la }
534e26a9
IJ
519}
520
cf6ea4de
IJ
521proc doleave {lchan} {
522 sendout PART $lchan
523 leaving $lchan
524}
525
534e26a9
IJ
526proc dojoin {lchan} {
527 global chan_nicks
528 sendout JOIN $lchan
529 set chan_nicks($lchan) {}
530}
531
532proc check_justme {lchan} {
533 global nick
534 upvar #0 chan_nicks($lchan) nlist
535 if {[llength $nlist] != 1} return
e2af9bcb 536 if {"[lindex $nlist 0]" != "[irctolower $nick]"} return
534e26a9
IJ
537 if {[chandb_exists $lchan]} {
538 set mode [chandb_get $lchan mode]
539 if {"$mode" != "*"} {
540 sendout MODE $lchan $mode
541 }
281b5f05
IJ
542 set topic [chandb_get $lchan topicset]
543 if {[string length $topic]} {
544 sendout TOPIC $lchan $topic
281b5f05 545 }
534e26a9 546 } else {
cf6ea4de 547 doleave $lchan
a4a1f396
IJ
548 }
549}
550
a056c4bd 551proc process_kickpart {chan user} {
a4a1f396 552 global nick
a056c4bd 553 check_nick $user
534e26a9
IJ
554 set luser [irctolower $user]
555 set lchan [irctolower $chan]
a056c4bd 556 if {![ischan $chan]} { error "not a channel" }
534e26a9
IJ
557 if {"$luser" == "[irctolower $nick]"} {
558 leaving $lchan
559 } else {
560 upvar #0 nick_onchans($luser) oc
561 upvar #0 chan_nicks($lchan) nlist
562 set oc [grep tc {"$tc" != "$lchan"} $oc]
563 set nlist [grep tn {"$tn" != "$luser"} $nlist]
564 nick_case $user
565 if {![llength $oc]} {
566 nick_forget $luser
567 } else {
568 check_justme $lchan
569 }
a4a1f396 570 }
534e26a9 571}
a056c4bd 572
281b5f05
IJ
573proc msg_TOPIC {p c dest topic} {
574 prefix_nick
575 if {![ischan $dest]} return
576 recordlastseen_n $n "changing the topic on $dest" 1
577 note_topic [irctolower $dest] $n $topic
578}
579
a056c4bd
IJ
580proc msg_KICK {p c chans users comment} {
581 set chans [split $chans ,]
582 set users [split $users ,]
583 if {[llength $chans] > 1} {
584 foreach chan $chans user $users { process_kickpart $chan $user }
585 } else {
586 foreach user $users { process_kickpart [lindex $chans 0] $user }
587 }
588}
589
590proc msg_KILL {p c user why} {
591 nick_forget $user
592}
593
20087363
IJ
594set nick_counter 0
595set nick_arys {onchans username unique}
534e26a9
IJ
596# nick_onchans($luser) -> [list ... $lchan ...]
597# nick_username($luser) -> <securely known local username>
598# nick_unique($luser) -> <counter>
599# nick_case($luser) -> $user (valid even if no longer visible)
ebbae0a9 600# nick_markid($luser) -> <after id for marktime>
534e26a9
IJ
601
602# chan_nicks($lchan) -> [list ... $luser ...]
ebbae0a9 603# chan_lastactivity($lchan) -> [clock seconds]
a056c4bd 604
534e26a9
IJ
605proc lnick_forget {luser} {
606 global nick_arys chan_nicks
ebbae0a9 607 lnick_marktime_cancel $luser
a056c4bd 608 foreach ary $nick_arys {
534e26a9 609 upvar #0 nick_${ary}($luser) av
a056c4bd
IJ
610 catch { unset av }
611 }
534e26a9
IJ
612 foreach lch [array names chan_nicks] {
613 upvar #0 chan_nicks($lch) nlist
614 set nlist [grep tn {"$tn" != "$luser"} $nlist]
615 check_justme $lch
616 }
617}
618
619proc nick_forget {user} {
620 global nick_arys chan_nicks
621 lnick_forget [irctolower $user]
622 nick_case $user
a4a1f396
IJ
623}
624
534e26a9 625proc nick_case {user} {
a4a1f396 626 global nick_case
534e26a9 627 set nick_case([irctolower $user]) $user
a056c4bd
IJ
628}
629
83dd1224 630proc msg_NICK {p c newnick} {
a4a1f396 631 global nick_arys nick_case
83dd1224
IJ
632 prefix_nick
633 recordlastseen_n $n "changing nicks to $newnick" 0
634 recordlastseen_n $newnick "changing nicks from $n" 1
6425c2d6 635 set luser [irctolower $n]
ebbae0a9 636 lnick_marktime_cancel $luser
6425c2d6 637 set lusernew [irctolower $newnick]
a056c4bd 638 foreach ary $nick_arys {
6425c2d6
IJ
639 upvar #0 nick_${ary}($luser) old
640 upvar #0 nick_${ary}($lusernew) new
a056c4bd
IJ
641 if {[info exists new]} { error "nick collision ?! $ary $n $newnick" }
642 if {[info exists old]} { set new $old; unset old }
643 }
6425c2d6 644 upvar #0 nick_onchans($lusernew) oc
534e26a9
IJ
645 foreach ch $oc {
646 upvar #0 chan_nicks($ch) nlist
647 set nlist [grep tn {"$tn" != "$luser"} $nlist]
648 lappend nlist $lusernew
649 }
ebbae0a9 650 lnick_marktime_start $lusernew "Hi." 500
a4a1f396 651 nick_case $newnick
83dd1224
IJ
652}
653
20087363
IJ
654proc nick_ishere {n} {
655 global nick_counter
534e26a9 656 upvar #0 nick_unique([irctolower $n]) u
20087363
IJ
657 if {![info exists u]} { set u [incr nick_counter].$n.[clock seconds] }
658 nick_case $n
659}
660
a056c4bd
IJ
661proc msg_JOIN {p c chan} {
662 prefix_nick
663 recordlastseen_n $n "joining $chan" 1
cf6ea4de
IJ
664 set nl [irctolower $n]
665 set lchan [irctolower $chan]
666 upvar #0 nick_onchans($nl) oc
667 upvar #0 chan_nicks($lchan) nlist
ebbae0a9
IJ
668 if {![info exists oc]} {
669 global marktime_join_startdelay
670 lnick_marktime_start $nl "Welcome." $marktime_join_startdelay
671 }
cf6ea4de
IJ
672 lappend oc $lchan
673 lappend nlist $nl
20087363 674 nick_ishere $n
a056c4bd
IJ
675}
676proc msg_PART {p c chan} {
677 prefix_nick
678 recordlastseen_n $n "leaving $chan" 1
679 process_kickpart $chan $n
680}
681proc msg_QUIT {p c why} {
682 prefix_nick
683 recordlastseen_n $n "leaving ($why)" 0
684 nick_forget $n
685}
422f52e4 686
cc2d31de
IJ
687proc msg_PRIVMSG {p c dest text} {
688 prefix_nick
422f52e4 689 if {[ischan $dest]} {
83dd1224 690 recordlastseen_n $n "invoking me in $dest" 1
422f52e4 691 set output $dest
cc2d31de 692 } else {
83dd1224 693 recordlastseen_n $n "talking to me" 1
422f52e4
IJ
694 set output $n
695 }
a4a1f396 696 nick_case $n
422f52e4
IJ
697
698 if {[catch {
699 regsub {^! *} $text {} text
700 set ucmd [ta_word]
83dd1224 701 set procname ucmd/[string tolower $ucmd]
422f52e4
IJ
702 if {[catch { info body $procname }]} {
703 error "unknown command; try help for help"
704 }
83dd1224 705 $procname $p $dest
422f52e4 706 } rv]} {
7ce72032 707 sendprivmsg $n "error: $rv"
422f52e4 708 } else {
7ce72032 709 manyset $rv priv_msgs pub_msgs priv_acts pub_acts
7a70431a 710 foreach {td val} [list $n $priv_acts $output $pub_acts] {
7ce72032 711 foreach l [split $val "\n"] {
7818b6af 712 sendaction_priority 0 $td $l
7ce72032
IJ
713 }
714 }
7a70431a 715 foreach {td val} [list $n $priv_msgs $output $pub_msgs] {
422f52e4 716 foreach l [split $val "\n"] {
7a70431a 717 sendprivmsg $td $l
422f52e4
IJ
718 }
719 }
720 }
721}
722
a056c4bd 723proc msg_INVITE {p c n chan} {
534e26a9 724 after 1000 [list dojoin [irctolower $chan]]
a056c4bd
IJ
725}
726
727proc grep {var predicate list} {
728 set o {}
729 upvar 1 $var v
730 foreach v $list {
731 if {[uplevel 1 [list expr $predicate]]} { lappend o $v }
732 }
733 return $o
734}
735
736proc msg_353 {p c dest type chan nicklist} {
737 global names_chans nick_onchans
534e26a9
IJ
738 set lchan [irctolower $chan]
739 upvar #0 chan_nicks($lchan) nlist
740 lappend names_chans $lchan
741 if {![info exists nlist]} {
742 # We don't think we're on this channel, so ignore it !
743 # Unfortunately, because we don't get a reply to PART,
744 # we have to remember ourselves whether we're on a channel,
745 # and ignore stuff if we're not, to avoid races. Feh.
746 return
747 }
748 set nlist_new {}
749 foreach user [split $nicklist { }] {
750 regsub {^[@+]} $user {} user
751 if {![string length $user]} continue
752 check_nick $user
753 set luser [irctolower $user]
754 upvar #0 nick_onchans($luser) oc
755 lappend oc $lchan
756 lappend nlist_new $luser
757 nick_ishere $user
a056c4bd 758 }
534e26a9 759 set nlist $nlist_new
a056c4bd
IJ
760}
761
762proc msg_366 {p c args} {
763 global names_chans nick_onchans
534e26a9
IJ
764 set lchan [irctolower $c]
765 foreach luser [array names nick_onchans] {
766 upvar #0 nick_onchans($luser) oc
767 if {[llength names_chans] > 1} {
a056c4bd 768 set oc [grep tc {[lsearch -exact $tc $names_chans] >= 0} $oc]
a056c4bd 769 }
534e26a9 770 if {![llength $oc]} { lnick_forget $n }
a056c4bd
IJ
771 }
772 unset names_chans
773}
774
11d9bff9
IJ
775proc ta_anymore {} {
776 upvar 1 text text
777 return [expr {!![string length $text]}]
778}
779
422f52e4
IJ
780proc ta_nomore {} {
781 upvar 1 text text
782 if {[string length $text]} { error "too many parameters" }
783}
784
785proc ta_word {} {
786 upvar 1 text text
787 if {![regexp {^([^ ]+) *(.*)} $text dummy firstword text]} {
788 error "too few parameters"
789 }
790 return $firstword
791}
792
793proc ta_nick {} {
794 upvar 1 text text
795 set v [ta_word]
796 check_nick $v
797 return $v
798}
799
83dd1224
IJ
800proc def_ucmd {cmdname body} {
801 proc ucmd/$cmdname {p dest} " upvar 1 text text\n$body"
802}
803
7ce72032
IJ
804proc ucmdr {priv pub args} {
805 return -code return [concat [list $priv $pub] $args]
422f52e4 806}
e1ba63be 807
e6cc22dc 808proc loadhelp {} {
5e5be903 809 global help_topics errorInfo
e6cc22dc
IJ
810
811 catch { unset help_topics }
812 set f [open helpinfos r]
d83fb8db
IJ
813 try_except_finally {
814 set lno 0
815 while {[gets $f l] >= 0} {
816 incr lno
817 if {[regexp {^#.*} $l]} {
818 } elseif {[regexp {^ *$} $l]} {
819 if {[info exists topic]} {
820 set help_topics($topic) [join $lines "\n"]
821 unset topic
822 unset lines
823 }
5e5be903
IJ
824 } elseif {[regexp {^\:\:} $l]} {
825 } elseif {[regexp {^\:([-+._0-9a-z]*)$} $l dummy newtopic]} {
d83fb8db
IJ
826 if {[info exists topic]} {
827 error "help $newtopic while in $topic"
828 }
829 set topic $newtopic
830 set lines {}
5e5be903 831 } elseif {[regexp {^[^:#]} $l]} {
d83fb8db 832 set topic
5e5be903
IJ
833 regsub -all {([^\\])\!\$?} _$l {\1} l
834 regsub -all {\\(.)} $l {\1} l
835 regsub {^_} $l {} l
d83fb8db
IJ
836 lappend lines [string trimright $l]
837 } else {
838 error "eh ? $lno: $l"
e6cc22dc 839 }
e6cc22dc 840 }
d83fb8db 841 if {[info exists topic]} { error "unfinished topic $topic" }
5e5be903
IJ
842 } {
843 set errorInfo "in helpinfos line $lno\n$errorInfo"
844 } {
d83fb8db 845 close $f
e6cc22dc 846 }
422f52e4
IJ
847}
848
e6cc22dc 849def_ucmd help {
cf6ea4de
IJ
850 upvar 1 n n
851
852 set topic [irctolower [string trim $text]]
853 if {[string length $topic]} {
854 set ontopic " on `$topic'"
855 } else {
856 set ontopic ""
857 }
7818b6af
IJ
858 if {[set lag [out_lagged]]} {
859 if {[ischan $dest]} { set replyto $dest } else { set replyto $n }
860 if {$lag > 1} {
861 sendaction_priority 1 $replyto \
cf6ea4de 862 "is very lagged. Please ask for help$ontopic again later."
7818b6af
IJ
863 ucmdr {} {}
864 } else {
865 sendaction_priority 1 $replyto \
cf6ea4de 866 "is lagged. Your help$ontopic will arrive shortly ..."
7818b6af
IJ
867 }
868 }
869
cf6ea4de
IJ
870 upvar #0 help_topics($topic) info
871 if {![info exists info]} { ucmdr "No help on $topic, sorry." {} }
e6cc22dc
IJ
872 ucmdr $info {}
873}
e1ba63be 874
e6cc22dc
IJ
875def_ucmd ? {
876 global help_topics
877 ucmdr $help_topics() {}
878}
e1ba63be 879
4fd2739c 880proc check_username {target} {
7ce72032
IJ
881 if {
882 [string length $target] > 8 ||
883 [regexp {[^-0-9a-z]} $target] ||
884 ![regexp {^[a-z]} $target]
885 } { error "invalid username" }
4fd2739c
IJ
886}
887
20087363 888proc somedb__head {} {
7a70431a 889 uplevel 1 {
20087363
IJ
890 set idl [irctolower $id]
891 upvar #0 ${nickchan}db($idl) ndbe
892 binary scan $idl H* idh
893 set idfn $fprefix$idh
894 if {![info exists iddbe] && [file exists $idfn]} {
895 set f [open $idfn r]
7a70431a
IJ
896 try_except_finally { set newval [read $f] } {} { close $f }
897 if {[llength $newval] % 2} { error "invalid length" }
20087363 898 set iddbe $newval
7a70431a
IJ
899 }
900 }
901}
902
20087363
IJ
903proc def_somedb {name arglist body} {
904 foreach {nickchan fprefix} {nick users/n chan chans/c} {
905 proc ${nickchan}db_$name $arglist \
534e26a9
IJ
906 "set nickchan $nickchan; set fprefix $fprefix; $body"
907 }
908}
909
910def_somedb list {} {
911 set list {}
912 foreach path [glob -nocomplain -path $fprefix *] {
913 binary scan $path "A[string length $fprefix]A*" afprefix thinghex
914 if {"$afprefix" != "$fprefix"} { error "wrong prefix $path $afprefix" }
915 lappend list [binary format H* $thinghex]
20087363 916 }
534e26a9
IJ
917 return $list
918}
919
920proc def_somedb_id {name arglist body} {
921 def_somedb $name [concat id $arglist] "somedb__head; $body"
7a70431a
IJ
922}
923
534e26a9 924def_somedb_id exists {} {
20087363 925 return [info exists iddbe]
7a70431a
IJ
926}
927
534e26a9 928def_somedb_id delete {} {
20087363
IJ
929 catch { unset iddbe }
930 file delete $idfn
7a70431a
IJ
931}
932
ebbae0a9 933set default_settings_nick {timeformat ks marktime off}
281b5f05
IJ
934set default_settings_chan {
935 autojoin 1
936 mode *
937 userinvite pub
938 topicset {}
939 topicsee {}
940 topictell {}
941}
7a70431a 942
534e26a9 943def_somedb_id set {args} {
20087363
IJ
944 upvar #0 default_settings_$nickchan def
945 if {![info exists iddbe]} { set iddbe $def }
946 foreach {key value} [concat $iddbe $args] { set a($key) $value }
7a70431a
IJ
947 set newval {}
948 foreach {key value} [array get a] { lappend newval $key $value }
20087363 949 set f [open $idfn.new w]
7a70431a
IJ
950 try_except_finally {
951 puts $f $newval
952 close $f
20087363 953 file rename -force $idfn.new $idfn
7a70431a 954 } {
7a70431a 955 } {
d83fb8db 956 catch { close $f }
7a70431a 957 }
20087363 958 set iddbe $newval
7a70431a
IJ
959}
960
534e26a9 961def_somedb_id get {key} {
20087363
IJ
962 upvar #0 default_settings_$nickchan def
963 if {[info exists iddbe]} {
534e26a9 964 set l [concat $iddbe $def]
7a70431a 965 } else {
20087363 966 set l $def
7a70431a
IJ
967 }
968 foreach {tkey value} $l {
969 if {"$tkey" == "$key"} { return $value }
970 }
971 error "unset setting $key"
972}
973
20087363
IJ
974proc opt {key} {
975 global calling_nick
976 if {[info exists calling_nick]} { set n $calling_nick } { set n {} }
977 return [nickdb_get $n $key]
978}
979
7a70431a
IJ
980proc check_notonchan {} {
981 upvar 1 dest dest
982 if {[ischan $dest]} { error "that command must be sent privately" }
983}
984
985proc nick_securitycheck {strict} {
986 upvar 1 n n
987 if {![nickdb_exists $n]} { error "you are unknown to me, use `register'." }
20087363 988 set wantu [nickdb_get $n username]
7a70431a
IJ
989 if {![string length $wantu]} {
990 if {$strict} {
991 error "that feature is only available to secure users, sorry."
992 } else {
993 return
994 }
995 }
534e26a9
IJ
996 set luser [irctolower $n]
997 upvar #0 nick_username($luser) nu
7a70431a
IJ
998 if {![info exists nu]} {
999 error "nick $n is secure, you must identify yourself first."
1000 }
1001 if {"$wantu" != "$nu"} {
1002 error "you are the wrong user - the nick $n belongs to $wantu, not $nu"
1003 }
1004}
1005
20087363
IJ
1006proc channel_securitycheck {channel n} {
1007 # You must also call `nick_securitycheck 1'
c362e172
IJ
1008 set mgrs [chandb_get $channel managers]
1009 if {[lsearch -exact [irctolower $mgrs] [irctolower $n]] < 0} {
20087363
IJ
1010 error "you are not a manager of $channel"
1011 }
1012}
1013
1014proc def_chancmd {name body} {
1015 proc channel/$name {} \
1016 " upvar 1 target chan; upvar 1 n n; upvar 1 text text; $body"
1017}
1018
281b5f05
IJ
1019proc ta_listop {findnow procvalue} {
1020 # findnow and procvalue are code fragments which will be executed
1021 # in the caller's level. findnow should set ta_listop_ev to
1022 # the current list, and procvalue should treat ta_listop_ev as
1023 # a proposed value in the list and check and possibly modify
1024 # (canonicalise?) it. After ta_listop, ta_listop_ev will
1025 # be the new value of the list.
1026 upvar 1 ta_listop_ev exchg
1027 upvar 1 text text
20087363
IJ
1028 set opcode [ta_word]
1029 switch -exact _$opcode {
281b5f05 1030 _= { }
20087363 1031 _+ - _- {
281b5f05
IJ
1032 uplevel 1 $findnow
1033 foreach item $exchg { set array($item) 1 }
20087363
IJ
1034 }
1035 default {
281b5f05 1036 error "list change opcode must be one of + - ="
20087363
IJ
1037 }
1038 }
281b5f05
IJ
1039 foreach exchg [split $text " "] {
1040 if {![string length $exchg]} continue
1041 uplevel 1 $procvalue
20087363 1042 if {"$opcode" != "-"} {
281b5f05 1043 set array($exchg) 1
20087363 1044 } else {
281b5f05 1045 catch { unset array($exchg) }
20087363
IJ
1046 }
1047 }
281b5f05
IJ
1048 set exchg [lsort [array names array]]
1049}
1050
1051def_chancmd manager {
1052 ta_listop {
1053 if {[chandb_exists $chan]} {
1054 set ta_listop_ev [chandb_get $chan managers]
1055 } else {
1056 set ta_listop_ev [list [irctolower $n]]
1057 }
1058 } {
1059 check_nick $ta_listop_ev
1060 set ta_listop_ev [irctolower $ta_listop_ev]
1061 }
1062 if {[llength $ta_listop_ev]} {
1063 chandb_set $chan managers $ta_listop_ev
1064 ucmdr "Managers of $chan: $ta_listop_ev" {}
20087363
IJ
1065 } else {
1066 chandb_delete $chan
1067 ucmdr {} {} "forgets about managing $chan." {}
1068 }
1069}
1070
1071def_chancmd autojoin {
1072 set yesno [ta_word]
1073 switch -exact [string tolower $yesno] {
1074 no { set nv 0 }
1075 yes { set nv 1 }
1076 default { error "channel autojoin must be `yes' or `no' }
1077 }
1078 chandb_set $chan autojoin $nv
a49f2997
IJ
1079 ucmdr [expr {$nv ? "I will join $chan when I'm restarted " : \
1080 "I won't join $chan when I'm restarted "}] {}
534e26a9
IJ
1081}
1082
5e5be903
IJ
1083def_chancmd userinvite {
1084 set nv [string tolower [ta_word]]
1085 switch -exact $nv {
1086 pub { set txt "!invite will work for $chan, but it won't work by /msg" }
1087 here { set txt "!invite and /msg invite will work, but only for users who are already on $chan." }
1088 all { set txt "Any user will be able to invite themselves or anyone else to $chan." }
1089 none { set txt "I will not invite anyone to $chan." }
1090 default {
1091 error "channel userinvite must be `pub', `here', `all' or `none'
1092 }
1093 }
1094 chandb_set $chan userinvite $nv
1095 ucmdr $txt {}
1096}
1097
281b5f05
IJ
1098def_chancmd topic {
1099 set what [ta_word]
1100 switch -exact $what {
1101 leave {
1102 ta_nomore
1103 chandb_set $chan topicset {}
1104 ucmdr "I won't ever change the topic of $chan." {}
1105 }
1106 set {
1107 set t [string trim $text]
1108 if {![string length $t]} {
1109 error "you must specific the topic to set"
1110 }
1111 chandb_set $chan topicset $t
a49f2997 1112 ucmdr "Whenever I'm alone on $chan, I'll set the topic to $t." {}
281b5f05
IJ
1113 }
1114 see - tell {
1115 ta_listop {
1116 set ta_listop_ev [chandb_get $chan topic$what]
1117 } {
1118 if {"$ta_listop_ev" != "*"} {
1119 if {![ischan $ta_listop_ev]} {
1120 error "bad channel \`$ta_listop_ev' in topic $what"
1121 }
1122 set ta_listop_ev [irctolower $ta_listop_ev]
1123 }
1124 }
1125 chandb_set $chan topic$what $ta_listop_ev
1126 ucmdr "Topic $what list for $chan: $ta_listop_ev" {}
1127 }
1128 default {
1129 error "unknown channel topic subcommand - see help channel"
1130 }
1131 }
1132}
1133
534e26a9
IJ
1134def_chancmd mode {
1135 set mode [ta_word]
1136 if {"$mode" != "*" && ![regexp {^(([-+][imnpst]+)+)$} $mode mode]} {
1137 error {channel mode must be * or match ([-+][imnpst]+)+}
1138 }
1139 chandb_set $chan mode $mode
1140 if {"$mode" == "*"} {
281b5f05 1141 ucmdr "I won't ever change the mode of $chan." {}
534e26a9 1142 } else {
281b5f05 1143 ucmdr "Whenever I'm alone on $chan, I'll set the mode to $mode." {}
534e26a9 1144 }
20087363
IJ
1145}
1146
1147def_chancmd show {
1148 if {[chandb_exists $chan]} {
1149 set l "Settings for $chan: autojoin "
1150 append l [lindex {no yes} [chandb_get $chan autojoin]]
b60b5a0f
IJ
1151 append l ", mode " [chandb_get $chan mode]
1152 append l ", userinvite " [chandb_get $chan userinvite] "."
20087363 1153 append l "\nManagers: "
8b6ee626 1154 append l [join [chandb_get $chan managers] " "]
281b5f05
IJ
1155 foreach {ts sep} {see "\n" tell " "} {
1156 set t [chandb_get $chan topic$ts]
1157 append l $sep
1158 if {[llength $t]} {
1159 append l "Topic $ts list: $t."
1160 } else {
1161 append l "Topic $ts list is empty."
1162 }
1163 }
8b6ee626
IJ
1164 append l "\n"
1165 set t [chandb_get $chan topicset]
1166 if {[string length $t]} {
1167 append l "Topic to set: $t"
1168 } else {
1169 append l "I will not change the topic."
1170 }
20087363
IJ
1171 ucmdr {} $l
1172 } else {
1173 ucmdr {} "The channel $chan is not managed."
1174 }
1175}
1176
cf6ea4de
IJ
1177proc channelmgr_monoop {} {
1178 upvar 1 dest dest
1179 upvar 1 text text
1180 upvar 1 n n
1181 upvar 1 p p
1182 upvar 1 target target
1183 global chan_nicks
1184
3c9af14f
IJ
1185 prefix_nick
1186
20087363
IJ
1187 if {[ischan $dest]} { set target $dest }
1188 if {[ta_anymore]} { set target [ta_word] }
1189 ta_nomore
cf6ea4de
IJ
1190 if {![info exists target]} {
1191 error "you must specify, or invoke me on, the relevant channel"
1192 }
1193 if {![info exists chan_nicks([irctolower $target])]} {
1194 error "I am not on $target."
1195 }
20087363 1196 if {![ischan $target]} { error "not a valid channel" }
3c9af14f 1197
20087363 1198 if {![chandb_exists $target]} { error "$target is not a managed channel." }
20087363
IJ
1199 nick_securitycheck 1
1200 channel_securitycheck $target $n
cf6ea4de
IJ
1201}
1202
1203def_ucmd op {
1204 channelmgr_monoop
20087363
IJ
1205 sendout MODE $target +o $n
1206}
1207
cf6ea4de
IJ
1208def_ucmd leave {
1209 channelmgr_monoop
1210 doleave $target
1211}
1212
5e5be903
IJ
1213def_ucmd invite {
1214 global chan_nicks
1215
1216 if {[ischan $dest]} {
1217 set target $dest
1218 set onchan 1
1219 } else {
1220 set target [ta_word]
1221 set onchan 0
1222 }
1223 set ltarget [irctolower $target]
1224 if {![ischan $target]} { error "$target is not a channel." }
1225 if {![info exists chan_nicks($ltarget)]} { error "I am not on $target." }
1226 set ui [chandb_get $ltarget userinvite]
1227 if {"$ui" == "pub" && !$onchan} {
1228 error "Invitations to $target must be made with !invite."
1229 }
1230 if {"$ui" != "all"} {
1231 prefix_nick
1232 if {[lsearch -exact $chan_nicks($ltarget) [irctolower $n]] < 0} {
1233 error "Invitations to $target may only be made by a user on the channel."
1234 }
1235 }
1236 if {"$ui" == "none"} {
1237 error "Sorry, I've not been authorised to invite people to $target."
1238 }
1239 if {![ta_anymore]} {
1240 error "You have to say who to invite."
1241 }
1242 set invitees {}
1243 while {[ta_anymore]} {
1244 set invitee [ta_word]
1245 check_nick $invitee
1246 lappend invitees $invitee
1247 }
1248 foreach invitee $invitees {
1249 sendout INVITE $invitee $ltarget
1250 }
1251 set who [lindex $invitees 0]
1252 switch -exact llength $invitees {
1253 0 { error "zero invitees" }
1254 1 { }
1255 2 { append who " and [lindex $invitees 1]" }
1256 * {
1257 set who [join [lreplace $invitees end end] ", "]
1258 append who " and [lindex $invitees [llength $invitees]]"
1259 }
1260 }
1261 ucmdr {} "invites $who to $target."
1262}
1263
20087363
IJ
1264def_ucmd channel {
1265 if {[ischan $dest]} { set target $dest }
1266 if {![ta_anymore]} {
1267 set subcmd show
1268 } else {
1269 set subcmd [ta_word]
1270 }
1271 if {[ischan $subcmd]} {
1272 set target $subcmd
1273 if {![ta_anymore]} {
1274 set subcmd show
1275 } else {
1276 set subcmd [ta_word]
1277 }
1278 }
1279 if {![info exists target]} { error "privately, you must specify a channel" }
1280 set procname channel/$subcmd
1281 if {"$subcmd" != "show"} {
1282 if {[catch { info body $procname }]} { error "unknown channel setting $subcmd" }
1283 prefix_nick
1284 nick_securitycheck 1
1285 if {[chandb_exists $target]} {
1286 channel_securitycheck $target $n
1287 } else {
1288 upvar #0 chan_initialop([irctolower $target]) io
534e26a9 1289 upvar #0 nick_unique([irctolower $n]) u
20087363
IJ
1290 if {![info exists io]} { error "$target is not a managed channel" }
1291 if {"$io" != "$u"} { error "you are not the interim manager of $target" }
1292 if {"$subcmd" != "manager"} { error "use `channel manager' first" }
1293 }
1294 }
1295 channel/$subcmd
1296}
1297
a4a1f396
IJ
1298def_ucmd who {
1299 if {[ta_anymore]} {
1300 set target [ta_word]; ta_nomore
1301 set myself 1
1302 } else {
1303 prefix_nick
1304 set target $n
1305 set myself [expr {"$target" != "$n"}]
1306 }
534e26a9
IJ
1307 set ltarget [irctolower $target]
1308 upvar #0 nick_case($ltarget) ctarget
a4a1f396 1309 set nshow $target
534e26a9
IJ
1310 if {[info exists ctarget]} {
1311 upvar #0 nick_onchans($ltarget) oc
1312 upvar #0 nick_username($ltarget) nu
1313 if {[info exists oc]} { set nshow $ctarget }
a4a1f396 1314 }
534e26a9 1315 if {![nickdb_exists $ltarget]} {
a4a1f396 1316 set ol "$nshow is not a registered nick."
20087363 1317 } elseif {[string length [set username [nickdb_get $target username]]]} {
a4a1f396
IJ
1318 set ol "The nick $nshow belongs to the user $username."
1319 } else {
1320 set ol "The nick $nshow is registered (but not to a username)."
1321 }
534e26a9 1322 if {![info exists ctarget] || ![info exists oc]} {
a4a1f396
IJ
1323 if {$myself} {
1324 append ol "\nI can't see $nshow on anywhere."
1325 } else {
1326 append ol "\nYou aren't on any channels with me."
1327 }
1328 } elseif {![info exists nu]} {
1329 append ol "\n$nshow has not identified themselves."
1330 } elseif {![info exists username]} {
1331 append ol "\n$nshow has identified themselves as the user $nu."
1332 } elseif {"$nu" != "$username"} {
1333 append ol "\nHowever, $nshow is being used by the user $nu."
1334 } else {
1335 append ol "\n$nshow has identified themselves to me."
1336 }
1337 ucmdr {} $ol
1338}
1339
7a70431a
IJ
1340def_ucmd register {
1341 prefix_nick
1342 check_notonchan
1343 set old [nickdb_exists $n]
1344 if {$old} { nick_securitycheck 0 }
534e26a9 1345 set luser [irctolower $n]
7a70431a
IJ
1346 switch -exact [string tolower [string trim $text]] {
1347 {} {
534e26a9 1348 upvar #0 nick_username($luser) nu
7a70431a
IJ
1349 if {![info exists nu]} {
1350 ucmdr {} \
a4a1f396 1351 "You must identify yourself before using `register'. See `help identify', or use `register insecure'."
7a70431a
IJ
1352 }
1353 nickdb_set $n username $nu
1354 ucmdr {} {} "makes a note of your username." {}
1355 }
1356 delete {
1357 nickdb_delete $n
1358 ucmdr {} {} "forgets your nickname." {}
1359 }
1360 insecure {
1361 nickdb_set $n username {}
1362 if {$old} {
1363 ucmdr {} "Security is now disabled for your nickname !"
1364 } else {
1365 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."
1366 }
1367 }
1368 }
11d9bff9
IJ
1369}
1370
1371proc timeformat_desc {tf} {
1372 switch -exact $tf {
86892128 1373 ks { return "Times will be displayed in seconds or kiloseconds." }
11d9bff9
IJ
1374 hms { return "Times will be displayed in hours, minutes, etc." }
1375 default { error "invalid timeformat: $v" }
1376 }
1377}
1378
1379proc def_setting {opt show_body set_body} {
1380 proc set_show/$opt {} "
1381 upvar 1 n n
1382 set opt $opt
1383 $show_body"
1384 if {![string length $set_body]} return
1385 proc set_set/$opt {} "
1386 upvar 1 n n
1387 upvar 1 text text
1388 set opt $opt
1389 $set_body"
1390}
1391
1392def_setting timeformat {
20087363 1393 set tf [nickdb_get $n timeformat]
11d9bff9
IJ
1394 return "$tf: [timeformat_desc $tf]"
1395} {
1396 set tf [string tolower [ta_word]]
1397 ta_nomore
1398 set desc [timeformat_desc $tf]
1399 nickdb_set $n timeformat $tf
1400 ucmdr {} $desc
1401}
1402
ebbae0a9
IJ
1403proc marktime_desc {mt} {
1404 if {"$mt" == "off"} {
1405 return "I will not send you periodic messages."
1406 } elseif {"$mt" == "once"} {
1407 return "I will send you one informational message when I see you."
1408 } else {
1409 return "I'll send you a message every [showintervalsecs $mt]."
1410 }
1411}
1412
1413def_setting marktime {
1414 set mt [nickdb_get $n marktime]
1415 set p $mt
a4e294d4 1416 if {[string match {[0-9]*} $mt]} { append p s }
ebbae0a9
IJ
1417 append p ": "
1418 append p [marktime_desc $mt]
1419 return $p
1420} {
1421 global marktime_min
1422 set mt [string tolower [ta_word]]
1423 ta_nomore
1424
1425 if {"$mt" == "off" || "$mt" == "once"} {
1426 } elseif {[regexp {^([0-9]+)([a-z]+)$} $mt dummy value unit]} {
1427 switch -exact $unit {
1428 s { set u 1 }
1429 ks { set u 1000 }
1430 m { set u 60 }
1431 h { set u 3600 }
1432 default { error "unknown unit of time $unit" }
1433 }
1434 if {$value > 86400*21/$u} { error "marktime interval too large" }
1435 set mt [expr {$value*$u}]
1436 if {$mt < $marktime_min} { error "marktime interval too small" }
1437 } else {
1438 error "invalid syntax for marktime"
1439 }
1440 nickdb_set $n marktime $mt
1441 lnick_marktime_start [irctolower $n] "So:" 500
1442 ucmdr {} [marktime_desc $mt]
1443}
1444
11d9bff9 1445def_setting security {
20087363 1446 set s [nickdb_get $n username]
11d9bff9
IJ
1447 if {[string length $s]} {
1448 return "Your nick, $n, is controlled by the user $s."
1449 } else {
1450 return "Your nick, $n, is not secure."
1451 }
1452} {}
1453
1454def_ucmd set {
1455 prefix_nick
1456 check_notonchan
1457 if {![nickdb_exists $n]} {
d83fb8db 1458 ucmdr {} "You are unknown to me and so have no settings. (Use `register'.)"
11d9bff9
IJ
1459 }
1460 if {![ta_anymore]} {
1461 set ol {}
1462 foreach proc [lsort [info procs]] {
1463 if {![regexp {^set_show/(.*)$} $proc dummy opt]} continue
1464 lappend ol [format "%-10s %s" $opt [set_show/$opt]]
1465 }
1466 ucmdr {} [join $ol "\n"]
1467 } else {
1468 set opt [ta_word]
1469 if {[catch { info body set_show/$opt }]} {
1470 error "no setting $opt"
1471 }
1472 if {![ta_anymore]} {
1473 ucmdr {} "$opt [set_show/$opt]"
1474 } else {
86892128 1475 nick_securitycheck 0
11d9bff9
IJ
1476 if {[catch { info body set_set/$opt }]} {
1477 error "setting $opt cannot be set with `set'"
1478 }
1479 set_set/$opt
1480 }
1481 }
1482}
7a70431a 1483
4fd2739c
IJ
1484def_ucmd identpass {
1485 set username [ta_word]
d83fb8db 1486 set passmd5 [md5sum "[ta_word]\n"]
4fd2739c
IJ
1487 ta_nomore
1488 prefix_nick
11d9bff9 1489 check_notonchan
534e26a9
IJ
1490 set luser [irctolower $n]
1491 upvar #0 nick_onchans($luser) onchans
4fd2739c 1492 if {![info exists onchans] || ![llength $onchans]} {
7a70431a 1493 ucmdr "You must be on a channel with me to identify yourself." {}
4fd2739c
IJ
1494 }
1495 check_username $username
1496 exec userv --timeout 3 $username << "$passmd5\n" > /dev/null \
1497 irc-identpass $n
534e26a9 1498 upvar #0 nick_username($luser) rec_username
4fd2739c 1499 set rec_username $username
7a70431a 1500 ucmdr "Pleased to see you, $username." {}
4fd2739c
IJ
1501}
1502
1503def_ucmd summon {
1504 set target [ta_word]
1505 ta_nomore
1506 check_username $target
7ce72032
IJ
1507 prefix_nick
1508
1509 upvar #0 lastsummon($target) ls
1510 set now [clock seconds]
1511 if {[info exists ls]} {
1512 set interval [expr {$now - $ls}]
1513 if {$interval < 30} {
1514 ucmdr {} \
1515 "Please be patient; $target was summoned only [showinterval $interval]."
1516 }
1517 }
1518 regsub {^[^!]*!} $p {} path
1519 if {[catch {
1520 exec userv --timeout 3 $target irc-summon $n $path \
1521 [expr {[ischan $dest] ? "$dest" : ""}] \
1522 < /dev/null
1523 } rv]} {
1524 regsub -all "\n" $rv { / } rv
1525 error $rv
1526 }
1527 if {[regexp {^problem (.*)} $rv dummy problem]} {
8a8d337d 1528 ucmdr {} "The user `$target' $problem."
7ce72032
IJ
1529 } elseif {[regexp {^ok ([^ ]+) ([0-9]+)$} $rv dummy tty idlesince]} {
1530 set idletime [expr {$now - $idlesince}]
1531 set ls $now
1532 ucmdr {} {} {} "invites $target ($tty[expr {
1533 $idletime > 10 ? ", idle for [showintervalsecs $idletime]" : ""
1534 }]) to [expr {
1535 [ischan $dest] ? "join us here" : "talk to you"
1536 }]."
1537 } else {
1538 error "unexpected response from userv service: $rv"
1539 }
1540}
1541
a69f7d2c
IJ
1542proc md5sum {value} { exec md5sum << $value }
1543
83dd1224 1544def_ucmd seen {
422f52e4 1545 global lastseen nick
83dd1224
IJ
1546 prefix_nick
1547 set ncase [ta_nick]
1548 set nlower [irctolower $ncase]
422f52e4 1549 ta_nomore
83dd1224
IJ
1550 set now [clock seconds]
1551 if {"$nlower" == "[irctolower $nick]"} {
422f52e4 1552 error "I am not self-aware."
83dd1224
IJ
1553 } elseif {![info exists lastseen($nlower)]} {
1554 set rstr "I've never seen $ncase."
422f52e4 1555 } else {
83dd1224
IJ
1556 manyset $lastseen($nlower) realnick time what
1557 set howlong [expr {$now - $time}]
1558 set string [showinterval $howlong]
1559 set rstr "I last saw $realnick $string, $what."
1560 }
1561 if {[ischan $dest]} {
1562 set where $dest
1563 } else {
1564 set where {}
1565 }
1566 upvar #0 lookedfor($nlower) lf
1567 if {[info exists lf]} { set oldvalue $lf } else { set oldvalue {} }
1568 set lf [list [list $now $n $where]]
1569 foreach v $oldvalue {
1570 if {"[irctolower [lindex $v 1]]" == "[irctolower $n]"} continue
1571 lappend lf $v
cc2d31de 1572 }
83dd1224 1573 ucmdr {} $rstr
cc2d31de
IJ
1574}
1575
ebbae0a9
IJ
1576proc lnick_marktime_cancel {luser} {
1577 upvar #0 nick_markid($luser) mi
1578 if {![info exists mi]} return
1579 catch { after cancel $mi }
1580 catch { unset mi }
1581}
1582
1583proc lnick_marktime_doafter {luser why ms} {
1584 lnick_marktime_cancel $luser
1585 upvar #0 nick_markid($luser) mi
1586 set mi [after $ms [list lnick_marktime_now $luser $why]]
1587}
1588
1589proc lnick_marktime_reset {luser} {
1590 set mt [nickdb_get $luser marktime]
1591 if {"$mt" == "off" || "$mt" == "once"} return
1592 lnick_marktime_doafter $luser "Time passes." [expr {$mt*1000}]
1593}
1594
1595proc lnick_marktime_start {luser why ms} {
1596 set mt [nickdb_get $luser marktime]
1597 if {"$mt" == "off"} {
1598 lnick_marktime_cancel $luser
1599 } else {
1600 lnick_marktime_doafter $luser $why $ms
1601 }
1602}
1603
1604proc lnick_marktime_now {luser why} {
1605 upvar #0 nick_onchans($luser) oc
93e9bcff
IJ
1606 global calling_nick
1607 set calling_nick $luser
ebbae0a9
IJ
1608 sendprivmsg $luser [lnick_pingstring $why $oc ""]
1609 lnick_marktime_reset $luser
1610}
1611
1612proc lnick_pingstring {why oc apstring} {
1613 global nick_onchans
1614 catch { exec uptime } uptime
1615 set nnicks [llength [array names nick_onchans]]
1616 if {[regexp \
1617 {^ *([0-9:apm]+) +up.*, +(\d+) users, +load average: +([0-9., ]+) *$} \
1618 $uptime dummy time users load]} {
93e9bcff 1619 regsub -all , $load {} load
ebbae0a9
IJ
1620 set uptime "$time $nnicks/$users $load"
1621 } else {
1622 append uptime ", $nnicks nicks"
1623 }
1624 if {[llength $oc]} {
1625 set best_la 0
1626 set activity quiet
1627 foreach ch $oc {
1628 upvar #0 chan_lastactivity($ch) la
1629 if {![info exists la]} continue
1630 if {$la <= $best_la} continue
1631 set activity "$ch [showintervalsecs [expr {[clock seconds]-$la}]]"
1632 set best_la $la
1633 }
1634 } else {
1635 set activity unseen
1636 }
1637 set str $why
1638 append str " " $uptime " " $activity
1639 if {[string length $apstring]} { append str " " $apstring }
1640 return $str
1641}
1642
1643def_ucmd ping {
1644 if {[ischan $dest]} {
1645 set oc [irctolower $dest]
1646 } else {
1647 global nick_onchans
1648 prefix_nick
1649 set ln [irctolower $n]
1650 if {[info exists nick_onchans($ln)]} {
1651 set oc $nick_onchans($ln)
1652 } else {
1653 set oc {}
1654 }
1655 if {[llength $oc]} { lnick_marktime_reset $ln }
1656 }
1657 ucmdr {} [lnick_pingstring "Pong!" $oc $text]
1658}
1659
28c8ab78
IJ
1660proc ensure_globalsecret {} {
1661 global globalsecret
1662
1663 if {[info exists globalsecret]} return
1664 set gsfile [open /dev/urandom r]
1665 fconfigure $gsfile -translation binary
1666 set globalsecret [read $gsfile 32]
1667 binary scan $globalsecret H* globalsecret
1668 close $gsfile
1669 unset gsfile
1670}
1671
1672proc ensure_outqueue {} {
1673 out__vars
1674 if {[info exists out_queue]} return
8bf6ec5b 1675 set out_creditms 0
28c8ab78
IJ
1676 set out_creditat [clock seconds]
1677 set out_queue {}
1678 set out_lag_reported 0
1679 set out_lag_reportwhen $out_creditat
1680}
1681
1682proc fail {msg} {
1683 logerror "failing: $msg"
1684 exit 1
1685}
1686
1687proc ensure_connecting {} {
a867f547 1688 global sock ownfullname host port nick socketargs
28c8ab78
IJ
1689 global musthaveping_ms musthaveping_after
1690
1691 if {[info exists sock]} return
a867f547 1692 set sock [eval socket $socketargs [list $host $port]]
cc2d31de 1693 fconfigure $sock -buffering line
cc2d31de
IJ
1694 fconfigure $sock -translation crlf
1695
b3d361ab 1696 sendout USER blight 0 * $ownfullname
cc2d31de
IJ
1697 sendout NICK $nick
1698 fileevent $sock readable onread
28c8ab78
IJ
1699
1700 set musthaveping_after [after $musthaveping_ms \
1701 {fail "no ping within timeout"}]
cc2d31de
IJ
1702}
1703
534e26a9
IJ
1704proc connected {} {
1705 global musthaveping_after
1706
1707 after cancel $musthaveping_after
1708 unset musthaveping_after
1709
1710 foreach chan [chandb_list] {
1711 if {[chandb_get $chan autojoin]} { dojoin $chan }
1712 }
1713}
1714
28c8ab78
IJ
1715ensure_globalsecret
1716ensure_outqueue
e6cc22dc 1717loadhelp
28c8ab78 1718ensure_connecting