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