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