~m4v/scratbot-plugins/spaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
# -*- Encoding: UTF-8 -*-
###
# Copyright (c) 2008-2009, Elián Hanisch
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
###

# imports
import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircdb as ircdb
import supybot.ircmsgs as ircmsgs
import supybot.callbacks as callbacks
import supybot.schedule as schedule

import re, getopt

import objects
from common import *
from databases import DatabaseError
from objects import FactNotFound, FactInvalid, FactLocked, AliasLoop

from network import freenode, freenodeSubstitution

# tables setup
tableConf = conf.supybot.plugins.Factos.sqlite.table
# base fact table
tableFact = objects.Table(objects.tblFactStruct, tableConf.fact(), tableIndex='name')
# base table for record edits
tableHist = objects.Table(objects.tblHistStruct, tableConf.history())
tableHistRedo = objects.Table(objects.tblHistStruct, tableConf.history() + '_redo')
# table for user hostmasks
tableUser = objects.databases.Table(objects.tblUserStruct, tableConf.users(), tableIndex='user_id')

class Fact(objects.Fact):
    """Class for handling facts."""
    dbTable = tableFact
    dbTableHist = tableHist
    prefix = conf.supybot.reply.whenAddressedBy.chars()[0]
    regexp = '[\w\-\.\#ñÑ]+' # regexp for a valid fact name

    def info(self):
        """
        Returns a string summarising information about the fact, used when somebody calls
        'fact --info'."""
        def getDate(attr):
            n = getattr(self, attr)
            if n is not None:
                s = date(n)
                if s == date(now()): # use hour then
                    return 'hoy a las %s' % hour(n)
                else:
                    return 'el ' + s
            else:
                return ''

        def getUser(attr):
            id = getattr(self, attr)
            if id is not None:
                return User(user_id=id, db=self.db)
            else:
                return None

        author = getUser('created_by')
        author.pull()
        dateCreated = getDate('created_at')
        if self.request_count > 1:
            sCount = 'se usó %s veces' % self.request_count
        elif self.request_count == 1:
            sCount = 'se usó una vez'
        else:
            sCount = 'no se usó'
        if self.isAlias():
            s = '%s es un alias a \'%s\' y fué creado por %s ' \
                    '%s, %s.' % (self.id(alias=False), self.data, author.getNick(),
                    dateCreated, sCount)
        else:
            s = 'El facto %s fué creado por %s %s, %s y tiene %s ' \
                    'carácteres.' % \
                    (self.id(), author.getNick(), dateCreated, sCount, len(self))
        editor = getUser('edited_by')
        if editor is not None:
            editor.pull()
            s += ' Editado por última vez %s por %s.' % \
            (getDate('edited_at'), editor.getNick())
        if self.isDisabled():
            if self.isLocked():
                s += ' Está bloqueado.'
            else:
                s += ' Está borrado.'
        else:
            if self.isLocked():
                s += ' Está protegido contra cambios.'
        return s


class User(objects.User):
    """Class for handling users."""
    dbTable = tableUser


def logInfo(irc, msg, s, fact=None):
    """Information logging."""
    vars = {'msg': msg.args[1]}
    if fact is not None:
        vars['data'] = fact.data
    s = doSubstitution(irc, msg, s, fact, vars=vars)
    log.info(s)

reRandWordList = re.compile(r'\$\([^|()]+(\|[^|()]+)+\)')
@freenodeSubstitution
def doSubstitution(irc, msg, s, fact=None, vars=None):
    """Returns <s> replacing any found keyword."""
    channel = formatChannel(msg.args[0])
    def getChannel():
        if channel:
            return channel
        else:
            return 'privado'
    def randInt():
        import random
        return str(random.randint(0, 100))
    def randNick():
        if channel:
            L = list(irc.state.channels[channel].users)
            if len(L) > 1:
                n = msg.nick
                while n == msg.nick:
                    n = utils.iter.choice(L)
                return n
            else:
                return msg.nick
        else:
            return 'alguien'
    def randWord(match):
        match = match.group()
        #log.debug('match: %s' %match)
        L = match[2:-1].split('|')
        return utils.iter.choice(L)
    if vars is None:
        vars = {}
    vars.update({
        'who': msg.nick,
        'nick': msg.nick,
        'hostmask': msg.prefix,
        'channel': getChannel,
        'botnick': irc.nick,
        'randnick': randNick,
        'randint': randInt,
        'to': irc.to or randNick,
        })
    if fact is not None:
        def edit_size():
            # for summarise how much was edited
            if hasattr(fact, 'old_fact'):
                return str(utils.str.distance(fact.data, fact.old_fact.data))
            else:
                return '0'
        fact_len = lambda : str(len(fact.data))
        fact_name = lambda : '%s%s' %(fact.prefix, fact.name)
        def alias():
            if fact.isAlias():
                return '%s%s' %(fact.prefix, fact.data)
            else:
                return fact_name()
        vars['fact'] = fact.id
        vars['fact_name'] = fact_name
        vars['alias'] = alias
        vars['fact_len'] = fact_len
        vars['edit_size'] = edit_size
    s = reRandWordList.sub(randWord, s)
    return utils.str.perlVariableSubstitute(vars, s)

def doArgSubstitution(s, args):
    """Substitutes numeric keywords (${1}, ${2}, ...) with args provided in <args>. Special keyword
    ${*} is substituted by <args>."""
    vars = {'*':args}
    n = 1
    for arg in args.split():
        vars[str(n)] = arg
        n += 1
    return utils.str.perlVariableSubstitute(vars, s)

reFactSub = re.compile('%%%s%%' %Fact.regexp)
def doFactSubstitution(s, db, channel=None):
    """Replaces %fact_name% keywords with fact_name's data, for indenting facts inside another."""
    for m in reFactSub.finditer(s):
        key = m.group()
        name = key.strip('%')
        name, localChannel = Fact.stripChannel(name)
        log.debug('calling fact substitution for %s, chan:%s' %(name, channel))
        sub = Fact(name=name, channel=localChannel, db=db)
        try:
            sub.pull(channel)
            sub.pullAlias(channel)
            log.debug('fact: %s, sub: %s' %(s, sub.data))
            s = s.replace(key, sub.data)
        except:
            pass
    return s


