tests: Convert ExpressionMatchTests into a GTest-based test case
[quassel.git] / src / common / util.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 "util.h"
22
23 #include <algorithm>
24 #include <array>
25 #include <utility>
26
27 #include <QCoreApplication>
28 #include <QDateTime>
29 #include <QDebug>
30 #include <QTextCodec>
31 #include <QVector>
32
33 #include "quassel.h"
34
35 // MIBenum values from http://www.iana.org/assignments/character-sets/character-sets.xml#table-character-sets-1
36 static QList<int> utf8DetectionBlacklist = QList<int>()
37     << 39 /* ISO-2022-JP */;
38
39 QString nickFromMask(const QString &mask)
40 {
41     return mask.left(mask.indexOf('!'));
42 }
43
44
45 QString userFromMask(const QString &mask)
46 {
47     const int offset = mask.indexOf('!') + 1;
48     if (offset <= 0)
49         return {};
50     const int length = mask.indexOf('@', offset) - offset;
51     return mask.mid(offset, length >= 0 ? length : -1);
52 }
53
54
55 QString hostFromMask(const QString &mask)
56 {
57     const int excl = mask.indexOf('!');
58     if (excl < 0)
59         return {};
60     const int offset = mask.indexOf('@', excl + 1) + 1;
61     return offset > 0 && offset < mask.size() ? mask.mid(offset) : QString{};
62 }
63
64
65 bool isChannelName(const QString &str)
66 {
67     if (str.isEmpty())
68         return false;
69     static constexpr std::array<quint8, 4> prefixes{{'#', '&', '!', '+'}};
70     return std::any_of(prefixes.cbegin(), prefixes.cend(), [&str](quint8 c) { return c == str[0]; });
71 }
72
73
74 QString stripFormatCodes(QString message)
75 {
76     static QRegExp regEx{"\x03(\\d\\d?(,\\d\\d?)?)?|\x04([\\da-fA-F]{6}(,[\\da-fA-F]{6})?)?|[\x02\x0f\x11\x12\x16\x1d\x1e\x1f]"};
77     return message.remove(regEx);
78 }
79
80
81 QString stripAcceleratorMarkers(const QString &label_)
82 {
83     QString label = label_;
84     int p = 0;
85     forever {
86         p = label.indexOf('&', p);
87         if (p < 0 || p + 1 >= label.length())
88             break;
89
90         if (label.at(p + 1).isLetterOrNumber() || label.at(p + 1) == '&')
91             label.remove(p, 1);
92
93         ++p;
94     }
95     return label;
96 }
97
98
99 QString decodeString(const QByteArray &input, QTextCodec *codec)
100 {
101     if (codec && utf8DetectionBlacklist.contains(codec->mibEnum()))
102         return codec->toUnicode(input);
103
104     // First, we check if it's utf8. It is very improbable to encounter a string that looks like
105     // valid utf8, but in fact is not. This means that if the input string passes as valid utf8, it
106     // is safe to assume that it is.
107     // Q_ASSERT(sizeof(const char) == sizeof(quint8));  // In God we trust...
108     bool isUtf8 = true;
109     int cnt = 0;
110     for (uchar c : input) {
111         if (cnt) {
112             // We check a part of a multibyte char. These need to be of the form 10yyyyyy.
113             if ((c & 0xc0) != 0x80) { isUtf8 = false; break; }
114             cnt--;
115             continue;
116         }
117         if ((c & 0x80) == 0x00) continue;  // 7 bit is always ok
118         if ((c & 0xf8) == 0xf0) { cnt = 3; continue; } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
119         if ((c & 0xf0) == 0xe0) { cnt = 2; continue; } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
120         if ((c & 0xe0) == 0xc0) { cnt = 1; continue; } // 2-byte char 110xxxxx 10yyyyyy
121         isUtf8 = false; break; // 8 bit char, but not utf8!
122     }
123     if (isUtf8 && cnt == 0) {
124         QString s = QString::fromUtf8(input);
125         //qDebug() << "Detected utf8:" << s;
126         return s;
127     }
128     //QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1());
129     if (!codec) return QString::fromLatin1(input);
130     return codec->toUnicode(input);
131 }
132
133
134 uint editingDistance(const QString &s1, const QString &s2)
135 {
136     uint n = s1.size()+1;
137     uint m = s2.size()+1;
138     QVector<QVector<uint> > matrix(n, QVector<uint>(m, 0));
139
140     for (uint i = 0; i < n; i++)
141         matrix[i][0] = i;
142
143     for (uint i = 0; i < m; i++)
144         matrix[0][i] = i;
145
146     uint min;
147     for (uint i = 1; i < n; i++) {
148         for (uint j = 1; j < m; j++) {
149             uint deleteChar = matrix[i-1][j] + 1;
150             uint insertChar = matrix[i][j-1] + 1;
151
152             if (deleteChar < insertChar)
153                 min = deleteChar;
154             else
155                 min = insertChar;
156
157             if (s1[i-1] == s2[j-1]) {
158                 uint inheritChar = matrix[i-1][j-1];
159                 if (inheritChar < min)
160                     min = inheritChar;
161             }
162
163             matrix[i][j] = min;
164         }
165     }
166     return matrix[n-1][m-1];
167 }
168
169
170 QString secondsToString(int timeInSeconds)
171 {
172     static QVector<std::pair<int, QString>> timeUnit {
173         std::make_pair(365*24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "year")),
174         std::make_pair(24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "day")),
175         std::make_pair(60*60, QCoreApplication::translate("Quassel::secondsToString()", "h")),
176         std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")),
177         std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec"))
178     };
179
180     if (timeInSeconds != 0) {
181         QStringList returnString;
182         for (const auto &tu : timeUnit) {
183             int n = timeInSeconds / tu.first;
184             if (n > 0) {
185                 returnString += QString("%1 %2").arg(QString::number(n), tu.second);
186             }
187             timeInSeconds = timeInSeconds % tu.first;
188         }
189         return returnString.join(", ");
190     }
191
192     return QString("%1 %2").arg(QString::number(timeInSeconds), timeUnit.last().second);
193 }
194
195
196 QByteArray prettyDigest(const QByteArray &digest)
197 {
198     QByteArray hexDigest = digest.toHex().toUpper();
199     QByteArray prettyDigest;
200     prettyDigest.fill(':', hexDigest.count() + (hexDigest.count() / 2) - 1);
201
202     for (int i = 0; i * 2 < hexDigest.count(); i++) {
203         prettyDigest.replace(i * 3, 2, hexDigest.mid(i * 2, 2));
204     }
205     return prettyDigest;
206 }
207
208
209 QString formatCurrentDateTimeInString(const QString &formatStr)
210 {
211     // Work on a copy of the string to avoid modifying the input string
212     QString formattedStr = QString(formatStr);
213
214     // Exit early if there's nothing to format
215     if (formattedStr.isEmpty())
216         return formattedStr;
217
218     // Find %%<text>%% in string. Replace inside text formatted to QDateTime with the current
219     // timestamp, using %%%% as an escape for multiple %% signs.
220     // For example:
221     // Simple:   "All Quassel clients vanished from the face of the earth... %%hh:mm:ss%%"
222     // > Result:  "All Quassel clients vanished from the face of the earth... 23:20:34"
223     // Complex:  "Away since %%hh:mm%% on %%dd.MM%% - %%%% not here %%%%"
224     // > Result:  "Away since 23:20 on 21.05 - %% not here %%"
225     //
226     // Match groups of double % signs - Some text %%inside here%%, and even %%%%:
227     //   %%(.*)%%
228     //   (...)    marks a capturing group
229     //   .*       matches zero or more characters, not including newlines
230     // Note that '\' must be escaped as '\\'
231     // Helpful interactive website for debugging and explaining:  https://regex101.com/
232     QRegExp regExpMatchTime("%%(.*)%%");
233
234     // Preserve the smallest groups possible to allow for multiple %%blocks%%
235     regExpMatchTime.setMinimal(true);
236
237     // NOTE: Move regExpMatchTime to a static regular expression if used anywhere that performance
238     // matters.
239
240     // Don't allow a runaway regular expression to loop for too long.  This might not happen.. but
241     // when dealing with user input, better to be safe..?
242     int numIterations = 0;
243
244     // Find each group of %%text here%% starting from the beginning
245     int index = regExpMatchTime.indexIn(formattedStr);
246     int matchLength;
247     QString matchedFormat;
248     while (index >= 0 && numIterations < 512) {
249         // Get the total length of the matched expression
250         matchLength = regExpMatchTime.cap(0).length();
251         // Get the format string, e.g. "this text here" from "%%this text here%%"
252         matchedFormat = regExpMatchTime.cap(1);
253         // Check that there's actual characters inside.  A quadruple % (%%%%) represents two %%
254         // signs.
255         if (matchedFormat.length() > 0) {
256             // Format the string according to the current date and time.  Invalid time format
257             // strings are ignored.
258             formattedStr.replace(index, matchLength,
259                                  QDateTime::currentDateTime().toString(matchedFormat));
260             // Subtract the length of the removed % signs
261             // E.g. "%%h:mm ap%%" turns into "h:mm ap", removing four % signs, thus -4.  This is
262             // used below to determine how far to advance when looking for the next formatting code.
263             matchLength -= 4;
264         } else if (matchLength == 4) {
265             // Remove two of the four percent signs, so '%%%%' escapes to '%%'
266             formattedStr.remove(index, 2);
267             // Subtract the length of the removed % signs, this time removing two % signs, thus -2.
268             matchLength -= 2;
269         } else {
270             // If neither of these match, something went wrong.  Don't modify it to be safe.
271             qDebug() << "Unexpected time format when parsing string, no matchedFormat, matchLength "
272                         "should be 4, actually is" << matchLength;
273         }
274
275         // Find the next group of %%text here%% starting from where the last group ended
276         index = regExpMatchTime.indexIn(formattedStr, index + matchLength);
277         numIterations++;
278     }
279
280     return formattedStr;
281 }
282
283
284 QString tryFormatUnixEpoch(const QString &possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC)
285 {
286     // Does the string resemble a Unix epoch?  Parse as 64-bit time
287     qint64 secsSinceEpoch = possibleEpochDate.toLongLong();
288     if (secsSinceEpoch == 0) {
289         // Parsing either failed, or '0' was sent.  No need to distinguish; either way, it's not
290         // useful as epoch.
291         // See https://doc.qt.io/qt-5/qstring.html#toLongLong
292         return possibleEpochDate;
293     }
294
295     // Time checks out, parse it
296     QDateTime date;
297 #if QT_VERSION >= 0x050800
298     date.setSecsSinceEpoch(secsSinceEpoch);
299 #else
300     // toSecsSinceEpoch() was added in Qt 5.8.  Manually downconvert to seconds for now.
301     // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
302     date.setMSecsSinceEpoch(secsSinceEpoch * 1000);
303 #endif
304
305     // Return the localized date/time
306     if (useUTC) {
307         // Return UTC time
308         if (dateFormat == Qt::DateFormat::ISODate) {
309             // Replace the "T" date/time separator with " " for readability.  This isn't quite the
310             // ISO 8601 spec (it specifies omitting the "T" entirely), but RFC 3339 allows this.
311             // Go with RFC 3339 for human readability that's still machine-parseable, too.
312             //
313             // Before: 2018-06-21T21:35:52Z
314             // After:  2018-06-21 21:35:52Z
315             //         ..........^ (10th character)
316             //
317             // See https://en.wikipedia.org/wiki/ISO_8601#cite_note-32
318             // And https://www.ietf.org/rfc/rfc3339.txt
319             return date.toUTC().toString(dateFormat).replace(10, 1, " ");
320         } else {
321             return date.toUTC().toString(dateFormat);
322         }
323     } else if (dateFormat == Qt::DateFormat::ISODate) {
324         // Add in ISO local timezone information via special handling below
325         // formatDateTimeToOffsetISO() handles converting "T" to " "
326         return formatDateTimeToOffsetISO(date);
327     } else {
328         // Return local time
329         return date.toString(dateFormat);
330     }
331 }
332
333
334 QString formatDateTimeToOffsetISO(const QDateTime &dateTime)
335 {
336     if (!dateTime.isValid()) {
337         // Don't try to do anything with invalid date/time
338         return "formatDateTimeToISO() invalid date/time";
339     }
340
341     // Replace the "T" date/time separator with " " for readability.  This isn't quite the ISO 8601
342     // spec (it specifies omitting the "T" entirely), but RFC 3339 allows this.  Go with RFC 3339
343     // for human readability that's still machine-parseable, too.
344     //
345     // Before: 2018-08-22T18:43:10-05:00
346     // After:  2018-08-22 18:43:10-05:00
347     //         ..........^ (10th character)
348     //
349     // See https://en.wikipedia.org/wiki/ISO_8601#cite_note-32
350     // And https://www.ietf.org/rfc/rfc3339.txt
351
352 #if 0
353     // The expected way to get a UTC offset on ISO 8601 dates
354     // Remove the "T" date/time separator
355     return dateTime.toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate).replace(10, 1, " ");
356 #else
357     // Work around Qt bug that converts to UTC instead of including timezone information
358     // See https://bugreports.qt.io/browse/QTBUG-26161
359     //
360     // NOTE: Despite the bug report marking as fixed in Qt 5.2.0 (QT_VERSION >= 0x050200), this
361     // still appears broken in Qt 5.5.1.
362     //
363     // Credit to "user362638" for the solution below, modified to fit Quassel's needs
364     // https://stackoverflow.com/questions/18750569/qdatetime-isodate-with-timezone
365
366     // Get the local and UTC time
367     QDateTime local = QDateTime(dateTime);
368     QDateTime utc = local.toUTC();
369     utc.setTimeSpec(Qt::LocalTime);
370
371     // Find the UTC offset
372     int utcOffset = utc.secsTo(local);
373
374     // Force the local time to follow this offset
375     local.setUtcOffset(utcOffset);
376     // Now the output should be correct
377     // Remove the "T" date/time separator
378     return local.toString(Qt::ISODate).replace(10, 1, " ");
379 #endif
380 }