1 /***************************************************************************
2 * Copyright (C) 2005-2020 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
27 #include <QCoreApplication>
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 */;
39 QString nickFromMask(const QString& mask)
41 return mask.left(mask.indexOf('!'));
44 QString userFromMask(const QString& mask)
46 const int offset = mask.indexOf('!') + 1;
49 const int length = mask.indexOf('@', offset) - offset;
50 return mask.mid(offset, length >= 0 ? length : -1);
53 QString hostFromMask(const QString& mask)
55 const int excl = mask.indexOf('!');
58 const int offset = mask.indexOf('@', excl + 1) + 1;
59 return offset > 0 && offset < mask.size() ? mask.mid(offset) : QString{};
62 bool isChannelName(const QString& str)
66 static constexpr std::array<quint8, 4> prefixes{{'#', '&', '!', '+'}};
67 return std::any_of(prefixes.cbegin(), prefixes.cend(), [&str](quint8 c) { return c == str[0]; });
70 QString stripFormatCodes(QString message)
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);
76 QString stripAcceleratorMarkers(const QString& label_)
78 QString label = label_;
82 p = label.indexOf('&', p);
83 if (p < 0 || p + 1 >= label.length())
86 if (label.at(p + 1).isLetterOrNumber() || label.at(p + 1) == '&')
94 QString decodeString(const QByteArray& input, QTextCodec* codec)
96 if (codec && utf8DetectionBlacklist.contains(codec->mibEnum()))
97 return codec->toUnicode(input);
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...
105 for (uchar c : input) {
107 // We check a part of a multibyte char. These need to be of the form 10yyyyyy.
108 if ((c & 0xc0) != 0x80) {
115 if ((c & 0x80) == 0x00)
116 continue; // 7 bit is always ok
117 if ((c & 0xf8) == 0xf0) {
120 } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
121 if ((c & 0xf0) == 0xe0) {
124 } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
125 if ((c & 0xe0) == 0xc0) {
128 } // 2-byte char 110xxxxx 10yyyyyy
130 break; // 8 bit char, but not utf8!
132 if (isUtf8 && cnt == 0) {
133 QString s = QString::fromUtf8(input);
134 // qDebug() << "Detected utf8:" << s;
137 // QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1());
139 return QString::fromLatin1(input);
140 return codec->toUnicode(input);
143 uint editingDistance(const QString& s1, const QString& s2)
145 uint n = s1.size() + 1;
146 uint m = s2.size() + 1;
147 QVector<QVector<uint>> matrix(n, QVector<uint>(m, 0));
149 for (uint i = 0; i < n; i++)
152 for (uint i = 0; i < m; i++)
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;
161 if (deleteChar < insertChar)
166 if (s1[i - 1] == s2[j - 1]) {
167 uint inheritChar = matrix[i - 1][j - 1];
168 if (inheritChar < min)
175 return matrix[n - 1][m - 1];
178 QString secondsToString(int timeInSeconds)
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"))};
188 if (timeInSeconds != 0) {
189 QStringList returnString;
190 for (const auto& tu : timeUnit) {
191 int n = timeInSeconds / tu.first;
193 returnString += QString("%1 %2").arg(QString::number(n), tu.second);
195 timeInSeconds = timeInSeconds % tu.first;
197 return returnString.join(", ");
200 return QString("%1 %2").arg(QString::number(timeInSeconds), timeUnit.last().second);
203 QByteArray prettyDigest(const QByteArray& digest)
205 QByteArray hexDigest = digest.toHex().toUpper();
206 QByteArray prettyDigest;
207 prettyDigest.fill(':', hexDigest.count() + (hexDigest.count() / 2) - 1);
209 for (int i = 0; i * 2 < hexDigest.count(); i++) {
210 prettyDigest.replace(i * 3, 2, hexDigest.mid(i * 2, 2));
215 QString formatCurrentDateTimeInString(const QString& formatStr)
217 // Work on a copy of the string to avoid modifying the input string
218 QString formattedStr = QString(formatStr);
220 // Exit early if there's nothing to format
221 if (formattedStr.isEmpty())
224 // Find %%<text>%% in string. Replace inside text formatted to QDateTime with the current
225 // timestamp, using %%%% as an escape for multiple %% signs.
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 %%"
232 // Match groups of double % signs - Some text %%inside here%%, and even %%%%:
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("%%(.*)%%");
240 // Preserve the smallest groups possible to allow for multiple %%blocks%%
241 regExpMatchTime.setMinimal(true);
243 // NOTE: Move regExpMatchTime to a static regular expression if used anywhere that performance
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;
250 // Find each group of %%text here%% starting from the beginning
251 int index = regExpMatchTime.indexIn(formattedStr);
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 %%
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.
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.
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"
283 // Find the next group of %%text here%% starting from where the last group ended
284 index = regExpMatchTime.indexIn(formattedStr, index + matchLength);
291 QString tryFormatUnixEpoch(const QString& possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC)
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
298 // See https://doc.qt.io/qt-5/qstring.html#toLongLong
299 return possibleEpochDate;
302 // Time checks out, parse it
304 #if QT_VERSION >= 0x050800
305 date.setSecsSinceEpoch(secsSinceEpoch);
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);
312 // Return the localized date/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.
320 // Before: 2018-06-21T21:35:52Z
321 // After: 2018-06-21 21:35:52Z
322 // ..........^ (10th character)
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, " ");
329 return date.toUTC().toString(dateFormat);
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);
339 return date.toString(dateFormat);
343 QString formatDateTimeToOffsetISO(const QDateTime& dateTime)
345 if (!dateTime.isValid()) {
346 // Don't try to do anything with invalid date/time
347 return "formatDateTimeToISO() invalid date/time";
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.
354 // Before: 2018-08-22T18:43:10-05:00
355 // After: 2018-08-22 18:43:10-05:00
356 // ..........^ (10th character)
358 // See https://en.wikipedia.org/wiki/ISO_8601#cite_note-32
359 // And https://www.ietf.org/rfc/rfc3339.txt
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, " ");