feverUtil.php 2.3 KB

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