class-wp-recovery-mode.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. /**
  3. * Error Protection API: WP_Recovery_Mode class
  4. *
  5. * @package WordPress
  6. * @since 5.2.0
  7. */
  8. /**
  9. * Core class used to implement Recovery Mode.
  10. *
  11. * @since 5.2.0
  12. */
  13. #[AllowDynamicProperties]
  14. class WP_Recovery_Mode {
  15. const EXIT_ACTION = 'exit_recovery_mode';
  16. /**
  17. * Service to handle cookies.
  18. *
  19. * @since 5.2.0
  20. * @var WP_Recovery_Mode_Cookie_Service
  21. */
  22. private $cookie_service;
  23. /**
  24. * Service to generate a recovery mode key.
  25. *
  26. * @since 5.2.0
  27. * @var WP_Recovery_Mode_Key_Service
  28. */
  29. private $key_service;
  30. /**
  31. * Service to generate and validate recovery mode links.
  32. *
  33. * @since 5.2.0
  34. * @var WP_Recovery_Mode_Link_Service
  35. */
  36. private $link_service;
  37. /**
  38. * Service to handle sending an email with a recovery mode link.
  39. *
  40. * @since 5.2.0
  41. * @var WP_Recovery_Mode_Email_Service
  42. */
  43. private $email_service;
  44. /**
  45. * Is recovery mode initialized.
  46. *
  47. * @since 5.2.0
  48. * @var bool
  49. */
  50. private $is_initialized = false;
  51. /**
  52. * Is recovery mode active in this session.
  53. *
  54. * @since 5.2.0
  55. * @var bool
  56. */
  57. private $is_active = false;
  58. /**
  59. * Get an ID representing the current recovery mode session.
  60. *
  61. * @since 5.2.0
  62. * @var string
  63. */
  64. private $session_id = '';
  65. /**
  66. * WP_Recovery_Mode constructor.
  67. *
  68. * @since 5.2.0
  69. */
  70. public function __construct() {
  71. $this->cookie_service = new WP_Recovery_Mode_Cookie_Service();
  72. $this->key_service = new WP_Recovery_Mode_Key_Service();
  73. $this->link_service = new WP_Recovery_Mode_Link_Service( $this->cookie_service, $this->key_service );
  74. $this->email_service = new WP_Recovery_Mode_Email_Service( $this->link_service );
  75. }
  76. /**
  77. * Initialize recovery mode for the current request.
  78. *
  79. * @since 5.2.0
  80. */
  81. public function initialize() {
  82. $this->is_initialized = true;
  83. add_action( 'wp_logout', array( $this, 'exit_recovery_mode' ) );
  84. add_action( 'login_form_' . self::EXIT_ACTION, array( $this, 'handle_exit_recovery_mode' ) );
  85. add_action( 'recovery_mode_clean_expired_keys', array( $this, 'clean_expired_keys' ) );
  86. if ( ! wp_next_scheduled( 'recovery_mode_clean_expired_keys' ) && ! wp_installing() ) {
  87. wp_schedule_event( time(), 'daily', 'recovery_mode_clean_expired_keys' );
  88. }
  89. if ( defined( 'WP_RECOVERY_MODE_SESSION_ID' ) ) {
  90. $this->is_active = true;
  91. $this->session_id = WP_RECOVERY_MODE_SESSION_ID;
  92. return;
  93. }
  94. if ( $this->cookie_service->is_cookie_set() ) {
  95. $this->handle_cookie();
  96. return;
  97. }
  98. $this->link_service->handle_begin_link( $this->get_link_ttl() );
  99. }
  100. /**
  101. * Checks whether recovery mode is active.
  102. *
  103. * This will not change after recovery mode has been initialized. {@see WP_Recovery_Mode::run()}.
  104. *
  105. * @since 5.2.0
  106. *
  107. * @return bool True if recovery mode is active, false otherwise.
  108. */
  109. public function is_active() {
  110. return $this->is_active;
  111. }
  112. /**
  113. * Gets the recovery mode session ID.
  114. *
  115. * @since 5.2.0
  116. *
  117. * @return string The session ID if recovery mode is active, empty string otherwise.
  118. */
  119. public function get_session_id() {
  120. return $this->session_id;
  121. }
  122. /**
  123. * Checks whether recovery mode has been initialized.
  124. *
  125. * Recovery mode should not be used until this point. Initialization happens immediately before loading plugins.
  126. *
  127. * @since 5.2.0
  128. *
  129. * @return bool
  130. */
  131. public function is_initialized() {
  132. return $this->is_initialized;
  133. }
  134. /**
  135. * Handles a fatal error occurring.
  136. *
  137. * The calling API should immediately die() after calling this function.
  138. *
  139. * @since 5.2.0
  140. *
  141. * @param array $error Error details from `error_get_last()`.
  142. * @return true|WP_Error True if the error was handled and headers have already been sent.
  143. * Or the request will exit to try and catch multiple errors at once.
  144. * WP_Error if an error occurred preventing it from being handled.
  145. */
  146. public function handle_error( array $error ) {
  147. $extension = $this->get_extension_for_error( $error );
  148. if ( ! $extension || $this->is_network_plugin( $extension ) ) {
  149. return new WP_Error( 'invalid_source', __( 'Error not caused by a plugin or theme.' ) );
  150. }
  151. if ( ! $this->is_active() ) {
  152. if ( ! is_protected_endpoint() ) {
  153. return new WP_Error( 'non_protected_endpoint', __( 'Error occurred on a non-protected endpoint.' ) );
  154. }
  155. if ( ! function_exists( 'wp_generate_password' ) ) {
  156. require_once ABSPATH . WPINC . '/pluggable.php';
  157. }
  158. return $this->email_service->maybe_send_recovery_mode_email( $this->get_email_rate_limit(), $error, $extension );
  159. }
  160. if ( ! $this->store_error( $error ) ) {
  161. return new WP_Error( 'storage_error', __( 'Failed to store the error.' ) );
  162. }
  163. if ( headers_sent() ) {
  164. return true;
  165. }
  166. $this->redirect_protected();
  167. }
  168. /**
  169. * Ends the current recovery mode session.
  170. *
  171. * @since 5.2.0
  172. *
  173. * @return bool True on success, false on failure.
  174. */
  175. public function exit_recovery_mode() {
  176. if ( ! $this->is_active() ) {
  177. return false;
  178. }
  179. $this->email_service->clear_rate_limit();
  180. $this->cookie_service->clear_cookie();
  181. wp_paused_plugins()->delete_all();
  182. wp_paused_themes()->delete_all();
  183. return true;
  184. }
  185. /**
  186. * Handles a request to exit Recovery Mode.
  187. *
  188. * @since 5.2.0
  189. */
  190. public function handle_exit_recovery_mode() {
  191. $redirect_to = wp_get_referer();
  192. // Safety check in case referrer returns false.
  193. if ( ! $redirect_to ) {
  194. $redirect_to = is_user_logged_in() ? admin_url() : home_url();
  195. }
  196. if ( ! $this->is_active() ) {
  197. wp_safe_redirect( $redirect_to );
  198. die;
  199. }
  200. if ( ! isset( $_GET['action'] ) || self::EXIT_ACTION !== $_GET['action'] ) {
  201. return;
  202. }
  203. if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], self::EXIT_ACTION ) ) {
  204. wp_die( __( 'Exit recovery mode link expired.' ), 403 );
  205. }
  206. if ( ! $this->exit_recovery_mode() ) {
  207. wp_die( __( 'Failed to exit recovery mode. Please try again later.' ) );
  208. }
  209. wp_safe_redirect( $redirect_to );
  210. die;
  211. }
  212. /**
  213. * Cleans any recovery mode keys that have expired according to the link TTL.
  214. *
  215. * Executes on a daily cron schedule.
  216. *
  217. * @since 5.2.0
  218. */
  219. public function clean_expired_keys() {
  220. $this->key_service->clean_expired_keys( $this->get_link_ttl() );
  221. }
  222. /**
  223. * Handles checking for the recovery mode cookie and validating it.
  224. *
  225. * @since 5.2.0
  226. */
  227. protected function handle_cookie() {
  228. $validated = $this->cookie_service->validate_cookie();
  229. if ( is_wp_error( $validated ) ) {
  230. $this->cookie_service->clear_cookie();
  231. $validated->add_data( array( 'status' => 403 ) );
  232. wp_die( $validated );
  233. }
  234. $session_id = $this->cookie_service->get_session_id_from_cookie();
  235. if ( is_wp_error( $session_id ) ) {
  236. $this->cookie_service->clear_cookie();
  237. $session_id->add_data( array( 'status' => 403 ) );
  238. wp_die( $session_id );
  239. }
  240. $this->is_active = true;
  241. $this->session_id = $session_id;
  242. }
  243. /**
  244. * Gets the rate limit between sending new recovery mode email links.
  245. *
  246. * @since 5.2.0
  247. *
  248. * @return int Rate limit in seconds.
  249. */
  250. protected function get_email_rate_limit() {
  251. /**
  252. * Filters the rate limit between sending new recovery mode email links.
  253. *
  254. * @since 5.2.0
  255. *
  256. * @param int $rate_limit Time to wait in seconds. Defaults to 1 day.
  257. */
  258. return apply_filters( 'recovery_mode_email_rate_limit', DAY_IN_SECONDS );
  259. }
  260. /**
  261. * Gets the number of seconds the recovery mode link is valid for.
  262. *
  263. * @since 5.2.0
  264. *
  265. * @return int Interval in seconds.
  266. */
  267. protected function get_link_ttl() {
  268. $rate_limit = $this->get_email_rate_limit();
  269. $valid_for = $rate_limit;
  270. /**
  271. * Filters the amount of time the recovery mode email link is valid for.
  272. *
  273. * The ttl must be at least as long as the email rate limit.
  274. *
  275. * @since 5.2.0
  276. *
  277. * @param int $valid_for The number of seconds the link is valid for.
  278. */
  279. $valid_for = apply_filters( 'recovery_mode_email_link_ttl', $valid_for );
  280. return max( $valid_for, $rate_limit );
  281. }
  282. /**
  283. * Gets the extension that the error occurred in.
  284. *
  285. * @since 5.2.0
  286. *
  287. * @global array $wp_theme_directories
  288. *
  289. * @param array $error Error details from `error_get_last()`.
  290. * @return array|false {
  291. * Extension details.
  292. *
  293. * @type string $slug The extension slug. This is the plugin or theme's directory.
  294. * @type string $type The extension type. Either 'plugin' or 'theme'.
  295. * }
  296. */
  297. protected function get_extension_for_error( $error ) {
  298. global $wp_theme_directories;
  299. if ( ! isset( $error['file'] ) ) {
  300. return false;
  301. }
  302. if ( ! defined( 'WP_PLUGIN_DIR' ) ) {
  303. return false;
  304. }
  305. $error_file = wp_normalize_path( $error['file'] );
  306. $wp_plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
  307. if ( 0 === strpos( $error_file, $wp_plugin_dir ) ) {
  308. $path = str_replace( $wp_plugin_dir . '/', '', $error_file );
  309. $parts = explode( '/', $path );
  310. return array(
  311. 'type' => 'plugin',
  312. 'slug' => $parts[0],
  313. );
  314. }
  315. if ( empty( $wp_theme_directories ) ) {
  316. return false;
  317. }
  318. foreach ( $wp_theme_directories as $theme_directory ) {
  319. $theme_directory = wp_normalize_path( $theme_directory );
  320. if ( 0 === strpos( $error_file, $theme_directory ) ) {
  321. $path = str_replace( $theme_directory . '/', '', $error_file );
  322. $parts = explode( '/', $path );
  323. return array(
  324. 'type' => 'theme',
  325. 'slug' => $parts[0],
  326. );
  327. }
  328. }
  329. return false;
  330. }
  331. /**
  332. * Checks whether the given extension a network activated plugin.
  333. *
  334. * @since 5.2.0
  335. *
  336. * @param array $extension Extension data.
  337. * @return bool True if network plugin, false otherwise.
  338. */
  339. protected function is_network_plugin( $extension ) {
  340. if ( 'plugin' !== $extension['type'] ) {
  341. return false;
  342. }
  343. if ( ! is_multisite() ) {
  344. return false;
  345. }
  346. $network_plugins = wp_get_active_network_plugins();
  347. foreach ( $network_plugins as $plugin ) {
  348. if ( 0 === strpos( $plugin, $extension['slug'] . '/' ) ) {
  349. return true;
  350. }
  351. }
  352. return false;
  353. }
  354. /**
  355. * Stores the given error so that the extension causing it is paused.
  356. *
  357. * @since 5.2.0
  358. *
  359. * @param array $error Error details from `error_get_last()`.
  360. * @return bool True if the error was stored successfully, false otherwise.
  361. */
  362. protected function store_error( $error ) {
  363. $extension = $this->get_extension_for_error( $error );
  364. if ( ! $extension ) {
  365. return false;
  366. }
  367. switch ( $extension['type'] ) {
  368. case 'plugin':
  369. return wp_paused_plugins()->set( $extension['slug'], $error );
  370. case 'theme':
  371. return wp_paused_themes()->set( $extension['slug'], $error );
  372. default:
  373. return false;
  374. }
  375. }
  376. /**
  377. * Redirects the current request to allow recovering multiple errors in one go.
  378. *
  379. * The redirection will only happen when on a protected endpoint.
  380. *
  381. * It must be ensured that this method is only called when an error actually occurred and will not occur on the
  382. * next request again. Otherwise it will create a redirect loop.
  383. *
  384. * @since 5.2.0
  385. */
  386. protected function redirect_protected() {
  387. // Pluggable is usually loaded after plugins, so we manually include it here for redirection functionality.
  388. if ( ! function_exists( 'wp_safe_redirect' ) ) {
  389. require_once ABSPATH . WPINC . '/pluggable.php';
  390. }
  391. $scheme = is_ssl() ? 'https://' : 'http://';
  392. $url = "{$scheme}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
  393. wp_safe_redirect( $url );
  394. exit;
  395. }
  396. }