]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - application/Utils.php
Merge pull request #682 from ArthurHoaro/delete-button
[github/shaarli/Shaarli.git] / application / Utils.php
index 0166ee2ac0e132035af72e132a50ceb4368933e7..35d652241bb6a5a4c42c7ded7b7381be48dc7f15 100644 (file)
@@ -31,7 +31,11 @@ function logm($logFile, $clientIp, $message)
  *   - are NOT cryptographically secure (they CAN be forged)
  *
  *  In Shaarli, they are used as a tinyurl-like link to individual entries,
- *  e.g. smallHash('20111006_131924') --> yZH23w
+ *  built once with the combination of the date and item ID.
+ *  e.g. smallHash('20111006_131924' . 142) --> eaWxtQ
+ *
+ * @warning before v0.8.1, smallhashes were built only with the date,
+ *          and their value has been preserved.
  *
  * @param string $text Create a hash from this text.
  *
@@ -227,3 +231,42 @@ function autoLocale($headerLocale)
     }
     setlocale(LC_ALL, $attempts);
 }
+
+/**
+ * Generates a default API secret.
+ *
+ * Note that the random-ish methods used in this function are predictable,
+ * which makes them NOT suitable for crypto.
+ * BUT the random string is salted with the salt and hashed with the username.
+ * It makes the generated API secret secured enough for Shaarli.
+ *
+ * PHP 7 provides random_int(), designed for cryptography.
+ * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
+
+ * @param string $username Shaarli login username
+ * @param string $salt     Shaarli password hash salt
+ *
+ * @return string|bool Generated API secret, 12 char length.
+ *                     Or false if invalid parameters are provided (which will make the API unusable).
+ */
+function generate_api_secret($username, $salt)
+{
+    if (empty($username) || empty($salt)) {
+        return false;
+    }
+
+    return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
+}
+
+/**
+ * Trim string, replace sequences of whitespaces by a single space.
+ * PHP equivalent to `normalize-space` XSLT function.
+ *
+ * @param string $string Input string.
+ *
+ * @return mixed Normalized string.
+ */
+function normalize_spaces($string)
+{
+    return preg_replace('/\s{2,}/', ' ', trim($string));
+}