f6a08db748b6041f7bb166bb0d2c9310c81e7673
[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 "ctcphandler.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   network()->ctcpHandler()->query(nick, ctcpTag, message);
158   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
159 }
160
161 void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg) {
162 #ifdef HAVE_QCA2
163   if(!bufferInfo.isValid())
164     return;
165
166   QStringList parms = msg.split(' ', QString::SkipEmptyParts);
167
168   if(parms.isEmpty() && !bufferInfo.bufferName().isEmpty())
169     parms.prepend(bufferInfo.bufferName());
170
171   if(parms.isEmpty()) {
172     emit displayMsg(Message::Info, bufferInfo.bufferName(), "",
173                     tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
174     return;
175   }
176
177   QString target = parms.at(0);
178
179   if(network()->cipherKey(target).isEmpty()) {
180     emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("No key has been set for %1.").arg(target));
181     return;
182   }
183
184   network()->setCipherKey(target, QByteArray());
185
186   if(network()->isChannelName(target) && network()->channels().contains(target)) {
187     qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(false);
188   }
189   else if(network()->nicks().contains(target)) {
190     qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(false);
191   }
192
193   emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been deleted.").arg(target));
194
195 #else
196   Q_UNUSED(msg)
197   emit displayMsg(Message::Error, bufferInfo.bufferName(), "", tr("Error: Setting an encryption key requires Quassel to have been built "
198                                                                   "with support for the Qt Cryptographic Architecture (QCA2) library. "
199                                                                   "Contact your distributor about a Quassel package with QCA2 "
200                                                                   "support, or rebuild Quassel with QCA2 present."));
201 #endif
202 }
203
204 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
205   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
206   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
207   QStringList params;
208   params << bufferInfo.bufferName() << m << nicks;
209   emit putCmd("MODE", serverEncode(params));
210 }
211
212 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
213   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
214   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
215   QStringList params;
216   params << bufferInfo.bufferName() << m << nicks;
217   emit putCmd("MODE", serverEncode(params));
218 }
219
220 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
221   QStringList params;
222   params << msg << bufferInfo.bufferName();
223   emit putCmd("INVITE", serverEncode(params));
224 }
225
226 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
227   Q_UNUSED(bufferInfo);
228
229   // trim spaces before chans or keys
230   QString sane_msg = msg;
231   sane_msg.replace(QRegExp(", +"), ",");
232   QStringList params = sane_msg.trimmed().split(" ");
233
234   QStringList chans = params[0].split(",", QString::SkipEmptyParts);
235   QStringList keys;
236   if(params.count() > 1)
237     keys = params[1].split(",");
238
239   int i;
240   for(i = 0; i < chans.count(); i++) {
241     if(!network()->isChannelName(chans[i]))
242       chans[i].prepend('#');
243
244     if(i < keys.count()) {
245       network()->addChannelKey(chans[i], keys[i]);
246     } else {
247       network()->removeChannelKey(chans[i]);
248     }
249   }
250
251   static const char *cmd = "JOIN";
252   i = 0;
253   QStringList joinChans, joinKeys;
254   int slicesize = chans.count();
255   QList<QByteArray> encodedParams;
256
257   // go through all to-be-joined channels and (re)build the join list
258   while(i < chans.count()) {
259     joinChans.append(chans.at(i));
260     if(i < keys.count())
261       joinKeys.append(keys.at(i));
262
263     // if the channel list we built so far either contains all requested channels or exceeds
264     // the desired amount of channels in this slice, try to send what we have so far
265     if(++i == chans.count() || joinChans.count() >= slicesize) {
266       params.clear();
267       params.append(joinChans.join(","));
268       params.append(joinKeys.join(","));
269       encodedParams = serverEncode(params);
270       // check if it fits in one command
271       if(lastParamOverrun(cmd, encodedParams) == 0) {
272         emit putCmd(cmd, encodedParams);
273       } else if(slicesize > 1) {
274         // back to start of slice, try again with half the amount of channels
275         i -= slicesize;
276         slicesize /= 2;
277       }
278       joinChans.clear();
279       joinKeys.clear();
280     }
281   }
282 }
283
284 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
285   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
286   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
287   if(reason.isEmpty())
288     reason = network()->identityPtr()->kickReason();
289
290   QList<QByteArray> params;
291   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
292   emit putCmd("KICK", params);
293 }
294
295 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
296   Q_UNUSED(bufferInfo)
297   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
298   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
299   QList<QByteArray> params;
300   params << serverEncode(nick) << serverEncode(pass);
301   emit putCmd("KILL", params);
302 }
303
304
305 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
306   Q_UNUSED(bufferInfo)
307   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
308 }
309
310 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
311   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
312   network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
313   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
314 }
315
316 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
317   Q_UNUSED(bufferInfo)
318
319   QStringList params = msg.split(' ', QString::SkipEmptyParts);
320   // 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
321   if(!params.isEmpty()) {
322     if(!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
323       params.prepend(bufferInfo.bufferName());
324     if(network()->isMyNick(params[0]) && params.count() == 2)
325       network()->updateIssuedModes(params[1]);
326     if(params[0] == "-reset" && params.count() == 1) {
327       // FIXME: give feedback to the user (I don't want to add new strings right now)
328       network()->resetPersistentModes();
329       return;
330     }
331   }
332
333   // TODO handle correct encoding for buffer modes (channelEncode())
334   emit putCmd("MODE", serverEncode(params));
335 }
336
337 // TODO: show privmsgs
338 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
339   Q_UNUSED(bufferInfo);
340   if(!msg.contains(' '))
341     return;
342
343   QString target = msg.section(' ', 0, 0);
344   QByteArray encMsg = userEncode(target, msg.section(' ', 1));
345
346 #ifdef HAVE_QCA2
347   putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
348 #else
349   putPrivmsg(serverEncode(target), encMsg);
350 #endif
351 }
352
353 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
354   Q_UNUSED(bufferInfo)
355   QString nick = msg.section(' ', 0, 0);
356   emit putCmd("NICK", serverEncode(nick));
357 }
358
359 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
360   QString bufferName = msg.section(' ', 0, 0);
361   QString payload = msg.section(' ', 1);
362   QList<QByteArray> params;
363   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
364   emit putCmd("NOTICE", params);
365   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
366 }
367
368 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
369   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
370   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
371   QStringList params;
372   params << bufferInfo.bufferName() << m << nicks;
373   emit putCmd("MODE", serverEncode(params));
374 }
375
376 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
377   Q_UNUSED(bufferInfo)
378   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
379 }
380
381 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
382   QList<QByteArray> params;
383   QString partReason;
384
385   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
386   QString channelName = msg.section(' ', 0, 0);
387   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
388     channelName = bufferInfo.bufferName();
389     partReason = msg;
390   } else {
391     partReason = msg.mid(channelName.length() + 1);
392   }
393
394   if(partReason.isEmpty())
395     partReason = network()->identityPtr()->partReason();
396
397   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
398   emit putCmd("PART", params);
399 }
400
401 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
402   Q_UNUSED(bufferInfo)
403
404   QString param = msg;
405   if(param.isEmpty())
406     param = QTime::currentTime().toString("hh:mm:ss.zzz");
407
408   putCmd("PING", serverEncode(param));
409 }
410
411 // TODO: implement queries
412 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
413   Q_UNUSED(bufferInfo)
414   QString target = msg.section(' ', 0, 0);
415   QString message = msg.section(' ', 1);
416   if(message.isEmpty())
417     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with 1%").arg(target), network()->myNick(), Message::Self);
418   else
419     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
420   handleMsg(bufferInfo, msg);
421 }
422
423 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
424   Q_UNUSED(bufferInfo)
425   network()->disconnectFromIrc(true, msg);
426 }
427
428 void CoreUserInputHandler::issueQuit(const QString &reason) {
429   emit putCmd("QUIT", serverEncode(reason));
430 }
431
432 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
433   Q_UNUSED(bufferInfo)
434   emit putRawLine(serverEncode(msg));
435 }
436
437 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
438   if(bufferInfo.bufferName().isEmpty())
439     return;  // server buffer
440
441   QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
442 #ifdef HAVE_QCA2
443   putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
444 #else
445   putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
446 #endif
447   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
448 }
449
450 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg) {
451 #ifdef HAVE_QCA2
452   if(!bufferInfo.isValid())
453     return;
454
455   QStringList parms = msg.split(' ', QString::SkipEmptyParts);
456
457   if(parms.count() == 1 && !bufferInfo.bufferName().isEmpty())
458     parms.prepend(bufferInfo.bufferName());
459   else if(parms.count() != 2) {
460     emit displayMsg(Message::Info, bufferInfo.bufferName(),
461                     tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
462                        "/setkey <key> when in a channel or query buffer sets the key for it."));
463     return;
464   }
465
466   QString target = parms.at(0);
467   QByteArray key = parms.at(1).toLocal8Bit();
468
469   network()->setCipherKey(target, key);
470
471   if(network()->isChannelName(target) && network()->channels().contains(target))
472     qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(true);
473   else if(network()->nicks().contains(target))
474     qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(true);
475
476   emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been set.").arg(target));
477 #else
478   Q_UNUSED(msg)
479   emit displayMsg(Message::Error, bufferInfo.bufferName(), tr("Error: Setting an encryption key requires Quassel to have been built "
480                                                               "with support for the Qt Cryptographic Architecture (QCA) library. "
481                                                               "Contact your distributor about a Quassel package with QCA "
482                                                               "support, or rebuild Quassel with QCA present."));
483 #endif
484 }
485
486 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
487   if(bufferInfo.bufferName().isEmpty())
488     return;
489
490   QList<QByteArray> params;
491   params << serverEncode(bufferInfo.bufferName());
492
493   if(!msg.isEmpty()) {
494 #   ifdef HAVE_QCA2
495       params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
496 #   else
497       params << channelEncode(bufferInfo.bufferName(), msg);
498 #   endif
499   }
500
501   emit putCmd("TOPIC", params);
502 }
503
504 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
505   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
506   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
507   QStringList params;
508   params << bufferInfo.bufferName() << m << nicks;
509   emit putCmd("MODE", serverEncode(params));
510 }
511
512 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
513   int splitPos = msg.indexOf(';');
514   if(splitPos <= 0)
515     return;
516
517   bool ok;
518   int delay = msg.left(splitPos).trimmed().toInt(&ok);
519   if(!ok)
520     return;
521
522   delay *= 1000;
523
524   QString command = msg.mid(splitPos + 1).trimmed();
525   if(command.isEmpty())
526     return;
527
528   _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
529 }
530
531 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
532   Q_UNUSED(bufferInfo)
533   emit putCmd("WHO", serverEncode(msg.split(' ')));
534 }
535
536 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
537   Q_UNUSED(bufferInfo)
538   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
539 }
540
541 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
542   Q_UNUSED(bufferInfo)
543   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
544 }
545
546 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
547   Q_UNUSED(bufferInfo);
548   emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
549 }
550
551 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher) {
552   // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,
553   // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted
554   // version is short enough...
555   // TODO: check out how the various possible encryption methods behave length-wise and make
556   //       this clean by predicting the length of the crypted msg.
557   //       For example, blowfish-ebc seems to create 8-char chunks.
558
559   static const char *cmd = "PRIVMSG";
560   static const char *splitter = " .,-";
561
562   int maxSplitPos = message.count();
563   int splitPos = maxSplitPos;
564   forever {
565     QByteArray crypted = message.left(splitPos);
566     bool isEncrypted = false;
567 #ifdef HAVE_QCA2
568     if(cipher && !message.isEmpty()) {
569       isEncrypted = cipher->encrypt(crypted);
570     }
571 #endif
572     int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted);
573     if(overrun) {
574       // In case this is not an encrypted msg, we can just cut off at the end
575       if(!isEncrypted)
576         maxSplitPos = message.count() - overrun;
577
578       splitPos = -1;
579       for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
580         splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
581       }
582       if(splitPos <= 0 || splitPos > maxSplitPos)
583         splitPos = maxSplitPos;
584
585       maxSplitPos = splitPos - 1;
586       if(maxSplitPos <= 0) { // this should never happen, but who knows...
587         qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data());
588         return;
589       }
590       continue;  // we never come back here for !encrypted!
591     }
592
593     // now we have found a valid splitpos (or didn't need to split to begin with)
594     putCmd(cmd, QList<QByteArray>() << target << crypted);
595     if(splitPos < message.count())
596       putPrivmsg(target, message.mid(splitPos), cipher);
597
598     return;
599   }
600 }
601
602 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
603 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
604   // the server will pass our message truncated to 512 bytes including CRLF with the following format:
605   // ":prefix COMMAND param0 param1 :lastparam"
606   // where prefix = "nickname!user@host"
607   // that means that the last message can be as long as:
608   // 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)
609   IrcUser *me = network()->me();
610   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
611
612   if(me)
613     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
614
615   if(!params.isEmpty()) {
616     for(int i = 0; i < params.count() - 1; i++) {
617       maxLen -= (params[i].count() + 1);
618     }
619     maxLen -= 2; // " :" last param separator;
620
621     if(params.last().count() > maxLen) {
622       return params.last().count() - maxLen;
623     } else {
624       return 0;
625     }
626   } else {
627     return 0;
628   }
629 }
630
631 #ifdef HAVE_QCA2
632 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const {
633   if(didEncrypt)
634     *didEncrypt = false;
635
636   if(message_.isEmpty())
637     return message_;
638
639   Cipher *cipher = network()->cipher(target);
640   if(!cipher)
641     return message_;
642
643   QByteArray message = message_;
644   bool result = cipher->encrypt(message);
645   if(didEncrypt)
646     *didEncrypt = result;
647
648   return message;
649 }
650 #endif
651
652 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
653   if(!_delayedCommands.contains(event->timerId())) {
654     QObject::timerEvent(event);
655     return;
656   }
657   BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
658   QString rawCommand = _delayedCommands[event->timerId()].command;
659   _delayedCommands.remove(event->timerId());
660   event->accept();
661
662   // the stored command might be the result of an alias expansion, so we need to split it up again
663   QStringList commands = rawCommand.split(QRegExp("; ?"));
664   foreach(QString command, commands) {
665     handleUserInput(bufferInfo, command);
666   }
667 }