feverUtil.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_fever_Util {
  4. private const FEVER_PATH = DATA_PATH . '/fever';
  5. /**
  6. * Make sure the fever path exists and is writable.
  7. *
  8. * @return bool true if the path is writable, false otherwise.
  9. */
  10. public static function checkFeverPath(): bool {
  11. if (!file_exists(self::FEVER_PATH) &&
  12. !mkdir($concurrentDirectory = self::FEVER_PATH, 0770, true) &&
  13. !is_dir($concurrentDirectory)
  14. ) {
  15. throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
  16. }
  17. $ok = touch(self::FEVER_PATH . '/index.html'); // is_writable() is not reliable for a folder on NFS
  18. if (!$ok) {
  19. Minz_Log::error("Could not save Fever API credentials. The directory does not have write access.");
  20. }
  21. return $ok;
  22. }
  23. /**
  24. * Return the corresponding path for a fever key.
  25. * @throws FreshRSS_Context_Exception
  26. */
  27. public static function getKeyPath(string $feverKey): string {
  28. $salt = sha1(FreshRSS_Context::systemConf()->salt);
  29. return self::FEVER_PATH . '/.key-' . $salt . '-' . $feverKey . '.txt';
  30. }
  31. /**
  32. * Update the fever key of a user.
  33. * @return string|false the Fever key, or false if the update failed
  34. * @throws FreshRSS_Context_Exception
  35. */
  36. public static function updateKey(string $username, string $passwordPlain): string|false {
  37. if (!self::checkFeverPath()) {
  38. return false;
  39. }
  40. self::deleteKey($username);
  41. $feverKey = strtolower(md5("{$username}:{$passwordPlain}"));
  42. $feverKeyPath = self::getKeyPath($feverKey);
  43. $result = file_put_contents($feverKeyPath, $username);
  44. if (is_int($result) && $result > 0) {
  45. return $feverKey;
  46. }
  47. Minz_Log::warning('Could not save Fever API credentials. Unknown error.', ADMIN_LOG);
  48. return false;
  49. }
  50. /**
  51. * Delete the Fever key of a user.
  52. *
  53. * @return bool true if the deletion succeeded, else false.
  54. * @throws FreshRSS_Context_Exception
  55. */
  56. public static function deleteKey(string $username): bool {
  57. $userConfig = FreshRSS_UserConfiguration::getForUser($username);
  58. if ($userConfig === null) {
  59. return false;
  60. }
  61. $feverKey = $userConfig->feverKey;
  62. if (!ctype_xdigit($feverKey)) {
  63. return false;
  64. }
  65. $feverKeyPath = self::getKeyPath($feverKey);
  66. return @unlink($feverKeyPath);
  67. }
  68. }