Reformat ALL the source!
[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
38 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg)
39 {
40     if (msg.isEmpty())
41         return;
42
43     AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
44
45     for (int i = 0; i < list.count(); i++) {
46         QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
47         QString payload = list.at(i).second.section(' ', 1);
48         handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
49     }
50 }
51
52
53 // ====================
54 //  Public Slots
55 // ====================
56 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg)
57 {
58     Q_UNUSED(bufferInfo)
59     if (msg.startsWith("-all")) {
60         if (msg.length() == 4) {
61             coreSession()->globalAway();
62             return;
63         }
64         Q_ASSERT(msg.length() > 4);
65         if (msg[4] == ' ') {
66             coreSession()->globalAway(msg.mid(5));
67             return;
68         }
69     }
70     issueAway(msg);
71 }
72
73
74 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck)
75 {
76     QString awayMsg = msg;
77     IrcUser *me = network()->me();
78
79     // if there is no message supplied we have to check if we are already away or not
80     if (autoCheck && msg.isEmpty()) {
81         if (me && !me->isAway()) {
82             Identity *identity = network()->identityPtr();
83             if (identity) {
84                 awayMsg = identity->awayReason();
85             }
86             if (awayMsg.isEmpty()) {
87                 awayMsg = tr("away");
88             }
89         }
90     }
91     if (me)
92         me->setAwayMessage(awayMsg);
93
94     putCmd("AWAY", serverEncode(awayMsg));
95 }
96
97
98 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg)
99 {
100     banOrUnban(bufferInfo, msg, true);
101 }
102
103
104 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg)
105 {
106     banOrUnban(bufferInfo, msg, false);
107 }
108
109
110 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban)
111 {
112     QString banChannel;
113     QString banUser;
114
115     QStringList params = msg.split(" ");
116
117     if (!params.isEmpty() && isChannelName(params[0])) {
118         banChannel = params.takeFirst();
119     }
120     else if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
121         banChannel = bufferInfo.bufferName();
122     }
123     else {
124         emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
125         return;
126     }
127
128     if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
129         IrcUser *ircuser = network()->ircUser(params[0]);
130         // generalizedHost changes <nick> to  *!ident@*.sld.tld.
131         QString generalizedHost = ircuser->host();
132         if (generalizedHost.isEmpty()) {
133             emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
134             return;
135         }
136
137         static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
138         if (ipAddress.exactMatch(generalizedHost))    {
139             int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
140             generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
141         }
142         else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
143             int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
144             generalizedHost.replace(0, secondLastPeriodPosition, "*");
145         }
146         banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
147     }
148     else {
149         banUser = params.join(" ");
150     }
151
152     QString banMode = ban ? "+b" : "-b";
153     QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
154     emit putRawLine(serverEncode(banMsg));
155 }
156
157
158 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg)
159 {
160     Q_UNUSED(bufferInfo)
161
162     QString nick = msg.section(' ', 0, 0);
163     QString ctcpTag = msg.section(' ', 1, 1).toUpper();
164     if (ctcpTag.isEmpty())
165         return;
166
167     QString message = msg.section(' ', 2);
168     QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
169
170     if (ctcpTag == "PING") {
171         uint now = QDateTime::currentDateTime().toTime_t();
172         message = QString::number(now);
173     }
174
175     // FIXME make this a proper event
176     coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
177     emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
178 }
179
180
181 void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg)
182 {
183 #ifdef HAVE_QCA2
184     if (!bufferInfo.isValid())
185         return;
186
187     if (!Cipher::neededFeaturesAvailable())
188         return;
189
190     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
191
192     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty())
193         parms.prepend(bufferInfo.bufferName());
194
195     if (parms.isEmpty()) {
196         emit displayMsg(Message::Info, bufferInfo.bufferName(), "",
197             tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
198         return;
199     }
200
201     QString target = parms.at(0);
202
203     if (network()->cipherKey(target).isEmpty()) {
204         emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("No key has been set for %1.").arg(target));
205         return;
206     }
207
208     network()->setCipherKey(target, QByteArray());
209
210     if (network()->isChannelName(target) && network()->channels().contains(target)) {
211         qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(false);
212     }
213     else if (network()->nicks().contains(target)) {
214         qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(false);
215     }
216
217     emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been deleted.").arg(target));
218
219 #else
220     Q_UNUSED(msg)
221     emit displayMsg(Message::Error, bufferInfo.bufferName(), "", tr("Error: Setting an encryption key requires Quassel to have been built "
222                                                                     "with support for the Qt Cryptographic Architecture (QCA2) library. "
223                                                                     "Contact your distributor about a Quassel package with QCA2 "
224                                                                     "support, or rebuild Quassel with QCA2 present."));
225 #endif
226 }
227
228
229 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg)
230 {
231     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
232     QString m = "-"; for (int i = 0; i < nicks.count(); i++) m += 'o';
233     QStringList params;
234     params << bufferInfo.bufferName() << m << nicks;
235     emit putCmd("MODE", serverEncode(params));
236 }
237
238
239 void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &msg)
240 {
241     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
242     QString m = "-"; for (int i = 0; i < nicks.count(); i++) m += 'h';
243     QStringList params;
244     params << bufferInfo.bufferName() << m << nicks;
245     emit putCmd("MODE", serverEncode(params));
246 }
247
248
249 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg)
250 {
251     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
252     QString m = "-"; for (int i = 0; i < nicks.count(); i++) m += 'v';
253     QStringList params;
254     params << bufferInfo.bufferName() << m << nicks;
255     emit putCmd("MODE", serverEncode(params));
256 }
257
258
259 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg)
260 {
261     QStringList params;
262     params << msg << bufferInfo.bufferName();
263     emit putCmd("INVITE", serverEncode(params));
264 }
265
266
267 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg)
268 {
269     Q_UNUSED(bufferInfo);
270
271     // trim spaces before chans or keys
272     QString sane_msg = msg;
273     sane_msg.replace(QRegExp(", +"), ",");
274     QStringList params = sane_msg.trimmed().split(" ");
275
276     QStringList chans = params[0].split(",", QString::SkipEmptyParts);
277     QStringList keys;
278     if (params.count() > 1)
279         keys = params[1].split(",");
280
281     int i;
282     for (i = 0; i < chans.count(); i++) {
283         if (!network()->isChannelName(chans[i]))
284             chans[i].prepend('#');
285
286         if (i < keys.count()) {
287             network()->addChannelKey(chans[i], keys[i]);
288         }
289         else {
290             network()->removeChannelKey(chans[i]);
291         }
292     }
293
294     static const char *cmd = "JOIN";
295     i = 0;
296     QStringList joinChans, joinKeys;
297     int slicesize = chans.count();
298     QList<QByteArray> encodedParams;
299
300     // go through all to-be-joined channels and (re)build the join list
301     while (i < chans.count()) {
302         joinChans.append(chans.at(i));
303         if (i < keys.count())
304             joinKeys.append(keys.at(i));
305
306         // if the channel list we built so far either contains all requested channels or exceeds
307         // the desired amount of channels in this slice, try to send what we have so far
308         if (++i == chans.count() || joinChans.count() >= slicesize) {
309             params.clear();
310             params.append(joinChans.join(","));
311             params.append(joinKeys.join(","));
312             encodedParams = serverEncode(params);
313             // check if it fits in one command
314             if (lastParamOverrun(cmd, encodedParams) == 0) {
315                 emit putCmd(cmd, encodedParams);
316             }
317             else if (slicesize > 1) {
318                 // back to start of slice, try again with half the amount of channels
319                 i -= slicesize;
320                 slicesize /= 2;
321             }
322             joinChans.clear();
323             joinKeys.clear();
324         }
325     }
326 }
327
328
329 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg)
330 {
331     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
332     QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
333     if (reason.isEmpty())
334         reason = network()->identityPtr()->kickReason();
335
336     QList<QByteArray> params;
337     params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
338     emit putCmd("KICK", params);
339 }
340
341
342 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg)
343 {
344     Q_UNUSED(bufferInfo)
345     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
346     QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
347     QList<QByteArray> params;
348     params << serverEncode(nick) << serverEncode(pass);
349     emit putCmd("KILL", params);
350 }
351
352
353 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg)
354 {
355     Q_UNUSED(bufferInfo)
356     emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
357 }
358
359
360 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg)
361 {
362     if (bufferInfo.bufferName().isEmpty()) return;  // server buffer
363     // FIXME make this a proper event
364     coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", msg);
365     emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
366 }
367
368
369 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
370 {
371     Q_UNUSED(bufferInfo)
372
373     QStringList params = msg.split(' ', QString::SkipEmptyParts);
374     // 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
375     if (!params.isEmpty()) {
376         if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
377             params.prepend(bufferInfo.bufferName());
378         if (network()->isMyNick(params[0]) && params.count() == 2)
379             network()->updateIssuedModes(params[1]);
380         if (params[0] == "-reset" && params.count() == 1) {
381             // FIXME: give feedback to the user (I don't want to add new strings right now)
382             network()->resetPersistentModes();
383             return;
384         }
385     }
386
387     // TODO handle correct encoding for buffer modes (channelEncode())
388     emit putCmd("MODE", serverEncode(params));
389 }
390
391
392 // TODO: show privmsgs
393 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
394 {
395     Q_UNUSED(bufferInfo);
396     if (!msg.contains(' '))
397         return;
398
399     QString target = msg.section(' ', 0, 0);
400     QByteArray encMsg = userEncode(target, msg.section(' ', 1));
401
402 #ifdef HAVE_QCA2
403     putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
404 #else
405     putPrivmsg(serverEncode(target), encMsg);
406 #endif
407 }
408
409
410 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
411 {
412     Q_UNUSED(bufferInfo)
413     QString nick = msg.section(' ', 0, 0);
414     emit putCmd("NICK", serverEncode(nick));
415 }
416
417
418 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
419 {
420     QString bufferName = msg.section(' ', 0, 0);
421     QString payload = msg.section(' ', 1);
422     QList<QByteArray> params;
423     params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
424     emit putCmd("NOTICE", params);
425     emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
426 }
427
428
429 void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &msg)
430 {
431     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
432     QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'h';
433     QStringList params;
434     params << bufferInfo.bufferName() << m << nicks;
435     emit putCmd("MODE", serverEncode(params));
436 }
437
438
439 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg)
440 {
441     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
442     QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'o';
443     QStringList params;
444     params << bufferInfo.bufferName() << m << nicks;
445     emit putCmd("MODE", serverEncode(params));
446 }
447
448
449 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
450 {
451     Q_UNUSED(bufferInfo)
452     emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
453 }
454
455
456 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
457 {
458     QList<QByteArray> params;
459     QString partReason;
460
461     // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
462     QString channelName = msg.section(' ', 0, 0);
463     if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
464         channelName = bufferInfo.bufferName();
465         partReason = msg;
466     }
467     else {
468         partReason = msg.mid(channelName.length() + 1);
469     }
470
471     if (partReason.isEmpty())
472         partReason = network()->identityPtr()->partReason();
473
474     params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
475     emit putCmd("PART", params);
476 }
477
478
479 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
480 {
481     Q_UNUSED(bufferInfo)
482
483     QString param = msg;
484     if (param.isEmpty())
485         param = QTime::currentTime().toString("hh:mm:ss.zzz");
486
487     putCmd("PING", serverEncode(param));
488 }
489
490
491 // TODO: implement queries
492 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
493 {
494     Q_UNUSED(bufferInfo)
495     QString target = msg.section(' ', 0, 0);
496     QString message = msg.section(' ', 1);
497     if (message.isEmpty())
498         emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with %1").arg(target), network()->myNick(), Message::Self);
499     else
500         emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
501     handleMsg(bufferInfo, msg);
502 }
503
504
505 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
506 {
507     Q_UNUSED(bufferInfo)
508     network()->disconnectFromIrc(true, msg);
509 }
510
511
512 void CoreUserInputHandler::issueQuit(const QString &reason)
513 {
514     emit putCmd("QUIT", serverEncode(reason));
515 }
516
517
518 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
519 {
520     Q_UNUSED(bufferInfo)
521     emit putRawLine(serverEncode(msg));
522 }
523
524
525 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
526 {
527     if (bufferInfo.bufferName().isEmpty())
528         return;  // server buffer
529
530     QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
531 #ifdef HAVE_QCA2
532     putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
533 #else
534     putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
535 #endif
536     emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
537 }
538
539
540 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
541 {
542 #ifdef HAVE_QCA2
543     if (!bufferInfo.isValid())
544         return;
545
546     if (!Cipher::neededFeaturesAvailable())
547         return;
548
549     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
550
551     if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty())
552         parms.prepend(bufferInfo.bufferName());
553     else if (parms.count() != 2) {
554         emit displayMsg(Message::Info, bufferInfo.bufferName(),
555             tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
556                "/setkey <key> when in a channel or query buffer sets the key for it."));
557         return;
558     }
559
560     QString target = parms.at(0);
561     QByteArray key = parms.at(1).toLocal8Bit();
562
563     network()->setCipherKey(target, key);
564
565     if (network()->isChannelName(target) && network()->channels().contains(target))
566         qobject_cast<CoreIrcChannel *>(network()->ircChannel(target))->setEncrypted(true);
567     else if (network()->nicks().contains(target))
568         qobject_cast<CoreIrcUser *>(network()->ircUser(target))->setEncrypted(true);
569
570     emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 has been set.").arg(target));
571 #else
572     Q_UNUSED(msg)
573     emit displayMsg(Message::Error, bufferInfo.bufferName(), tr("Error: Setting an encryption key requires Quassel to have been built "
574                                                                 "with support for the Qt Cryptographic Architecture (QCA) library. "
575                                                                 "Contact your distributor about a Quassel package with QCA "
576                                                                 "support, or rebuild Quassel with QCA present."));
577 #endif
578 }
579
580
581 void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
582 {
583 #ifdef HAVE_QCA2
584     if (!bufferInfo.isValid())
585         return;
586
587     if (!Cipher::neededFeaturesAvailable())
588         return;
589
590     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
591
592     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty())
593         parms.prepend(bufferInfo.bufferName());
594
595     if (parms.isEmpty()) {
596         emit displayMsg(Message::Info, bufferInfo.bufferName(), "",
597             tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a channel or query."));
598         return;
599     }
600
601     QString target = parms.at(0);
602     QByteArray key = network()->cipherKey(target);
603
604     if (key.isEmpty()) {
605         emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("No key has been set for %1.").arg(target));
606         return;
607     }
608
609     emit displayMsg(Message::Info, bufferInfo.bufferName(), tr("The key for %1 is %2").arg(target).arg(QString(key)));
610
611 #else
612     Q_UNUSED(msg)
613     emit displayMsg(Message::Error, bufferInfo.bufferName(), "", tr("Error: Setting an encryption key requires Quassel to have been built "
614                                                                     "with support for the Qt Cryptographic Architecture (QCA2) library. "
615                                                                     "Contact your distributor about a Quassel package with QCA2 "
616                                                                     "support, or rebuild Quassel with QCA2 present."));
617 #endif
618 }
619
620
621 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
622 {
623     if (bufferInfo.bufferName().isEmpty())
624         return;
625
626     QList<QByteArray> params;
627     params << serverEncode(bufferInfo.bufferName());
628
629     if (!msg.isEmpty()) {
630 #   ifdef HAVE_QCA2
631         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
632 #   else
633         params << channelEncode(bufferInfo.bufferName(), msg);
634 #   endif
635     }
636
637     emit putCmd("TOPIC", params);
638 }
639
640
641 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
642 {
643     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
644     QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
645     QStringList params;
646     params << bufferInfo.bufferName() << m << nicks;
647     emit putCmd("MODE", serverEncode(params));
648 }
649
650
651 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
652 {
653     int splitPos = msg.indexOf(';');
654     if (splitPos <= 0)
655         return;
656
657     bool ok;
658     int delay = msg.left(splitPos).trimmed().toInt(&ok);
659     if (!ok)
660         return;
661
662     delay *= 1000;
663
664     QString command = msg.mid(splitPos + 1).trimmed();
665     if (command.isEmpty())
666         return;
667
668     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
669 }
670
671
672 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
673 {
674     Q_UNUSED(bufferInfo)
675     emit putCmd("WHO", serverEncode(msg.split(' ')));
676 }
677
678
679 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
680 {
681     Q_UNUSED(bufferInfo)
682     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
683 }
684
685
686 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
687 {
688     Q_UNUSED(bufferInfo)
689     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
690 }
691
692
693 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
694 {
695     Q_UNUSED(bufferInfo);
696     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
697 }
698
699
700 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher)
701 {
702     // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,
703     // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted
704     // version is short enough...
705     // TODO: check out how the various possible encryption methods behave length-wise and make
706     //       this clean by predicting the length of the crypted msg.
707     //       For example, blowfish-ebc seems to create 8-char chunks.
708
709     static const char *cmd = "PRIVMSG";
710     static const char *splitter = " .,-";
711
712     int maxSplitPos = message.count();
713     int splitPos = maxSplitPos;
714     forever {
715         QByteArray crypted = message.left(splitPos);
716         bool isEncrypted = false;
717 #ifdef HAVE_QCA2
718         if (cipher && !message.isEmpty()) {
719             isEncrypted = cipher->encrypt(crypted);
720         }
721 #endif
722         int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted);
723         if (overrun) {
724             // In case this is not an encrypted msg, we can just cut off at the end
725             if (!isEncrypted)
726                 maxSplitPos = message.count() - overrun;
727
728             splitPos = -1;
729             for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {
730                 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
731             }
732             if (splitPos <= 0 || splitPos > maxSplitPos)
733                 splitPos = maxSplitPos;
734
735             maxSplitPos = splitPos - 1;
736             if (maxSplitPos <= 0) { // this should never happen, but who knows...
737                 qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data());
738                 return;
739             }
740             continue; // we never come back here for !encrypted!
741         }
742
743         // now we have found a valid splitpos (or didn't need to split to begin with)
744         putCmd(cmd, QList<QByteArray>() << target << crypted);
745         if (splitPos < message.count())
746             putPrivmsg(target, message.mid(splitPos), cipher);
747
748         return;
749     }
750 }
751
752
753 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
754 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params)
755 {
756     // the server will pass our message truncated to 512 bytes including CRLF with the following format:
757     // ":prefix COMMAND param0 param1 :lastparam"
758     // where prefix = "nickname!user@host"
759     // that means that the last message can be as long as:
760     // 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)
761     IrcUser *me = network()->me();
762     int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
763
764     if (me)
765         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
766
767     if (!params.isEmpty()) {
768         for (int i = 0; i < params.count() - 1; i++) {
769             maxLen -= (params[i].count() + 1);
770         }
771         maxLen -= 2; // " :" last param separator;
772
773         if (params.last().count() > maxLen) {
774             return params.last().count() - maxLen;
775         }
776         else {
777             return 0;
778         }
779     }
780     else {
781         return 0;
782     }
783 }
784
785
786 #ifdef HAVE_QCA2
787 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
788 {
789     if (didEncrypt)
790         *didEncrypt = false;
791
792     if (message_.isEmpty())
793         return message_;
794
795     if (!Cipher::neededFeaturesAvailable())
796         return message_;
797
798     Cipher *cipher = network()->cipher(target);
799     if (!cipher)
800         return message_;
801
802     QByteArray message = message_;
803     bool result = cipher->encrypt(message);
804     if (didEncrypt)
805         *didEncrypt = result;
806
807     return message;
808 }
809
810
811 #endif
812
813 void CoreUserInputHandler::timerEvent(QTimerEvent *event)
814 {
815     if (!_delayedCommands.contains(event->timerId())) {
816         QObject::timerEvent(event);
817         return;
818     }
819     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
820     QString rawCommand = _delayedCommands[event->timerId()].command;
821     _delayedCommands.remove(event->timerId());
822     event->accept();
823
824     // the stored command might be the result of an alias expansion, so we need to split it up again
825     QStringList commands = rawCommand.split(QRegExp("; ?"));
826     foreach(QString command, commands) {
827         handleUserInput(bufferInfo, command);
828     }
829 }