despammificating the pglog
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #include "coreuserinputhandler.h"
21
22 #include "util.h"
23
24 #include "ctcpparser.h"
25
26 #include <QRegExp>
27
28 #ifdef HAVE_QCA2
29 #  include "cipher.h"
30 #endif
31
32 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
33   : CoreBasicHandler(parent)
34 {
35 }
36
37 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) {
38   if(msg.isEmpty())
39     return;
40
41   AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
42
43   for(int i = 0; i < list.count(); i++) {
44     QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
45     QString payload = list.at(i).second.section(' ', 1);
46     handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
47   }
48 }
49
50 // ====================
51 //  Public Slots
52 // ====================
53 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
54   Q_UNUSED(bufferInfo)
55   if(msg.startsWith("-all")) {
56     if(msg.length() == 4) {
57       coreSession()->globalAway();
58       return;
59     }
60     Q_ASSERT(msg.length() > 4);
61     if(msg[4] == ' ') {
62       coreSession()->globalAway(msg.mid(5));
63       return;
64     }
65   }
66   issueAway(msg);
67 }
68
69 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck) {
70   QString awayMsg = msg;
71   IrcUser *me = network()->me();
72
73   // if there is no message supplied we have to check if we are already away or not
74   if(autoCheck && msg.isEmpty()) {
75     if(me && !me->isAway()) {
76       Identity *identity = network()->identityPtr();
77       if(identity) {
78         awayMsg = identity->awayReason();
79       }
80       if(awayMsg.isEmpty()) {
81         awayMsg = tr("away");
82       }
83     }
84   }
85   if(me)
86     me->setAwayMessage(awayMsg);
87
88   putCmd("AWAY", serverEncode(awayMsg));
89 }
90
91 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
92   banOrUnban(bufferInfo, msg, true);
93 }
94
95 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
96   banOrUnban(bufferInfo, msg, false);
97 }
98
99 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
100   QString banChannel;
101   QString banUser;
102
103   QStringList params = msg.split(" ");
104
105   if(!params.isEmpty() && isChannelName(params[0])) {
106     banChannel = params.takeFirst();
107   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
108     banChannel = bufferInfo.bufferName();
109   } else {
110     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
111     return;
112   }
113
114   if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
115     IrcUser *ircuser = network()->ircUser(params[0]);
116     // generalizedHost changes <nick> to  *!ident@*.sld.tld.
117     QString generalizedHost = ircuser->host();
118     if(generalizedHost.isEmpty()) {
119       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
120       return;
121     }
122
123     static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
124     if(ipAddress.exactMatch(generalizedHost))    {
125         int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
126         generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
127     } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
128       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
129       generalizedHost.replace(0, secondLastPeriodPosition, "*");
130     }
131     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
132   } else {
133     banUser = params.join(" ");
134   }
135
136   QString banMode = ban ? "+b" : "-b";
137   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
138   emit putRawLine(serverEncode(banMsg));
139 }
140
141 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
142   Q_UNUSED(bufferInfo)
143
144   QString nick = msg.section(' ', 0, 0);
145   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
146   if(ctcpTag.isEmpty())
147     return;
148
149   QString message = msg.section(' ', 2);
150   QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
151
152   if(ctcpTag == "PING") {
153     uint now = QDateTime::currentDateTime().toTime_t();
154     message = QString::number(now);
155   }
156
157   // FIXME make this a proper event
158   coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
159   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
160 }
161
162 void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg) {
163 #ifdef HAVE_QCA2
164   if(!bufferInfo.isValid())
165     return;
166
167   QStringList parms = msg.split(' ', QString::SkipEmptyParts);
168
169   if(parms.isEmpty() && !bufferInfo.bufferName().isEmpty())
170     parms.prepend(bufferInfo.bufferName());
171
172   if(parms.isEmpty()) {
173     emit displayMsg(Message::Info, bufferInfo.bufferName(), "",
174                     tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
175     return;
176   }
177
178   QString target = parms.at(0);
179
180   if(network()->cipherKey(target).isEmpty()) {
181     emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("No key has been set for %1.").arg(target));
182     return;
183   }
184
185   network()->setCipherKey(target, QByteArray());
186
187   if(network()->isChannelName(target) && network()->channels().contains(target)) {
188     qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(false);
189   }
190   else if(network()->nicks().contains(target)) {
191     qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(false);
192   }
193
194   emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been deleted.").arg(target));
195
196 #else
197   Q_UNUSED(msg)
198   emit displayMsg(Message::Error, bufferInfo.bufferName(), "", tr("Error: Setting an encryption key requires Quassel to have been built "
199                                                                   "with support for the Qt Cryptographic Architecture (QCA2) library. "
200                                                                   "Contact your distributor about a Quassel package with QCA2 "
201                                                                   "support, or rebuild Quassel with QCA2 present."));
202 #endif
203 }
204
205 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
206   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
207   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
208   QStringList params;
209   params << bufferInfo.bufferName() << m << nicks;
210   emit putCmd("MODE", serverEncode(params));
211 }
212
213 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
214   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
215   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
216   QStringList params;
217   params << bufferInfo.bufferName() << m << nicks;
218   emit putCmd("MODE", serverEncode(params));
219 }
220
221 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
222   QStringList params;
223   params << msg << bufferInfo.bufferName();
224   emit putCmd("INVITE", serverEncode(params));
225 }
226
227 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
228   Q_UNUSED(bufferInfo);
229
230   // trim spaces before chans or keys
231   QString sane_msg = msg;
232   sane_msg.replace(QRegExp(", +"), ",");
233   QStringList params = sane_msg.trimmed().split(" ");
234
235   QStringList chans = params[0].split(",", QString::SkipEmptyParts);
236   QStringList keys;
237   if(params.count() > 1)
238     keys = params[1].split(",");
239
240   int i;
241   for(i = 0; i < chans.count(); i++) {
242     if(!network()->isChannelName(chans[i]))
243       chans[i].prepend('#');
244
245     if(i < keys.count()) {
246       network()->addChannelKey(chans[i], keys[i]);
247     } else {
248       network()->removeChannelKey(chans[i]);
249     }
250   }
251
252   static const char *cmd = "JOIN";
253   i = 0;
254   QStringList joinChans, joinKeys;
255   int slicesize = chans.count();
256   QList<QByteArray> encodedParams;
257
258   // go through all to-be-joined channels and (re)build the join list
259   while(i < chans.count()) {
260     joinChans.append(chans.at(i));
261     if(i < keys.count())
262       joinKeys.append(keys.at(i));
263
264     // if the channel list we built so far either contains all requested channels or exceeds
265     // the desired amount of channels in this slice, try to send what we have so far
266     if(++i == chans.count() || joinChans.count() >= slicesize) {
267       params.clear();
268       params.append(joinChans.join(","));
269       params.append(joinKeys.join(","));
270       encodedParams = serverEncode(params);
271       // check if it fits in one command
272       if(lastParamOverrun(cmd, encodedParams) == 0) {
273         emit putCmd(cmd, encodedParams);
274       } else if(slicesize > 1) {
275         // back to start of slice, try again with half the amount of channels
276         i -= slicesize;
277         slicesize /= 2;
278       }
279       joinChans.clear();
280       joinKeys.clear();
281     }
282   }
283 }
284
285 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
286   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
287   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
288   if(reason.isEmpty())
289     reason = network()->identityPtr()->kickReason();
290
291   QList<QByteArray> params;
292   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
293   emit putCmd("KICK", params);
294 }
295
296 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
297   Q_UNUSED(bufferInfo)
298   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
299   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
300   QList<QByteArray> params;
301   params << serverEncode(nick) << serverEncode(pass);
302   emit putCmd("KILL", params);
303 }
304
305
306 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
307   Q_UNUSED(bufferInfo)
308   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
309 }
310
311 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
312   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
313   // FIXME make this a proper event
314   coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", msg);
315   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
316 }
317
318 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
319   Q_UNUSED(bufferInfo)
320
321   QStringList params = msg.split(' ', QString::SkipEmptyParts);
322   // if the first argument is neither a channel nor us (user modes are only to oneself) the current buffer is assumed to be the target
323   if(!params.isEmpty()) {
324     if(!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
325       params.prepend(bufferInfo.bufferName());
326     if(network()->isMyNick(params[0]) && params.count() == 2)
327       network()->updateIssuedModes(params[1]);
328     if(params[0] == "-reset" && params.count() == 1) {
329       // FIXME: give feedback to the user (I don't want to add new strings right now)
330       network()->resetPersistentModes();
331       return;
332     }
333   }
334
335   // TODO handle correct encoding for buffer modes (channelEncode())
336   emit putCmd("MODE", serverEncode(params));
337 }
338
339 // TODO: show privmsgs
340 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
341   Q_UNUSED(bufferInfo);
342   if(!msg.contains(' '))
343     return;
344
345   QString target = msg.section(' ', 0, 0);
346   QByteArray encMsg = userEncode(target, msg.section(' ', 1));
347
348 #ifdef HAVE_QCA2
349   putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
350 #else
351   putPrivmsg(serverEncode(target), encMsg);
352 #endif
353 }
354
355 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
356   Q_UNUSED(bufferInfo)
357   QString nick = msg.section(' ', 0, 0);
358   emit putCmd("NICK", serverEncode(nick));
359 }
360
361 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
362   QString bufferName = msg.section(' ', 0, 0);
363   QString payload = msg.section(' ', 1);
364   QList<QByteArray> params;
365   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
366   emit putCmd("NOTICE", params);
367   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
368 }
369
370 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
371   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
372   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
373   QStringList params;
374   params << bufferInfo.bufferName() << m << nicks;
375   emit putCmd("MODE", serverEncode(params));
376 }
377
378 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
379   Q_UNUSED(bufferInfo)
380   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
381 }
382
383 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
384   QList<QByteArray> params;
385   QString partReason;
386
387   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
388   QString channelName = msg.section(' ', 0, 0);
389   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
390     channelName = bufferInfo.bufferName();
391     partReason = msg;
392   } else {
393     partReason = msg.mid(channelName.length() + 1);
394   }
395
396   if(partReason.isEmpty())
397     partReason = network()->identityPtr()->partReason();
398
399   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
400   emit putCmd("PART", params);
401 }
402
403 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
404   Q_UNUSED(bufferInfo)
405
406   QString param = msg;
407   if(param.isEmpty())
408     param = QTime::currentTime().toString("hh:mm:ss.zzz");
409
410   putCmd("PING", serverEncode(param));
411 }
412
413 // TODO: implement queries
414 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
415   Q_UNUSED(bufferInfo)
416   QString target = msg.section(' ', 0, 0);
417   QString message = msg.section(' ', 1);
418   if(message.isEmpty())
419     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with %1").arg(target), network()->myNick(), Message::Self);
420   else
421     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
422   handleMsg(bufferInfo, msg);
423 }
424
425 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
426   Q_UNUSED(bufferInfo)
427   network()->disconnectFromIrc(true, msg);
428 }
429
430 void CoreUserInputHandler::issueQuit(const QString &reason) {
431   emit putCmd("QUIT", serverEncode(reason));
432 }
433
434 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
435   Q_UNUSED(bufferInfo)
436   emit putRawLine(serverEncode(msg));
437 }
438
439 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
440   if(bufferInfo.bufferName().isEmpty())
441     return;  // server buffer
442
443   QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
444 #ifdef HAVE_QCA2
445   putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
446 #else
447   putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
448 #endif
449   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
450 }
451
452 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg) {
453 #ifdef HAVE_QCA2
454   if(!bufferInfo.isValid())
455     return;
456
457   QStringList parms = msg.split(' ', QString::SkipEmptyParts);
458
459   if(parms.count() == 1 && !bufferInfo.bufferName().isEmpty())
460     parms.prepend(bufferInfo.bufferName());
461   else if(parms.count() != 2) {
462     emit displayMsg(Message::Info, bufferInfo.bufferName(),
463                     tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
464                        "/setkey <key> when in a channel or query buffer sets the key for it."));
465     return;
466   }
467
468   QString target = parms.at(0);
469   QByteArray key = parms.at(1).toLocal8Bit();
470
471   network()->setCipherKey(target, key);
472
473   if(network()->isChannelName(target) && network()->channels().contains(target))
474     qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(true);
475   else if(network()->nicks().contains(target))
476     qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(true);
477
478   emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been set.").arg(target));
479 #else
480   Q_UNUSED(msg)
481   emit displayMsg(Message::Error, bufferInfo.bufferName(), tr("Error: Setting an encryption key requires Quassel to have been built "
482                                                               "with support for the Qt Cryptographic Architecture (QCA) library. "
483                                                               "Contact your distributor about a Quassel package with QCA "
484                                                               "support, or rebuild Quassel with QCA present."));
485 #endif
486 }
487
488 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
489   if(bufferInfo.bufferName().isEmpty())
490     return;
491
492   QList<QByteArray> params;
493   params << serverEncode(bufferInfo.bufferName());
494
495   if(!msg.isEmpty()) {
496 #   ifdef HAVE_QCA2
497       params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
498 #   else
499       params << channelEncode(bufferInfo.bufferName(), msg);
500 #   endif
501   }
502
503   emit putCmd("TOPIC", params);
504 }
505
506 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
507   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
508   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
509   QStringList params;
510   params << bufferInfo.bufferName() << m << nicks;
511   emit putCmd("MODE", serverEncode(params));
512 }
513
514 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
515   int splitPos = msg.indexOf(';');
516   if(splitPos <= 0)
517     return;
518
519   bool ok;
520   int delay = msg.left(splitPos).trimmed().toInt(&ok);
521   if(!ok)
522     return;
523
524   delay *= 1000;
525
526   QString command = msg.mid(splitPos + 1).trimmed();
527   if(command.isEmpty())
528     return;
529
530   _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
531 }
532
533 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
534   Q_UNUSED(bufferInfo)
535   emit putCmd("WHO", serverEncode(msg.split(' ')));
536 }
537
538 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
539   Q_UNUSED(bufferInfo)
540   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
541 }
542
543 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
544   Q_UNUSED(bufferInfo)
545   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
546 }
547
548 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
549   Q_UNUSED(bufferInfo);
550   emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
551 }
552
553 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher) {
554   // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,
555   // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted
556   // version is short enough...
557   // TODO: check out how the various possible encryption methods behave length-wise and make
558   //       this clean by predicting the length of the crypted msg.
559   //       For example, blowfish-ebc seems to create 8-char chunks.
560
561   static const char *cmd = "PRIVMSG";
562   static const char *splitter = " .,-";
563
564   int maxSplitPos = message.count();
565   int splitPos = maxSplitPos;
566   forever {
567     QByteArray crypted = message.left(splitPos);
568     bool isEncrypted = false;
569 #ifdef HAVE_QCA2
570     if(cipher && !message.isEmpty()) {
571       isEncrypted = cipher->encrypt(crypted);
572     }
573 #endif
574     int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted);
575     if(overrun) {
576       // In case this is not an encrypted msg, we can just cut off at the end
577       if(!isEncrypted)
578         maxSplitPos = message.count() - overrun;
579
580       splitPos = -1;
581       for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
582         splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
583       }
584       if(splitPos <= 0 || splitPos > maxSplitPos)
585         splitPos = maxSplitPos;
586
587       maxSplitPos = splitPos - 1;
588       if(maxSplitPos <= 0) { // this should never happen, but who knows...
589         qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data());
590         return;
591       }
592       continue;  // we never come back here for !encrypted!
593     }
594
595     // now we have found a valid splitpos (or didn't need to split to begin with)
596     putCmd(cmd, QList<QByteArray>() << target << crypted);
597     if(splitPos < message.count())
598       putPrivmsg(target, message.mid(splitPos), cipher);
599
600     return;
601   }
602 }
603
604 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
605 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
606   // the server will pass our message truncated to 512 bytes including CRLF with the following format:
607   // ":prefix COMMAND param0 param1 :lastparam"
608   // where prefix = "nickname!user@host"
609   // that means that the last message can be as long as:
610   // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
611   IrcUser *me = network()->me();
612   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
613
614   if(me)
615     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
616
617   if(!params.isEmpty()) {
618     for(int i = 0; i < params.count() - 1; i++) {
619       maxLen -= (params[i].count() + 1);
620     }
621     maxLen -= 2; // " :" last param separator;
622
623     if(params.last().count() > maxLen) {
624       return params.last().count() - maxLen;
625     } else {
626       return 0;
627     }
628   } else {
629     return 0;
630   }
631 }
632
633 #ifdef HAVE_QCA2
634 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const {
635   if(didEncrypt)
636     *didEncrypt = false;
637
638   if(message_.isEmpty())
639     return message_;
640
641   Cipher *cipher = network()->cipher(target);
642   if(!cipher)
643     return message_;
644
645   QByteArray message = message_;
646   bool result = cipher->encrypt(message);
647   if(didEncrypt)
648     *didEncrypt = result;
649
650   return message;
651 }
652 #endif
653
654 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
655   if(!_delayedCommands.contains(event->timerId())) {
656     QObject::timerEvent(event);
657     return;
658   }
659   BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
660   QString rawCommand = _delayedCommands[event->timerId()].command;
661   _delayedCommands.remove(event->timerId());
662   event->accept();
663
664   // the stored command might be the result of an alias expansion, so we need to split it up again
665   QStringList commands = rawCommand.split(QRegExp("; ?"));
666   foreach(QString command, commands) {
667     handleUserInput(bufferInfo, command);
668   }
669 }