class RepeatQueue(dict):
    """
    Repeat protection, you can call the same fact twice as long as the timeout was reached, or
    if the message threshold in the channel was reached."""
    def __init__(self):
        config = conf.supybot.plugins.Factos.repeatProtection
        self.collisionTime = 4
        self.timeout = config.timeout
        self.threshold = config.msgthreshold
        self.msgcount = {}
        self.msgcollision = {}

        def ifRepeatProtection(channel):
            if isChannel(channel):
                return config.get(channel)()
            else:
                return False

        def ifCollision(channel):
            if isChannel(channel):
                return config.collision.get(channel)()
            else:
                return False

        self.ifCollision = ifCollision
        self.ifRepeatProtection = ifRepeatProtection

    @staticmethod
    def makeKey(fact, channel, options):
        options = frozenset(options.iteritems())
        return fact, channel, options

    def _clearOld(self, channel, now):
        """Purges enqueue of old msg."""
        timeout = self.timeout()
        threshold = self.threshold()
        for (key, when) in self.items():
            if now - when[0] > timeout:
                #log.debug('RepeatQueue: removing %r from the queue due to timeout.' %(key, ))
                del self[key]
            elif self._getcount(channel) - when[1] > threshold:
                #log.debug('RepeatQueue: removing %r from the queue due to msg threshold.' %(key, ))
                del self[key]

    def enqueue(self, key, now):
        channel = key[1]
        self[key] = (now, self._getcount(channel))
        #log.debug('RepeatQueue: adding %r to the queue: %s' % (key, self[key]))

    def inQueue(self, key, clear=True):
        channel = key[1]
        if not self.ifRepeatProtection(channel):
            return False
        _now = now()
        if clear:
            self._clearOld(channel, _now)
        if key in self:
            return True
        else:
            self.enqueue(key, _now)
            return False

    def collision(self, name, channel):
        """A collision is when the same fact is called twice or more times, because many users
        called the same fact for somebody at the same time."""
        if not self.ifCollision(channel):
            return False
        key = (name, channel)
        _now = now()
        self._clearOldCollision(_now)
        if key in self.msgcollision:
            return True
        else:
            self.msgcollision[name, channel] = _now
            return False

    def _clearOldCollision(self, _now):
        collision = self.collisionTime
        for (key, when) in self.msgcollision.items():
            if _now - when > collision:
                del self.msgcollision[key]

    def count(self, channel):
        """Counts msg for a channel, this should be called every time a msg is send in a channel."""
        if isChannel(channel):
            self.msgcount[channel] = self._getcount(channel) + 1
        #log.debug('RepeatQueue: message count for %s: %s.' % (channel, self.msgcount[channel]))

    def _getcount(self, channel):
        try:
            return self.msgcount[channel]
        except KeyError:
            return 0

factQueue = RepeatQueue()

