ssl: Use QSslSocket directly to avoid redundant qobject_casts
[quassel.git] / src / common / aliasmanager.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 "aliasmanager.h"
22
23 #include <QDebug>
24 #include <QStringList>
25
26 #include "network.h"
27
28 int AliasManager::indexOf(const QString& name) const
29 {
30     for (int i = 0; i < _aliases.count(); i++) {
31         if (_aliases[i].name == name)
32             return i;
33     }
34     return -1;
35 }
36
37 QVariantMap AliasManager::initAliases() const
38 {
39     QVariantMap aliases;
40     QStringList names;
41     QStringList expansions;
42
43     for (int i = 0; i < _aliases.count(); i++) {
44         names << _aliases[i].name;
45         expansions << _aliases[i].expansion;
46     }
47
48     aliases["names"] = names;
49     aliases["expansions"] = expansions;
50     return aliases;
51 }
52
53 void AliasManager::initSetAliases(const QVariantMap& aliases)
54 {
55     QStringList names = aliases["names"].toStringList();
56     QStringList expansions = aliases["expansions"].toStringList();
57
58     if (names.count() != expansions.count()) {
59         qWarning() << "AliasesManager::initSetAliases: received" << names.count() << "alias names but only" << expansions.count()
60                    << "expansions!";
61         return;
62     }
63
64     _aliases.clear();
65     for (int i = 0; i < names.count(); i++) {
66         _aliases << Alias(names[i], expansions[i]);
67     }
68 }
69
70 void AliasManager::addAlias(const QString& name, const QString& expansion)
71 {
72     if (contains(name)) {
73         return;
74     }
75
76     _aliases << Alias(name, expansion);
77
78     SYNC(ARG(name), ARG(expansion))
79 }
80
81 AliasManager::AliasList AliasManager::defaults()
82 {
83     AliasList aliases;
84     aliases << Alias("j", "/join $0") << Alias("ns", "/msg nickserv $0") << Alias("nickserv", "/msg nickserv $0")
85             << Alias("cs", "/msg chanserv $0") << Alias("chanserv", "/msg chanserv $0") << Alias("hs", "/msg hostserv $0")
86             << Alias("hostserv", "/msg hostserv $0") << Alias("wii", "/whois $0 $0") << Alias("back", "/quote away");
87
88 #ifdef Q_OS_LINUX
89     // let's add aliases for scripts that only run on linux
90     aliases << Alias("inxi", "/exec inxi $0") << Alias("sysinfo", "/exec inxi -d");
91 #endif
92
93     return aliases;
94 }
95
96 AliasManager::CommandList AliasManager::processInput(const BufferInfo& info, const QString& msg)
97 {
98     CommandList result;
99     processInput(info, msg, result);
100     return result;
101 }
102
103 void AliasManager::processInput(const BufferInfo& info, const QString& msg_, CommandList& list)
104 {
105     QString msg = msg_;
106
107     // leading slashes indicate there's a command to call unless there is another one in the first section (like a path /proc/cpuinfo)
108     // For those habitally tied to irssi, "/ " also makes the rest of the line a literal message
109     int secondSlashPos = msg.indexOf('/', 1);
110     int firstSpacePos = msg.indexOf(' ');
111     if (!msg.startsWith('/') || firstSpacePos == 1 || (secondSlashPos != -1 && (secondSlashPos < firstSpacePos || firstSpacePos == -1))) {
112         if (msg.startsWith("//"))
113             msg.remove(0, 1);  // "//asdf" is transformed to "/asdf"
114         else if (msg.startsWith("/ "))
115             msg.remove(0, 2);  // "/ /asdf" is transformed to "/asdf"
116         msg.prepend("/SAY ");  // make sure we only send proper commands to the core
117     }
118     else {
119         // check for aliases
120         QString cmd = msg.section(' ', 0, 0).remove(0, 1).toUpper();
121         for (int i = 0; i < count(); i++) {
122             if ((*this)[i].name.toUpper() == cmd) {
123                 expand((*this)[i].expansion, info, msg.section(' ', 1), list);
124                 return;
125             }
126         }
127     }
128
129     list.append(qMakePair(info, msg));
130 }
131
132 void AliasManager::expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& list)
133 {
134     const Network* net = network(bufferInfo.networkId());
135     if (!net) {
136         // FIXME send error as soon as we have a method for that!
137         return;
138     }
139
140     QRegExp paramRangeR(R"(\$(\d+)\.\.(\d*))");
141     QStringList commands = alias.split(QRegExp("; ?"));
142     QStringList params = msg.split(' ');
143     QStringList expandedCommands;
144     for (int i = 0; i < commands.count(); i++) {
145         QString command = commands[i];
146
147         // replace ranges like $1..3
148         if (!params.isEmpty()) {
149             int pos;
150             while ((pos = paramRangeR.indexIn(command)) != -1) {
151                 int start = paramRangeR.cap(1).toInt();
152                 bool ok;
153                 int end = paramRangeR.cap(2).toInt(&ok);
154                 if (!ok) {
155                     end = params.count();
156                 }
157                 if (end < start)
158                     command = command.replace(pos, paramRangeR.matchedLength(), QString());
159                 else {
160                     command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
161                 }
162             }
163         }
164
165         for (int j = params.count(); j > 0; j--) {
166             // Find the referenced IRC user...
167             IrcUser* ircUser = net->ircUser(params[j - 1]);
168             // ...and replace components, using short-circuit evaluation as ircUser might be null
169
170             // Account, or "*" if blank/nonexistent/logged out
171             command = command.replace(QString("$%1:account").arg(j),
172                                       (ircUser && !ircUser->account().isEmpty()) ? ircUser->account() : QString("*"));
173
174             // Hostname, or "*" if blank/nonexistent
175             command = command.replace(QString("$%1:hostname").arg(j),
176                                       (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*"));
177
178             // Identd
179             // Ident if verified, or "*" if blank/unknown/unverified (prefixed with "~")
180             //
181             // Most IRC daemons have the option to prefix an ident with "~" if it could not be
182             // verified via an identity daemon such as oidentd.  In these cases, it can be handy to
183             // have a way to ban via ident if verified, or all idents if not verified.  If the
184             // server does not verify idents, it usually won't add "~".
185             //
186             // Identd must be replaced before ident to avoid being treated as "$i:ident" + "d"
187             command = command.replace(QString("$%1:identd").arg(j),
188                                       (ircUser && !ircUser->user().isEmpty() && !ircUser->user().startsWith("~")) ? ircUser->user()
189                                                                                                                   : QString("*"));
190
191             // Ident, or "*" if blank/nonexistent
192             command = command.replace(QString("$%1:ident").arg(j), (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*"));
193
194             // Nickname
195             // Must be replaced last to avoid interferring with more specific aliases
196             command = command.replace(QString("$%1").arg(j), params[j - 1]);
197         }
198         command = command.replace("$0", msg);
199         command = command.replace("$channelname", bufferInfo.bufferName());  // legacy
200         command = command.replace("$channel", bufferInfo.bufferName());
201         command = command.replace("$currentnick", net->myNick());  // legacy
202         command = command.replace("$nick", net->myNick());
203         expandedCommands << command;
204     }
205
206     while (!expandedCommands.isEmpty()) {
207         QString command;
208         if (expandedCommands[0].trimmed().toLower().startsWith("/wait ")) {
209             command = expandedCommands.join("; ");
210             expandedCommands.clear();
211         }
212         else {
213             command = expandedCommands.takeFirst();
214         }
215         list.append(qMakePair(bufferInfo, command));
216     }
217 }