Implement sender prefix storage in the database
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "coresession.h"
22
23 #include <QtScript>
24
25 #include "core.h"
26 #include "coreuserinputhandler.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coredccconfig.h"
31 #include "coreeventmanager.h"
32 #include "coreidentity.h"
33 #include "coreignorelistmanager.h"
34 #include "coreirclisthelper.h"
35 #include "corenetwork.h"
36 #include "corenetworkconfig.h"
37 #include "coresessioneventprocessor.h"
38 #include "coretransfermanager.h"
39 #include "coreusersettings.h"
40 #include "ctcpparser.h"
41 #include "eventstringifier.h"
42 #include "internalpeer.h"
43 #include "ircchannel.h"
44 #include "ircparser.h"
45 #include "ircuser.h"
46 #include "logger.h"
47 #include "messageevent.h"
48 #include "remotepeer.h"
49 #include "storage.h"
50 #include "util.h"
51
52
53 class ProcessMessagesEvent : public QEvent
54 {
55 public:
56     ProcessMessagesEvent() : QEvent(QEvent::User) {}
57 };
58
59
60 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
61     : QObject(parent),
62     _user(uid),
63     _signalProxy(new SignalProxy(SignalProxy::Server, this)),
64     _aliasManager(this),
65     _bufferSyncer(new CoreBufferSyncer(this)),
66     _backlogManager(new CoreBacklogManager(this)),
67     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
68     _dccConfig(new CoreDccConfig(this)),
69     _ircListHelper(new CoreIrcListHelper(this)),
70     _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
71     _coreInfo(this),
72     _transferManager(new CoreTransferManager(this)),
73     _eventManager(new CoreEventManager(this)),
74     _eventStringifier(new EventStringifier(this)),
75     _sessionEventProcessor(new CoreSessionEventProcessor(this)),
76     _ctcpParser(new CtcpParser(this)),
77     _ircParser(new IrcParser(this)),
78     scriptEngine(new QScriptEngine(this)),
79     _processMessages(false),
80     _ignoreListManager(this)
81 {
82     SignalProxy *p = signalProxy();
83     p->setHeartBeatInterval(30);
84     p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
85
86     connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
87
88     connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
89     connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
90
91     p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
92     p->attachSignal(this, SIGNAL(displayMsg(Message)));
93     p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
94
95     p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
96     p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
97     p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
98     p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
99
100     p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
101     p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
102     p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
103     p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
104
105     p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
106     p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
107
108     loadSettings();
109     initScriptEngine();
110
111     eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
112     eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
113     eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
114     eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
115     eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
116     // some events need to be handled after msg generation
117     eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
118     eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
119
120     // periodically save our session state
121     connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
122
123     p->synchronize(_bufferSyncer);
124     p->synchronize(&aliasManager());
125     p->synchronize(_backlogManager);
126     p->synchronize(dccConfig());
127     p->synchronize(ircListHelper());
128     p->synchronize(networkConfig());
129     p->synchronize(&_coreInfo);
130     p->synchronize(&_ignoreListManager);
131     p->synchronize(transferManager());
132     // Restore session state
133     if (restoreState)
134         restoreSessionState();
135
136     emit initialized();
137 }
138
139
140 CoreSession::~CoreSession()
141 {
142     saveSessionState();
143
144     /* Why partially duplicate CoreNetwork destructor?  When each CoreNetwork quits in the
145      * destructor, disconnections are processed in sequence for each object.  For many IRC servers
146      * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
147      *
148      * Here, CoreSession first calls disconnect on all networks, letting them all start
149      * disconnecting before beginning to sequentially wait for each network.  Ideally, after the
150      * first network is disconnected, the other networks will have already closed.  Worst-case may
151      * still wait [msecs wait time * num. of networks], but the risk should be much lower.
152      *
153      * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
154      * outside of deleting the whole CoreSession.
155      *
156      * If this proves to be problematic in the future, there's an alternative Qt signal-based system
157      * implemented in another pull request that guarentees a maximum amount of time to disconnect,
158      * but at the cost of more complex code.
159      *
160      * See https://github.com/quassel/quassel/pull/203
161      */
162
163     foreach(CoreNetwork *net, _networks.values()) {
164         // Request each network properly disconnect, but don't count as user-requested disconnect
165         if (net->socketConnected()) {
166             // Only try if the socket's fully connected (not initializing or disconnecting).
167             // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
168             // shown even if other messages are queued.
169             net->disconnectFromIrc(false, QString(), false, true);
170         }
171     }
172
173     // Process the putCmd events that trigger the quit.  Without this, shutting down the core
174     // results in abrubtly closing the socket rather than sending the QUIT as expected.
175     QCoreApplication::processEvents();
176
177     foreach(CoreNetwork *net, _networks.values()) {
178         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
179         if (!net->forceDisconnect()) {
180             qWarning() << "Timed out quitting network" << net->networkName() <<
181                           "(user ID " << net->userId() << ")";
182         }
183         // Delete the network now that it's closed
184         delete net;
185     }
186 }
187
188
189 CoreNetwork *CoreSession::network(NetworkId id) const
190 {
191     if (_networks.contains(id)) return _networks[id];
192     return 0;
193 }
194
195
196 CoreIdentity *CoreSession::identity(IdentityId id) const
197 {
198     if (_identities.contains(id)) return _identities[id];
199     return 0;
200 }
201
202
203 void CoreSession::loadSettings()
204 {
205     CoreUserSettings s(user());
206
207     // migrate to db
208     QList<IdentityId> ids = s.identityIds();
209     QList<NetworkInfo> networkInfos = Core::networks(user());
210     foreach(IdentityId id, ids) {
211         CoreIdentity identity(s.identity(id));
212         IdentityId newId = Core::createIdentity(user(), identity);
213         QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
214         while (networkIter != networkInfos.end()) {
215             if (networkIter->identity == id) {
216                 networkIter->identity = newId;
217                 Core::updateNetwork(user(), *networkIter);
218                 networkIter = networkInfos.erase(networkIter);
219             }
220             else {
221                 ++networkIter;
222             }
223         }
224         s.removeIdentity(id);
225     }
226     // end of migration
227
228     foreach(CoreIdentity identity, Core::identities(user())) {
229         createIdentity(identity);
230     }
231
232     foreach(NetworkInfo info, Core::networks(user())) {
233         createNetwork(info);
234     }
235 }
236
237
238 void CoreSession::saveSessionState() const
239 {
240     _bufferSyncer->storeDirtyIds();
241     _bufferViewManager->saveBufferViews();
242     _networkConfig->save();
243 }
244
245
246 void CoreSession::restoreSessionState()
247 {
248     QList<NetworkId> nets = Core::connectedNetworks(user());
249     CoreNetwork *net = 0;
250     foreach(NetworkId id, nets) {
251         net = network(id);
252         Q_ASSERT(net);
253         net->connectToIrc();
254     }
255 }
256
257
258 void CoreSession::addClient(RemotePeer *peer)
259 {
260     peer->dispatch(sessionState());
261     signalProxy()->addPeer(peer);
262 }
263
264
265 void CoreSession::addClient(InternalPeer *peer)
266 {
267     signalProxy()->addPeer(peer);
268     emit sessionState(sessionState());
269 }
270
271
272 void CoreSession::removeClient(Peer *peer)
273 {
274     RemotePeer *p = qobject_cast<RemotePeer *>(peer);
275     if (p)
276         quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
277 }
278
279
280 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
281 {
282     return Core::persistentChannels(user(), id);
283 }
284
285
286 // FIXME switch to BufferId
287 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
288 {
289     CoreNetwork *net = network(bufinfo.networkId());
290     if (net) {
291         net->userInput(bufinfo, msg);
292     }
293     else {
294         qWarning() << "Trying to send to unconnected network:" << msg;
295     }
296 }
297
298
299 // ALL messages coming pass through these functions before going to the GUI.
300 // So this is the perfect place for storing the backlog and log stuff.
301 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
302     const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
303 {
304     // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
305     // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
306     // KDE's notifications), hence we remove those just to be safe.
307     QString text = text_;
308     text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
309     RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
310
311     // check for HardStrictness ignore
312     CoreNetwork *currentNetwork = network(networkId);
313     QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
314     if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
315         return;
316
317     _messageQueue << rawMsg;
318     if (!_processMessages) {
319         _processMessages = true;
320         QCoreApplication::postEvent(this, new ProcessMessagesEvent());
321     }
322 }
323
324
325 void CoreSession::recvStatusMsgFromServer(QString msg)
326 {
327     CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
328     Q_ASSERT(net);
329     emit displayStatusMsg(net->networkName(), msg);
330 }
331
332
333 void CoreSession::processMessageEvent(MessageEvent *event)
334 {
335     recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
336         event->target().isNull() ? "" : event->target(),
337         event->text().isNull() ? "" : event->text(),
338         event->sender().isNull() ? "" : event->sender(),
339         event->msgFlags());
340 }
341
342
343 QList<BufferInfo> CoreSession::buffers() const
344 {
345     return Core::requestBuffers(user());
346 }
347
348
349 void CoreSession::customEvent(QEvent *event)
350 {
351     if (event->type() != QEvent::User)
352         return;
353
354     processMessages();
355     event->accept();
356 }
357
358
359 void CoreSession::processMessages()
360 {
361     if (_messageQueue.count() == 1) {
362         const RawMessage &rawMsg = _messageQueue.first();
363         bool createBuffer = !(rawMsg.flags & Message::Redirected);
364         BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
365         if (!bufferInfo.isValid()) {
366             Q_ASSERT(!createBuffer);
367             bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
368         }
369         Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
370                     senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
371         if(Core::storeMessage(msg))
372             emit displayMsg(msg);
373     }
374     else {
375         QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
376         MessageList messages;
377         QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
378         BufferInfo bufferInfo;
379         for (int i = 0; i < _messageQueue.count(); i++) {
380             const RawMessage &rawMsg = _messageQueue.at(i);
381             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
382                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
383             }
384             else {
385                 bool createBuffer = !(rawMsg.flags & Message::Redirected);
386                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
387                 if (!bufferInfo.isValid()) {
388                     Q_ASSERT(!createBuffer);
389                     redirectedMessages << rawMsg;
390                     continue;
391                 }
392                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
393             }
394             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
395                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
396             messages << msg;
397         }
398
399         // recheck if there exists a buffer to store a redirected message in
400         for (int i = 0; i < redirectedMessages.count(); i++) {
401             const RawMessage &rawMsg = redirectedMessages.at(i);
402             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
403                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
404             }
405             else {
406                 // no luck -> we store them in the StatusBuffer
407                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
408                 // add the StatusBuffer to the Cache in case there are more Messages for the original target
409                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
410             }
411             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
412                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
413             messages << msg;
414         }
415
416         if(Core::storeMessages(messages)) {
417             // FIXME: extend protocol to a displayMessages(MessageList)
418             for (int i = 0; i < messages.count(); i++) {
419                 emit displayMsg(messages[i]);
420             }
421         }
422     }
423     _processMessages = false;
424     _messageQueue.clear();
425 }
426
427 QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
428 {
429     CoreNetwork *currentNetwork = network(bufferInfo.networkId());
430     if (!currentNetwork) {
431         return "";
432     }
433
434     if (bufferInfo.type() != BufferInfo::ChannelBuffer) {
435         return "";
436     }
437
438     IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
439     if (!currentChannel) {
440         return "";
441     }
442
443     const QString modes = currentChannel->userModes(nickFromMask(sender).toLower());
444     return currentNetwork->modesToPrefixes(modes);
445 }
446
447 Protocol::SessionState CoreSession::sessionState() const
448 {
449     QVariantList bufferInfos;
450     QVariantList networkIds;
451     QVariantList identities;
452
453     foreach(const BufferInfo &id, buffers())
454         bufferInfos << QVariant::fromValue(id);
455     foreach(const NetworkId &id, _networks.keys())
456         networkIds << QVariant::fromValue(id);
457     foreach(const Identity *i, _identities.values())
458         identities << QVariant::fromValue(*i);
459
460     return Protocol::SessionState(identities, bufferInfos, networkIds);
461 }
462
463
464 void CoreSession::initScriptEngine()
465 {
466     signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
467     signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
468
469     // FIXME
470     //QScriptValue storage_ = scriptEngine->newQObject(storage);
471     //scriptEngine->globalObject().setProperty("storage", storage_);
472 }
473
474
475 void CoreSession::scriptRequest(QString script)
476 {
477     emit scriptResult(scriptEngine->evaluate(script).toString());
478 }
479
480
481 /*** Identity Handling ***/
482 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
483 {
484 #ifndef HAVE_SSL
485     Q_UNUSED(additional)
486 #endif
487
488     CoreIdentity coreIdentity(identity);
489 #ifdef HAVE_SSL
490     if (additional.contains("KeyPem"))
491         coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
492     if (additional.contains("CertPem"))
493         coreIdentity.setSslCert(additional["CertPem"].toByteArray());
494 #endif
495     qDebug() << Q_FUNC_INFO;
496     IdentityId id = Core::createIdentity(user(), coreIdentity);
497     if (!id.isValid())
498         return;
499     else
500         createIdentity(coreIdentity);
501 }
502
503
504 void CoreSession::createIdentity(const CoreIdentity &identity)
505 {
506     CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
507     _identities[identity.id()] = coreIdentity;
508     // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
509     coreIdentity->synchronize(signalProxy());
510     connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
511     emit identityCreated(*coreIdentity);
512 }
513
514
515 void CoreSession::updateIdentityBySender()
516 {
517     CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
518     if (!identity)
519         return;
520     Core::updateIdentity(user(), *identity);
521 }
522
523
524 void CoreSession::removeIdentity(IdentityId id)
525 {
526     CoreIdentity *identity = _identities.take(id);
527     if (identity) {
528         emit identityRemoved(id);
529         Core::removeIdentity(user(), id);
530         identity->deleteLater();
531     }
532 }
533
534
535 /*** Network Handling ***/
536
537 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
538 {
539     NetworkInfo info = info_;
540     int id;
541
542     if (!info.networkId.isValid())
543         Core::createNetwork(user(), info);
544
545     if (!info.networkId.isValid()) {
546         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
547         return;
548     }
549
550     id = info.networkId.toInt();
551     if (!_networks.contains(id)) {
552         // create persistent chans
553         QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
554         foreach(QString channel, persistentChans) {
555             if (!rx.exactMatch(channel)) {
556                 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
557                 continue;
558             }
559             Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
560             Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
561             if (!rx.cap(2).isEmpty())
562                 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
563         }
564
565         CoreNetwork *net = new CoreNetwork(id, this);
566         connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
567             SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
568         connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
569         connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
570
571         net->setNetworkInfo(info);
572         net->setProxy(signalProxy());
573         _networks[id] = net;
574         signalProxy()->synchronize(net);
575         emit networkCreated(id);
576     }
577     else {
578         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
579         _networks[info.networkId]->requestSetNetworkInfo(info);
580     }
581 }
582
583
584 void CoreSession::removeNetwork(NetworkId id)
585 {
586     // Make sure the network is disconnected!
587     CoreNetwork *net = network(id);
588     if (!net)
589         return;
590
591     if (net->connectionState() != Network::Disconnected) {
592         // make sure we no longer receive data from the tcp buffer
593         disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
594         disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
595         connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
596         net->disconnectFromIrc();
597     }
598     else {
599         destroyNetwork(id);
600     }
601 }
602
603
604 void CoreSession::destroyNetwork(NetworkId id)
605 {
606     QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
607     Network *net = _networks.take(id);
608     if (net && Core::removeNetwork(user(), id)) {
609         // make sure that all unprocessed RawMessages from this network are removed
610         QList<RawMessage>::iterator messageIter = _messageQueue.begin();
611         while (messageIter != _messageQueue.end()) {
612             if (messageIter->networkId == id) {
613                 messageIter = _messageQueue.erase(messageIter);
614             }
615             else {
616                 ++messageIter;
617             }
618         }
619         // remove buffers from syncer
620         foreach(BufferId bufferId, removedBuffers) {
621             _bufferSyncer->removeBuffer(bufferId);
622         }
623         emit networkRemoved(id);
624         net->deleteLater();
625     }
626 }
627
628
629 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
630 {
631     BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
632     if (bufferInfo.isValid()) {
633         _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
634     }
635 }
636
637
638 void CoreSession::clientsConnected()
639 {
640     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
641     Identity *identity = 0;
642     CoreNetwork *net = 0;
643     IrcUser *me = 0;
644     while (netIter != _networks.end()) {
645         net = *netIter;
646         ++netIter;
647
648         if (!net->isConnected())
649             continue;
650         identity = net->identityPtr();
651         if (!identity)
652             continue;
653         me = net->me();
654         if (!me)
655             continue;
656
657         if (identity->detachAwayEnabled() && me->isAway()) {
658             net->userInputHandler()->handleAway(BufferInfo(), QString());
659         }
660     }
661 }
662
663
664 void CoreSession::clientsDisconnected()
665 {
666     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
667     Identity *identity = 0;
668     CoreNetwork *net = 0;
669     IrcUser *me = 0;
670     QString awayReason;
671     while (netIter != _networks.end()) {
672         net = *netIter;
673         ++netIter;
674
675         if (!net->isConnected())
676             continue;
677
678         identity = net->identityPtr();
679         if (!identity)
680             continue;
681         me = net->me();
682         if (!me)
683             continue;
684
685         if (identity->detachAwayEnabled() && !me->isAway()) {
686             if (!identity->detachAwayReason().isEmpty())
687                 awayReason = identity->detachAwayReason();
688             net->setAutoAwayActive(true);
689             // Allow handleAway() to format the current date/time in the string.
690             net->userInputHandler()->handleAway(BufferInfo(), awayReason);
691         }
692     }
693 }
694
695
696 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
697 {
698     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
699     CoreNetwork *net = 0;
700     while (netIter != _networks.end()) {
701         net = *netIter;
702         ++netIter;
703
704         if (!net->isConnected())
705             continue;
706
707         net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
708     }
709 }
710
711 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
712 {
713     bool success = false;
714     UserId uid = Core::validateUser(userName, oldPassword);
715     if (uid.isValid() && uid == user())
716         success = Core::changeUserPassword(uid, newPassword);
717
718     emit passwordChanged(peer, success);
719 }