class IrcReplies:
    """
    This is a wrapper for the irc object, contains methods keywords substitution and commonly used replies. Not all the
    replies used are here, some are specific to some commands, therefore they are in those commands' methods."""
    def __init__(self, irc, msg):
        self.irc = irc
        self.msg = msg
        self.channel = msg.args[0]
        self.silence = False

    def __getattr__(self, name):
        """Look in self.irc for methods not defined here."""
        return getattr(self.irc, name)

    def _substitution(self, s, fact=None, args=''):
        s2 = doArgSubstitution(s, args)
        if args:
            if s2 == s:
                # nothing was substituted, prefix args
                s = '%s: %s' %(args, s)
            else:
                s = s2
        elif self.irc.prefixNick and self.irc.to:
            # lets substitute with nick then
            s2 = doArgSubstitution(s, self.irc.to)
            if s2 != s:
                # worked, remove prefix
                self.irc.prefixNick = False
                s = s2
        elif s2 != s:
            s = s2
        return doSubstitution(self.irc, self.msg, s, fact)

    def _factSubstitution(self, s, fact):
        if fact:
            return doFactSubstitution(s, fact.db, self.msg.args[0])
        else:
            return s

    def _notice(self, s, fact=None, args='', **kwargs):
        """Implements notices sent to other channels, for notifying when a fact is created, edited, etc."""
        if fact and fact.checkFlag('nonotice'): return
        channels = conf.supybot.plugins.Factos.noticeInChannels()
        if not channels: return
        for channel in channels:
            if channel == self.channel: continue # don't notify in the same channel
            msg = ircmsgs.privmsg(channel, self._substitution(s, fact, args))
            log.debug('Forwarding msg to: %s msg: %s' %(channel, str(msg)))
            self.irc.queueMsg(msg)

    def _alert(self, fact, args='', to=None, prefixNick=None, **kwargs):
        if prefixNick is True and not args:
            args = to
        channels = conf.supybot.plugins.Factos.alertInChannels()
        if not channels: return
        logInfo(self.irc, self.msg, 'Alerting about $fact in %s' %str(channels), fact)
        for channel in channels:
            if channel == self.channel: continue # don't alert in the same channel
            if isChannel(channel):
                s = conf.supybot.plugins.Factos.alertInChannels.message.get(channel)()
            else:
                s = conf.supybot.plugins.Factos.alertInChannels.message()
            msg = ircmsgs.privmsg(channel, self._substitution(s, fact, args))
            self.irc.queueMsg(msg)

    def __reply(self, s, fact=None, noreplace=False, args='', **kwargs):
        """Send msg, replacing keywords if needed."""
        #log.debug('IrcReplies.__reply() s: %s kwargs: %s' % (s, kwargs))
        if not noreplace:
            s = self._substitution(s, fact, args=args)
            s = self._factSubstitution(s, fact)
        self.irc.reply(s, **kwargs)

    def noReply(self):
        self.irc.noReply()

    def error(self, s, **kwargs):
        self.irc.error(s, **kwargs)

    def reply(self, s, **kwargs):
        # TODO reply localization should be done here!
        if not self.silence:
            self.__reply(s, **kwargs)

    def fact(self, fact, to=None, private=None, prefixNick=None, info=False, raw=False, alert=False, **kwargs):
        """Used for display a fact. Will do some checks if fact is going to highlight/query
        somebody."""
        log.debug('IrcReplies.fact() fact: %s to: %s kwargs: %s' % (fact, to, kwargs))
        s = ''
        if to:
            # lets show that our bot isn't dumb
            channel = self.channel
            if to == self.irc.nick:
                # fact sent to ourselves
                s = 'Yo ya se que es $fact, gracias.'
            elif to == self.msg.nick:
                # fact sent to himself, always in private
                private = True
            elif not isChannel(channel) and to != self.msg.nick:
                # somebody in private is asking to send a fact to somebody, this can be abused so we
                # refuse to do so
                s = 'Lo siento, dile $fact tu mismo.'
            else:
                try:
                    usuarios = self.irc.state.channels[channel].users
                except KeyError:
                    usuarios = (self.msg.nick, )
                if to not in usuarios and not alert: # FIXME don't fail if the fact has +alert
                                                     # this is a workaround, I will have to rethink
                                                     # if checking nick validity is worth it.
                    # nick isn't in channel
                    s = 'No veo a nadie llamado %s.' % to
            if s:
                # user used a bad target, direct the reply msg to him.
                to = None
                if private:
                    private = None
                    prefixNick = True
                self.silence = True # any following reply will be ignored
            self.irc.to = to
            self.irc.prefixNick = prefixNick
        self.irc.private = private
        if not s:
            # everything ok, lets get the proper reply
            if raw:
                s = fact.raw()
            elif info:
                s = fact.info()
            else:
                if alert and not private and isChannel(self.channel):
                    # send a notice that this fact was called.
                    self._alert(fact, to=to, prefixNick=prefixNick, **kwargs)
                s = fact.data
        self.__reply(s, fact=fact, **kwargs)

    def created(self, fact, **kwargs):
        """New fact created reply."""
        self.__reply('Facto $fact creado.', fact, **kwargs)
        self._notice('$nick creó el facto $fact en $channel (${fact_len} letras)', fact)

    def duplicate(self, fact, **kwargs):
        """Duplicate fact reply (coulnd't create fact)"""
        self.__reply('$fact ya existe. Si desea editarlo utilise %sno.' %fact.prefix, fact,
                **kwargs)

    def edited(self, fact, **kwargs):
        """Fact edited reply."""
        self.__reply('Facto $fact actualizado.', fact, **kwargs)
        self._notice('$nick editó el facto $fact en $channel (${edit_size} letras editadas)', fact)

    def deleted(self, fact, **kwargs):
        """Fact deleted (disabled) reply."""
        self.__reply('Facto $fact borrado.', fact, **kwargs)
        self._notice('$nick borró $fact en $channel.', fact)

    def undeleted(self, fact, **kwargs):
        """Fact was restored reply (after being deleted)."""
        self.__reply('Facto $fact restaurado.', fact, **kwargs)
        self._notice('$nick restauró $fact en $channel.', fact)

    def locked(self, fact, **kwargs):
        """Fact locked reply."""
        self.__reply('Facto $fact protegido contra cambios.', fact, **kwargs)
        #self._notice('$nick protegió $fact en $channel.', fact)

    def unlocked(self, fact, **kwargs):
        """Fact unlocked reply."""
        self.__reply('$fact ahora se puede editar.', fact, **kwargs)
        #self._notice('$nick desprotegió $fact en $channel.', fact)

    def factNotFound(self, fact, **kwargs):
        """Fact not found reply. If config option quiet is True for that channel, bot will remain
        silent."""
        quiet = conf.supybot.plugins.Factos.quiet.get(self.channel)()
        if quiet:
            self.noReply()
        else:
            self.__reply('El facto $fact no existe.', fact, **kwargs)

    def factInvalid(self, fact, **kwargs):
        """Invalid fact reply. Got a fact too long either as input or from the database."""
        if len(fact):
            if len(fact.name) > fact.nameMaxLen:
                self.irc.reply('El nombre del facto tiene %d carácteres. El máximo es %d.' % \
                        (len(fact.name), fact.nameMaxLen))
                return
            elif len(fact) > fact.dataMaxLen:
                self.irc.reply('Me diste un facto de %d carácteres. El máximo es %d.' % \
                    (len(fact), fact.dataMaxLen))
                return
        raise callbacks.Error, 'El facto %s es inválido, esto es probablemente un bug o un error en la base.' % \
            fact

    def factForbidden(self, fact, **kwargs):
        """Fact forbidden reply. This is used when a fact is deleted and locked."""
        self.__reply('$fact está bloqueado.', fact, **kwargs)

    def factLocked(self, fact, **kwargs):
        """Fact is locked reply. When somebody attempts to edit it."""
        self.__reply('$fact está protegido contra cambios.', fact, **kwargs)


editorCapability = 'factosEdit'
modCapability = 'factosMod' # TODO not implemented yet
def checkCapability(irc, msg, capability='', onlyCapability=False):
    """Checks if user is allowed to edit the database, this is either because it has the needed
    capabilities, or because is in a channel that allows anybody present to do edits (it can be
    limited to public edits only, and not by query).
    onlyCapability only account user's capabilities and not the channel she/he's in."""

    channel = formatChannel(msg.args[0])
    config = conf.supybot.plugins.Factos.allow
    #log.debug('checkCapability: nick:%r cap:%r from:%r' % (msg.prefix, capability, channel))
    if ircdb.checkCapabilities(msg.prefix, (capability, 'admin')):
        # the user is authorised
        return True
    if channel:
        # the command was sent in the channel
        allow = config.get(channel)()
    else:
        # private command, try to guess if nick is in any channel that allows edits
        channels = [ chan for (chan, chanObj) in irc.state.channels.iteritems() if msg.nick in chanObj.users ]
        allow = False
        for channel in channels:
            if config.query.get(channel)() and config.get(channel)():
                allow = True
                break
        if allow:
            log.info('Allowing %r to edit facts because is present in %r.' % (msg.prefix, channel))
    if allow and not onlyCapability:
        # free to edit anything
        return True
    else:
        irc.errorNoCapability(capability or 'admin')
        return False

def capability(f):
    """Decorator for commands that needs capability check."""
    def check(self, irc, msg, *args):
        if checkCapability(irc, msg, editorCapability):
            f(self, irc, msg, *args)
    check.__doc__ = f.__doc__
    return check

