feverUtil.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. if (FreshRSS_Context::$system_conf === null) {
  29. throw new FreshRSS_Context_Exception('System configuration not initialised!');
  30. }
  31. $salt = sha1(FreshRSS_Context::$system_conf->salt);
  32. return self::FEVER_PATH . '/.key-' . $salt . '-' . $feverKey . '.txt';
  33. }
  34. /**
  35. * Update the fever key of a user.
  36. * @return string|false the Fever key, or false if the update failed
  37. * @throws FreshRSS_Context_Exception
  38. */
  39. public static function updateKey(string $username, string $passwordPlain) {
  40. if (!self::checkFeverPath()) {
  41. return false;
  42. }
  43. self::deleteKey($username);
  44. $feverKey = strtolower(md5("{$username}:{$passwordPlain}"));
  45. $feverKeyPath = self::getKeyPath($feverKey);
  46. $result = file_put_contents($feverKeyPath, $username);
  47. if (is_int($result) && $result > 0) {
  48. return $feverKey;
  49. }
  50. Minz_Log::warning('Could not save Fever API credentials. Unknown error.', ADMIN_LOG);
  51. return false;
  52. }
  53. /**
  54. * Delete the Fever key of a user.
  55. *
  56. * @return bool true if the deletion succeeded, else false.
  57. * @throws FreshRSS_Context_Exception
  58. */
  59. public static function deleteKey(string $username): bool {
  60. $userConfig = get_user_configuration($username);
  61. if ($userConfig === null) {
  62. return false;
  63. }
  64. $feverKey = $userConfig->feverKey;
  65. if (!ctype_xdigit($feverKey)) {
  66. return false;
  67. }
  68. $feverKeyPath = self::getKeyPath($feverKey);
  69. return @unlink($feverKeyPath);
  70. }
  71. }