X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=application%2FUtils.php;h=35d652241bb6a5a4c42c7ded7b7381be48dc7f15;hb=refs%2Fpull%2F785%2Fhead;hp=0a5b476ebf9779bbe47f8ea7f28ef0de21b28481;hpb=9cf93bcfc53c36e0dd59fcfc717ac483ee74b35a;p=github%2Fshaarli%2FShaarli.git diff --git a/application/Utils.php b/application/Utils.php index 0a5b476e..35d65224 100644 --- a/application/Utils.php +++ b/application/Utils.php @@ -231,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)); +}