def factExceptions(f):
    """Decorator that adds exceptions for catch our errors. It also wraps irc with IrcReplies, so
    this decorator should be used in all commands."""
    def exceptBlock(self, irc, msg, *args):
        irc = IrcReplies(irc, msg)
        try:
            f(self, irc, msg, *args)
        except FactNotFound, exc:
            irc.factNotFound(exc.fact)
            #log.warning(exc.info)
            #log.warning(exc.fact.debug())
            #log.warning(exc.fact.raw())
        except FactLocked, exc:
            irc.factLocked(exc.fact)
        except FactInvalid, exc:
            irc.factInvalid(exc.fact)
        except AliasLoop, exc:
            irc.error('alias recursivo: %s' %exc)
        except DatabaseError, exc:
            irc.error(str(exc))
    exceptBlock.__doc__ = f.__doc__
    return exceptBlock

def factParse(f):
    """Decorator for add fact parsing to commands that don't use regexps."""
    def parse(self, irc, msg, args, name):
        channel = msg.args[0]
        args = name.split()
        name, localChannel = Fact.stripChannel(args.pop(0))
        fact = self.Fact(name=name, channel=localChannel)
        user = self.User(host=msg.prefix)
        f(self, irc, msg, channel, user, fact, *args)
    parse.__doc__ = f.__doc__
    return parse

# Database config
filename = conf.supybot.directories.data.dirize(conf.supybot.plugins.Factos.sqlite.database())
SqliteDB = lambda file: objects.SqliteDB(file, tableFact, tableHist, tableHistRedo, tableUser)
factosDatabase = plugins.DB(filename, {'sqlite':SqliteDB})

