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