a4a9d648b6e3f5f376df615440ba857da14e87d2
[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", "/quote nickserv $0") << Alias("nickserv", "/quote nickserv $0")
85             << Alias("cs", "/quote chanserv $0") << Alias("chanserv", "/quote chanserv $0") << Alias("hs", "/quote hostserv $0")
86             << Alias("hostserv", "/quote hostserv $0") << Alias("wii", "/whois $0 $0") << Alias("back", "/quote away")
87             << Alias("raw", "/quote $0");
88
89 #ifdef Q_OS_LINUX
90     // let's add aliases for scripts that only run on linux
91     aliases << Alias("inxi", "/exec inxi $0") << Alias("sysinfo", "/exec inxi -d");
92 #endif
93
94     return aliases;
95 }
96
97 AliasManager::CommandList AliasManager::processInput(const BufferInfo& info, const QString& msg)
98 {
99     CommandList result;
100     processInput(info, msg, result);
101     return result;
102 }
103
104 void AliasManager::processInput(const BufferInfo& info, const QString& msg_, CommandList& list)
105 {
106     QString msg = msg_;
107
108     // leading slashes indicate there's a command to call unless there is another one in the first section (like a path /proc/cpuinfo)
109     // For those habitally tied to irssi, "/ " also makes the rest of the line a literal message
110     int secondSlashPos = msg.indexOf('/', 1);
111     int firstSpacePos = msg.indexOf(' ');
112     if (!msg.startsWith('/') || firstSpacePos == 1 || (secondSlashPos != -1 && (secondSlashPos < firstSpacePos || firstSpacePos == -1))) {
113         if (msg.startsWith("//"))
114             msg.remove(0, 1);  // "//asdf" is transformed to "/asdf"
115         else if (msg.startsWith("/ "))
116             msg.remove(0, 2);  // "/ /asdf" is transformed to "/asdf"
117         msg.prepend("/SAY ");  // make sure we only send proper commands to the core
118     }
119     else {
120         // check for aliases
121         QString cmd = msg.section(' ', 0, 0).remove(0, 1).toUpper();
122         for (int i = 0; i < count(); i++) {
123             if ((*this)[i].name.toUpper() == cmd) {
124                 expand((*this)[i].expansion, info, msg.section(' ', 1), list);
125                 return;
126             }
127         }
128     }
129
130     list.append(qMakePair(info, msg));
131 }
132
133 void AliasManager::expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& list)
134 {
135     const Network* net = network(bufferInfo.networkId());
136     if (!net) {
137         // FIXME send error as soon as we have a method for that!
138         return;
139     }
140
141     QRegExp paramRangeR(R"(\$(\d+)\.\.(\d*))");
142     QStringList commands = alias.split(QRegExp("; ?"));
143     QStringList params = msg.split(' ');
144     QStringList expandedCommands;
145     for (int i = 0; i < commands.count(); i++) {
146         QString command = commands[i];
147
148         // replace ranges like $1..3
149         if (!params.isEmpty()) {
150             int pos;
151             while ((pos = paramRangeR.indexIn(command)) != -1) {
152                 int start = paramRangeR.cap(1).toInt();
153                 bool ok;
154                 int end = paramRangeR.cap(2).toInt(&ok);
155                 if (!ok) {
156                     end = params.count();
157                 }
158                 if (end < start)
159                     command = command.replace(pos, paramRangeR.matchedLength(), QString());
160                 else {
161                     command = command.replace(pos, paramRangeR.matchedLength(), QStringList(params.mid(start - 1, end - start + 1)).join(" "));
162                 }
163             }
164         }
165
166         for (int j = params.count(); j > 0; j--) {
167             // Find the referenced IRC user...
168             IrcUser* ircUser = net->ircUser(params[j - 1]);
169             // ...and replace components, using short-circuit evaluation as ircUser might be null
170
171             // Account, or "*" if blank/nonexistent/logged out
172             command = command.replace(QString("$%1:account").arg(j),
173                                       (ircUser && !ircUser->account().isEmpty()) ? ircUser->account() : QString("*"));
174
175             // Hostname, or "*" if blank/nonexistent
176             command = command.replace(QString("$%1:hostname").arg(j),
177                                       (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*"));
178
179             // Identd
180             // Ident if verified, or "*" if blank/unknown/unverified (prefixed with "~")
181             //
182             // Most IRC daemons have the option to prefix an ident with "~" if it could not be
183             // verified via an identity daemon such as oidentd.  In these cases, it can be handy to
184             // have a way to ban via ident if verified, or all idents if not verified.  If the
185             // server does not verify idents, it usually won't add "~".
186             //
187             // Identd must be replaced before ident to avoid being treated as "$i:ident" + "d"
188             command = command.replace(QString("$%1:identd").arg(j),
189                                       (ircUser && !ircUser->user().isEmpty() && !ircUser->user().startsWith("~")) ? ircUser->user()
190                                                                                                                   : QString("*"));
191
192             // Ident, or "*" if blank/nonexistent
193             command = command.replace(QString("$%1:ident").arg(j), (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*"));
194
195             // Nickname
196             // Must be replaced last to avoid interferring with more specific aliases
197             command = command.replace(QString("$%1").arg(j), params[j - 1]);
198         }
199         command = command.replace("$0", msg);
200         command = command.replace("$channelname", bufferInfo.bufferName());  // legacy
201         command = command.replace("$channel", bufferInfo.bufferName());
202         command = command.replace("$currentnick", net->myNick());  // legacy
203         command = command.replace("$nick", net->myNick());
204         expandedCommands << command;
205     }
206
207     while (!expandedCommands.isEmpty()) {
208         QString command;
209         if (expandedCommands[0].trimmed().toLower().startsWith("/wait ")) {
210             command = expandedCommands.join("; ");
211             expandedCommands.clear();
212         }
213         else {
214             command = expandedCommands.takeFirst();
215         }
216         list.append(qMakePair(bufferInfo, command));
217     }
218 }