class Factos(callbacks.Plugin):
    """See README.txt for detailed info of how to use this plugin."""
    flags = (re.IGNORECASE | re.VERBOSE)
    addressedRegexps = ('ignore', 'getFact', 'tellFact', 'addFact', 'editFact', 'addAlias',
            'substitute', 'substitute2', 'appendFact')

    def __init__(self, irc):
        self.__parent = super(Factos, self)
        self.__parent.__init__(irc)
        # compile regexps
        self.addressedRes = []
        for name in self.addressedRegexps:
            method = getattr(self, name)
            s = method.__doc__.replace(':fact:', Fact.regexp)
            r = re.compile(s, self.flags)
            self.addressedRes.append((r, name))
        # database
        try:
            self.db = factosDatabase()
        except DatabaseError, exc:
            raise callbacks.Error, exc
        # be sure users can't be editors
        anti = ircdb.makeAntiCapability(editorCapability)
        conf.supybot.capabilities().add(anti)
        # get channel access list in 1 min
        schedule.addEvent(lambda : self.updateAccessList(irc, None, None), 60) 

    def die(self):
        # remove plugin's capabilities
        anti = ircdb.makeAntiCapability(editorCapability)
        conf.supybot.capabilities().remove(anti)

    def doPrivmsg(self, irc, msg):
        factQueue.count(msg.args[0]) # kick the msg counter

    def doNotice(self, irc, msg):
        freenode.doNotice(irc, msg)

    def Fact(self, **kwargs):
        return Fact(db=self.db, **kwargs)

    def User(self, **kwargs):
        return User(db=self.db, **kwargs)

    @factExceptions
    def invalidCommand(self, irc, msg, tokens):
        channel = msg.args[0]
        message = msg.args[1]
        tokens = message.split()
        # remove prefix char, must be done in tokens so we don't discard any space after the prefix, because
        # such msgs should be ignored
        if tokens[0][0] in conf.supybot.reply.whenAddressedBy.chars():
            tokens[0] = tokens[0][1:]

        for (r, name) in self.addressedRes:
            methodOptions = name + 'Opts'
            # check for options, and strip them from msg if any
            if hasattr(self, methodOptions):
                optlist = getattr(self, methodOptions)
                log.debug('checking for opts: %s' %(optlist, ))
                try:
                    opts, message = getopt.gnu_getopt(tokens, '', optlist)
                except Exception, e:
                    if e.opt in optlist or (e.opt + '=') in optlist:
                        irc.error(e.msg)
                        return
                    else:
                        continue
                message = ' '.join(message)
            else:
                opts = None
                message = ' '.join(tokens)
            match = r.search(message)
            if match:
                log.debug('%s called: %s opts: %s msg: %r' %(name, match.groups(), opts, message))
                self.options = {}
                if opts:
                    for o, v in opts:
                        if not v:
                            v = True
                        self.options[o[2:]] = v
                getattr(self, name)(irc, msg, channel, match)
                break

    def ignore(self, irc, msg, channel, match):
        r"""^[^\wñÑ\#]  # anything that doesn't start with these chars should be ignored"""

        logInfo(irc, msg, 'ignoring $hostmask at $channel. msg: \'$msg\'')
        #debugfact('Factos._ignore', fact)
        irc.noReply()

    getFactOpts = ('info', 'raw', 'history=', 'noreplace', 'disabled')#, 'fullhistory')
    def getFact(self, irc, msg, channel, match):
        r"""^
        (:fact:)        # fact name
        (?:
        (?:\s?(>|\s)    # a separator: '>' or ' '
        \s?([^\s]+))    # one nick
        |
        (?:\s?\|        # a separator: '|'
        \s?(.+))        # any text
        )?
        $"""

        name, s, nick, args = match.groups()
        name, localChannel = Fact.stripChannel(name)
        if len(name) > Fact.nameMaxLen:
            irc.noReply()
            return
        if s is None and args is None:
            pass
        elif s == '>':
            self.options['private'] = True
            self.options['to'] = nick
        elif s == ' ':
            self.options['prefixNick'] = True
            self.options['to'] = nick
        elif args:
            self.options['args'] = args

        fact = self.Fact(name=name, channel=localChannel)
        logInfo(irc, msg, '$fact called by $hostmask at $channel.', fact)
        #debugfact('Factos._getFact', fact)

        if 'history' in self.options:
            try:
                id = int(self.options['history'])
            except ValueError:
                irc.error('Bad history id')
                return
            redo = ''
            if id > 0:
                # redo history
                redo = True
                hist = self.db.getHist(equal=fact.name, channel=fact.channel, table=tableHistRedo)
                id -= 1
            else:
                hist = self.db.getHist(equal=fact.name, channel=fact.channel)
                hist = list(hist)  
                hist.reverse()
            try:
                hist = hist[id]
            except IndexError:
                irc.reply('Sin historial.')
                return
            irc.reply('Revisión %s%s | \'%s:%s\'' % (redo and '(deshecha) ', hist['history_id'], hist['name'], hist['data']))
        elif 'fullhistory' in self.options:
            hist_list = self.db.getHist(equal=fact.name, channel=fact.channel)
            if hist_list:
                hist_list.reverse()
                for hist in hist_list:
                    irc.reply('Revisión Nº%s | \'%s:%s\'' % (hist['history_id'], hist['name'], hist['data']),
                            private=True)
            else:
                irc.reply('No history.')
        elif ('info' in self.options) or ('raw' in self.options):
            # pullDisabled=True as we might want info about a deleted fact
            fact.pull(channel, True)
            if fact:
                irc.fact(fact, **self.options)
        else:
            disabled = 'disabled' in self.options
            if disabled:
                del self.options['disabled']
                self.options['private'] = True
                # msg shouldn't go to anyone else other than the caller if disabled is True
                if 'to' in self.options:
                    del self.options['to']
                if 'prefixNick' in self.options:
                    del self.options['prefixNick']
            self._getFact(irc, msg, fact, channel, disabled)

    def _getFact(self, irc, msg, fact, channel, disabled=False):
        """Gets a fact and displays it. This method is for commands that calls facts but use
        different regexps."""

        fact.pull(channel, disabled)
        alias = fact.isAlias()
        if alias:
            alias_data, alias_flags = fact.getData(channel, disabled)
            trueFact = fact.getAlias()
            trueFact.pull(channel, disabled)
        else:
            alias_data, alias_flags = None, None
            trueFact = fact

        # test fact modes/flags
        if fact.checkFlag('mute', alias_flags):
            # fact is muted
            irc.noReply()
            return
        if fact.checkFlag('ignore', alias_flags):
            # fact is ignored
            return
        if fact.checkFlag('private', alias_flags):
            # fact should be replied in private
            self.options['to'] = msg.nick
            self.options['private'] = True
        if fact.checkFlag('noreplace', alias_flags):
            # keywords won't be replaced
            self.options['noreplace'] = True
        if fact.checkFlag('alert', alias_flags):
            self.options['alert'] = True
        if fact.checkFlag('action', alias_flags):
            self.options['action'] = True

        # repeat protection
        if factQueue.collision(trueFact.name, channel):
            logInfo(irc, msg, 'Not saying $fact due to a collision.', fact)
            irc.noReply()
            return
        key = factQueue.makeKey(fact.name, channel, self.options)
        if factQueue.inQueue(key):
            repeatKey = (fact.name, channel, 'repeat')
            if factQueue.inQueue(repeatKey, False):
                logInfo(irc, msg, 'Not saying $fact due to repeat protection.', fact)
                irc.noReply()
            else:
                irc.reply('Dije ${fact_name} hace un rato, mirá más arriba.', fact=fact)
            return
        elif alias:
            # check if the target of the alias was used
            key = factQueue.makeKey(trueFact.name, channel, self.options)
            if factQueue.inQueue(key):
                repeatKey = (trueFact.name, channel, 'alias_repeat')
                if factQueue.inQueue(repeatKey, False):
                    logInfo(irc, msg, 'Not saying $fact due to repeat protection.', fact)
                    irc.noReply()
                else:
                    irc.reply('${fact_name} es lo mismo que $alias, ya lo dije hace un rato, mirá más arriba.', fact=fact)
                return

        if isChannel(channel) and not disabled \
                              and 'noreplace' not in self.options:
            # ok, update request counter
            fact.request(msg.prefix)     
            fact.push()
            if fact.isAlias():
                trueFact.request(msg.prefix) # in the aliased fact as well, so detecting the most
                trueFact.push()              # popular fact is easier
        if alias_data is not None:
            fact.data = alias_data
        irc.fact(fact, **self.options)

    def tellFact(self, irc, msg, channel, match):
        r"""^
        dile\sa\s   # dile a <nick> sobre <facto> format
        ([^\s]+)    # nick
        \ssobre\s
        (:fact:)    # fact name
        $"""

        nick, name = match.groups()
        name, localChannel = Fact.stripChannel(name)
        fact = self.Fact(name=name, channel=localChannel)
        logInfo(irc, msg, '$fact called by $hostmask at $channel.', fact)

        self.options['to'] = nick
        self.options['private'] = True
        self._getFact(irc, msg, fact, channel)
        irc.reply('por favor mira mi mensaje privado.', to=nick, prefixNick=True)

    @capability
    def addFact(self, irc, msg, channel, match):
        r"""^
        (:fact:)            # fact name
        \s?(\ses\s|:)\s?    # separator: ' es ' or ':'
        (.+)                # fact's text
        $"""

        name, s, data = match.groups()
        name, localChannel = Fact.stripChannel(name)
        if s != ':':
            data = '%s%s%s' % (name, s, data)

        fact = self.Fact(name=name, channel=localChannel, data=data)
        logInfo(irc, msg, 'addFact called by $hostmask at $channel. \'$fact:$data\'', fact)
        #debugfact('addFact', fact)

        user = self.User(host=msg.prefix)
        user.pull()

        try:
            try:
                fact.pull(channel, True)
            except FactNotFound:
                fact.create(user.user_id)
                user.facts += 1
                user.push()
                irc.created(fact)
            else:
                if not fact.isDisabled():
                    irc.duplicate(fact)
                    return
                # fact exists, but is disabled
                fact.edit(user.user_id, data, alias=False)
                fact.undisable(user.user_id)
                fact.push()
                user.edits += 1
                user.push()
                irc.created(fact)
        except FactLocked:
            irc.factForbidden(fact)

    editFactOpts = ('preview', )
    @capability
    def editFact(self, irc, msg, channel, match):
        r"""^
        no[\s,]\s?  # must start with 'no,' or 'no '
        (.+)        # anything (for check against addFact or addAlias regexps)
        $"""

        edit = match.groups()[0]
        name = None
        for r, method in self.addressedRes:
            if method in ('addFact', 'addAlias'):
                match = r.search(edit)
                if match:
                    if method == 'addFact':
                        name, s, edit_data = match.groups()
                        name, localChannel = Fact.stripChannel(name)
                        if s != ':':
                            edit_data = '%s%s%s' % (name, s, edit_data)
                        edit_alias = 0
                        break
                    elif method == 'addAlias':
                        name, edit_data = match.groups()
                        name, localChannel = Fact.stripChannel(name)
                        edit_alias = Fact.f['alias']
                        break

        if not name: return
        fact = self.Fact(name=name, channel=localChannel, data=edit_data, flags=edit_alias)
        logInfo(irc, msg, 'editFact called by $hostmask at $channel. \'$fact:$data\'', fact)
        #debugfact('Factos._editFact', fact)

        self._editFact(irc, msg, channel, fact)

    def _editFact(self, irc, msg, channel, fact):
        """Edits a fact. Common code for commands that edit facts but use different regexps."""
        user = self.User(host=msg.prefix)
        user.pull()

        data = fact.data
        makeAlias = fact.isAlias()

        fact.pull(channel)
        if fact.isAlias():
            alias = fact.copy() # make a copy for use in the edit message
            fact.pullAlias(channel)
            if makeAlias and alias.name == fact.name:
                irc.factInvalid(fact)
                return
        else:
            alias = None
        if fact.data == data:
            irc.reply('Pero si %s ya dice eso.' % fact)
            return
        fact.edit(user.user_id, data, alias=makeAlias)
        if 'preview' in self.options:
            irc.reply('Preview: %s' % fact.data)
            return
        fact.push()
        user.edits += 1
        user.push()
        irc.edited(alias or fact)

    substituteOpts = ('preview', )
    @capability
    def substitute(self, irc, msg, channel, match):
        r"""^       # !sed/regexp/text/fact or !s/regexp/text/fact
        (?:s|sed)   # start with 's' or 'sed'
        (\W)        # any symbol (for use as delimiter)
        (.+)        # anything (sed regexp)
        \1          # the delimiter
        (.*)        # anything (replace text)
        \1          # the delimiter
        \s?(:fact:) # fact name
        $"""

        s, regexp, replace, fact = match.groups()
        self._substitute(irc, msg, channel, regexp, replace, fact)
    
    substitute2Opts = ('preview', )
    @capability
    def substitute2(self, irc, msg, channel, match): # alternate syntax for sed command
        r"""^    # !sed fact s/regexp/text/
        sed\s    # start with 'sed '
        (:fact:) # fact name
        \ss(\W)  # ' s' and any symbol (for use as delimiter)
        (.+)     # anything (sed regexp)
        \2       # the delimiter
        (.*)     # anything (replace text)
        \2       # the delimiter
        $"""
       
        fact, s, regexp, replace = match.groups()
        self._substitute(irc, msg, channel, regexp, replace, fact)
        
    def _substitute(self, irc, msg, channel, regexp, replace, fact):
        """Regexp substitute function."""
        name, localChannel = Fact.stripChannel(fact)

        fact = self.Fact(name=name, channel=localChannel)
        logInfo(irc, msg, 'substitute called by $hostmask at $channel. regexp:\'%s\' replace:\'%s\''
                'fact:\'$fact\'' %(regexp, replace), fact)
        #debugfact('Factos._substitute', fact)

        fact.pull(channel)
        fact.pullAlias(channel)
        try:
            if re.search(regexp, fact.data):
                fact.data = re.sub(regexp, replace, fact.data)
            else:
                irc.reply('El patrón \'%s\' no encontró nada para reemplazar.' %regexp)
                return
        except:
            irc.error('El patrón \'%s\' no es válido, ver '
                    'http://docs.python.org/lib/re-syntax.html' %regexp)
        else:
            self._editFact(irc, msg, channel, fact)

    appendFactOpts = ('preview', )
    @capability
    def appendFact(self, irc, msg, channel, match):
        r"""(?:añadir|añade|agregar?)\sa\s      # start with 'añadir a' or other variation
        (:fact:)                                # fact name
        \s(.+)                                  # text to append
        $"""

        name, data = match.groups()
        name, localChannel = Fact.stripChannel(name)
        fact = self.Fact(name=name, channel=localChannel)
        logInfo(irc, msg, 'appendFact called by $hostmask at $channel. append:\'%s\''
                'fact:\'$fact\'' %data, fact)

        fact.pull(channel)
        fact.pullAlias(channel)
        fact.data = '%s %s' % (fact.data, data)
        self._editFact(irc, msg, channel, fact)

    @capability
    def addAlias(self, irc, msg, channel, match):
        r"""^
        (:fact:)    # fact name (alias)
        \salias\s   # ' alias '
        (:fact:)    # fact name (alias target)
        $"""

        alias, factName = match.groups()
        alias, localChannel = Fact.stripChannel(alias)
        factName, factChannel = Fact.stripChannel(factName)
        fact = self.Fact(name=alias, channel=localChannel)
        target = self.Fact(name=factName, channel=factChannel)
        logInfo(irc, msg, 'addAlias called by $hostmask at $channel. \'%s\'\'%s\'' %(fact, target))
        debugfact('Factos._addAlias', fact)
        user = self.User(host=msg.prefix)

        user.pull()
        try:
            target.pull(channel)
            target.pullAlias(channel)
            if not factChannel and target.channel:
                target.channel = None #make sure alias pointing to generic facts stay generic
            try:
                fact.pull(channel, True)
                if not fact.isDisabled():
                    irc.duplicate(fact)
                    return
                fact.edit(user.user_id, target.id(prefix=False), alias=True)
                fact.undisable(user.user_id)
                fact.push()
                user.edits += 1
                user.push()
                irc.created(fact)
            except FactNotFound:
                fact.data = target.id(prefix=False)
                fact.markAlias()
                fact.create(user.user_id)
                user.facts += 1
                user.push()
                irc.created(fact)
        except FactLocked:
            irc.factForbidden(fact)

    @factExceptions
    @capability
    @factParse
    def delFact(self, irc, msg, channel, user, fact):
        """<facto>
        Borra el facto suministrado."""
        #debugfact('Factos.delFact', fact)
        logInfo(irc, msg, 'delFact channel: $channel msg: $msg')

        user.pull()
        fact.pull(channel)
        fact.disable(user.user_id)
        fact.push()
        user.push()
        irc.deleted(fact)

    borrar = wrap(delFact, ['something'])

    @factExceptions
    @capability
    @factParse
    def undelFact(self, irc, msg, channel, user, fact):
        """<facto>
        Restaura el facto anteriormente borrado."""
        #debugfact('Factos.undelFact', fact)
        logInfo(irc, msg, 'undelFact channel: $channel msg: $msg')

        user.pull()
        try:
            fact.pull(channel, True)
            if not fact.isDisabled():
                irc.reply('%s no se encuentra borrado.' % fact)
                return
            fact.undisable(user.user_id)
            fact.push()
            user.push()
            irc.undeleted(fact)
        except FactLocked, exc:
            irc.factForbidden(exc.fact)

    desborrar = wrap(undelFact, ['something'])

    @factExceptions
    @factParse
    def lockFact(self, irc, msg, channel, user, fact):
        """<facto>
        Protege el facto contra modificaciones,
        necesitas estar registrado como admin del bot para usar este comando."""
        #debugfact('Factos.lockFact', fact)
        logInfo(irc, msg, 'lockFact channel: $channel msg: $msg')

        user.pull()
        fact.pull(channel, True)
        fact.lock(user.user_id)
        fact.push()
        user.push()
        irc.locked(fact)

    proteger = wrap(lockFact, [('checkCapability', 'admin'), 'something'])

    @factExceptions
    @factParse
    def unlockFact(self, irc, msg, channel, user, fact):
        """<facto>
        Habilita el facto para ser modificado,
        necesitas estar registrado como admin del bot para usar este comando."""
        #debugfact('Factos.unlockFact', fact)
        logInfo(irc, msg, 'unlockFact channel: $channel msg: $msg')

        user.pull()
        fact.pull(channel, True)
        fact.unlock(user.user_id)
        fact.push()
        user.push()
        irc.unlocked(fact)

    desproteger = wrap(unlockFact, [('checkCapability', 'admin'), 'something'])

    # TODO should be refactored
    def search(self, irc, msg, args, text):
        """<clave> [<clave> ... ]
        Busca factos que contengan las claves suministradas."""
        logInfo(irc, msg, 'search channel: $channel msg: $msg')

        channel = formatChannel(msg.args[0])
        if '--all-channels' in text: # ugly but good for now
            text = text.replace('--all-channels', '')
            tableList = self.db.getTables(all=self.registryValue('sqlite.table.fact'))
        elif channel:
            tableList = self.db.getTables(inChannel=channel)
        else:
            tableList = self.db.getTables(all=self.registryValue('sqlite.table.fact'))
        facts = []
        #log.debug('Factos.search() tables=%s' % (tableList, ))

        def setFact(values, table):
            fact = Fact()
            fact.setValues(values)
            fact.channel = table.getChannel()
            return fact

        keywords = text.split()
        for table in tableList:
            facts.extend([ setFact(v, table) for v in self.db.search(keywords, table=table) ])
        # remove disabled
        facts = [ f for f in facts if not f.isDisabled() ]
        facts.sort()
        # remove duplicates (aliases) # XXX there should be other way
        r = range(len(facts)); r.reverse()
        for n in r:
            if facts[n] in facts[:n]:
                i = facts[:n].index(facts[n])
                # pop the least used one
                if facts[n].request_count > facts[i].request_count:
                    facts.pop(i)
                else:
                    facts.pop(n)
        if facts:
            if len(facts) > 1:
                reply = 'Se encontraron %s factos: ' % len(facts)
            else:
                reply = 'Se encontró un facto: '
            reply += ' '.join([ v.id(True, alias=False) for v in facts ])
            irc.reply(reply)
        else:
            if len(keywords) <= 1:
                keys = keywords[0]
            else:
                keys = ' y '.join((', '.join(keywords[:-1]), keywords[-1]))
            irc.reply('No se encontró nada con %s' % keys)

    buscar = wrap(search, ['text'])

    # TODO should be refactored
    def editor(self, irc, msg, args, optlist, userid):
        """[<nick|hostmask>] [--(id <número>|raw)]
        Muestra información sobre el usuario identificado por id, nick o hostmask de la tabla de usuarios.
        El nick y el hostmask acepta los comodines * y ?."""
        logInfo(irc, msg, 'editor channel: $channel msg: $msg')

        id = raw = None
        for (k, v) in optlist:
            if k == 'id': id = v
            if k == 'raw': raw = v

        def setUser(v):
            u = User()
            u.setValues(v)
            return u

        def formattedReply(u, prefix=''):
            s = '%s editó la base por primera vez en %s, y la última fué en %s. Agregó %s factos y %s'\
                    ' ediciones.' % (ircutils.nickFromHostmask(u.host), date(u.first_seen), date(u.last_seen),
                    u.facts, u.edits)
            if prefix:
                s = '%s %s' % (prefix, s)
            return s

        def needsAdmin(irc, msg):
            if not ircdb.checkCapability(msg.prefix, 'admin'):
                irc.errorNoCapability('admin')
                return True
            return False

        if id is not None:
            # checking by userid, this should be only done by an admin and privately so hostmasks won't be
            # public
            if needsAdmin(irc, msg): return
            user = self.db.getUserById(id)
            if user:
                if raw:
                    irc.reply(setUser(user).raw(), private=True)
                else:
                    irc.reply(formattedReply(setUser(user), 'id:%s %r' % (id, user['host'])), private=True)
            else:
                irc.reply('No encontré ningún usuario con el id %s.' % id, private=True)
        elif userid and ircutils.isUserHostmask(userid):
            # checking by hostmask, this should be only done by an admin and privately so hostmasks wonn't be
            # public
            if needsAdmin(irc, msg): return
            users = self.db.getUsers(userid)
            if users:
                s = '%s hostmask(s) encontrados. %s' % (len(users),
                    ', '.join([ 'id:%s %r' % (user['user_id'], user['host']) for user in users ]))
                irc.reply(s, private=True)
            else:
                irc.reply('No encontré ningún usuario con el hostmask %s.' % userid, private=True)
        elif userid and ircutils.isNick(userid):
            # checking by nick, anyone can use this.
            users = self.db.getUsers('%s!*@*' % userid)
            if users:
                if len(users) > 1:
                    users.sort(key=lambda x:x['first_seen'])
                    first_seen = users[0]['first_seen']
                    users.sort(key=lambda x:x['last_seen'])
                    last_seen = users[-1]['last_seen']
                    edits = facts = 0
                    nicks = []
                    for user in users:
                        edits += int(user['edits'])
                        facts += int(user['facts'])
                        # nicks might not be the same if wildcards are used
                        nicks.append(ircutils.nickFromHostmask(user['host']))
                    nicks = set(nicks)
                    host = ','.join(nicks) + '!*@*' # a bit hackish but good enough for me
                    user_id = '-1' # lets use an invalid user id
                    users = (user_id, host, first_seen, last_seen, facts, edits)
                else:
                    users = users[0]
                irc.reply(formattedReply(setUser(users)))
            else:
                irc.reply('No encontré ningún usuario con el nick %s.' % userid)
        elif userid:
            irc.error('%s es una identificación de usuario inválida.' % userid)
        else:
            irc.reply(callbacks.getHelp(self.editor))

    editor = wrap(editor, [getopts({'id':'int', 'raw':''}), optional('something')])

    @factExceptions
    @capability
    @factParse
    def undo(self, irc, msg, channel, user, fact):
        """<facto>
        Deshace el último cambio en el facto suministrado, puede revertir este cambio con el comando rehacer."""
        logInfo(irc, msg, 'undo channel: $channel msg: $msg')

        fact.pull(channel)
        hist = self.db.getHist(equal=fact.name, channel=fact.channel, limit=1)
        if hist:
            undo_hist = hist[0]
            self.db.updateHist(fact.getHist(), undo_hist['history_id'], channel=fact.channel)
            fact.upFromHist(undo_hist)
            fact.push()
            irc.edited(fact)
        else:
            irc.reply('No hay cambios para deshacer en %s.' % fact)

    deshacer = wrap(undo, ['something'])

    @factExceptions
    @capability
    @factParse
    def redo(self, irc, msg, channel, user, fact):
        """<facto>
        Rehace el último cambio deshecho en el facto suministrado."""
        logInfo(irc, msg, 'redo channel: $channel msg: $msg')

        fact.pull(channel)
        hist = self.db.getHist(equal=fact.name, channel=fact.channel, table=tableHistRedo, limit=1)
        if hist:
            redo_hist = hist[0]
            self.db.updateHist(fact.getHist(), redo_hist['history_id'], undo=False,
                    channel=fact.channel)
            fact.upFromHist(redo_hist)
            fact.push()
            irc.edited(fact)
        else:
            irc.reply('%s ya está en su último cambio.' % fact)

    rehacer = wrap(redo, ['something'])

    # TODO should be refactored
    def stats(self, irc, msg, args):
        """
        Muestra algunas estadísticas sobre la base de factos."""
        channel = formatChannel(msg.args[0])
        tableList = self.db.getTables(channel)
        #log.debug('Factos.stats() tables=%s' % (tableList, ))

        def setFact(values, table):
            fact = Fact()
            fact.setValues(values)
            fact.channel = table.getChannel()
            return fact

        def formatFactList(facts):
            i = [ fact.id(alias=False) for fact in facts ]
            return ', '.join(i)

        facts = []
        for table in tableList:
            facts.extend([ setFact(v, table) for v in self.db.get(table=table) ])
        deleted = alias = active = 0
        for fact in facts:
            if fact.isDisabled():
                deleted += 1
            elif fact.isAlias():
                alias += 1
            else:
                active += 1
        # sort by request count
        #log.debug('Factos.stats() facts=%s' % str([ f.id() for f in facts ]))
        facts.sort(key=lambda x: x.request_count)
        facts.reverse()
        #log.debug('Factos.stats() facts=%s' % str([ f.id() for f in facts ]))
        # drop least used aliases
        r = range(len(facts)); r.reverse()
        for n in r:
            if facts[n] in facts[:n]:
                del facts[n]
        #log.debug('Factos.stats() result=%s' % str((active, deleted, alias)))
        if active:
            irc.reply('Tengo almacenado %s factos activos y %s sinónimos. '\
                'Los más usados son %s.' % (active, alias, formatFactList(facts[:6])))
        else:
            irc.reply('No hay factos activos en la base.')

    estadistica = wrap(stats)

    @factExceptions
    @factParse
    def factStatus(self, irc, msg, channel, user, fact, *args):
        """<facto> [(+|-)propiedad ..]
        Permite modificar las propiedades especiales de cada facto."""
        logInfo(irc, msg, 'factflag channel: $channel msg: $msg')

        fact.pull(channel, True)

        def getFlags():
            flags = []
            for name, flag in Fact.f.iteritems():
                if fact.checkFlag(flag):
                    flags.append(name)
            if not flags:
                flags = '(none)'
            else:
                flags = ', '.join(flags)
            return flags

        if args:
            user.pull()
            for action in args:
                if action[0] not in ('-', '+'):
                    irc.error('invalid prefix, use +flag or -flag')
                    return
                try:
                    fact.setFlag(action, user.user_id)
                except KeyError:
                    irc.error('invalid mode flag, valid names: %s' %' '.join(fact.f.iterkeys()))
                    return
            fact.push()
            irc.reply('$fact mode set to: %s' %getFlags(), fact=fact)
        else:
            irc.reply('$fact mode: %s' %getFlags(), fact=fact)

    factmode = wrap(factStatus, [('checkCapability', 'admin'), 'text'])

    def updateAccessList(self, irc, msg, args):
        """
        Updates the list of users with access in the channels the bot is in. For special
        keywords."""
        # note this irc object isn't a IrcReplies instance.
        # this command shouldn't give replies, since is used in the scheduler
        channels = irc.state.channels.iterkeys()
        freenode.askAccessList(irc, channels)

    updateaccesslist = wrap(updateAccessList)


Class = Factos

# vim:set shiftwidth=4 softtabstop=4 tabstop=4 expandtab textwidth=100: