class-yoast-network-admin.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Internals
  6. */
  7. /**
  8. * Multisite utility class for network admin functionality.
  9. */
  10. class Yoast_Network_Admin implements WPSEO_WordPress_Integration, WPSEO_WordPress_AJAX_Integration {
  11. /**
  12. * Action identifier for updating plugin network options.
  13. *
  14. * @var string
  15. */
  16. const UPDATE_OPTIONS_ACTION = 'yoast_handle_network_options';
  17. /**
  18. * Action identifier for restoring a site.
  19. *
  20. * @var string
  21. */
  22. const RESTORE_SITE_ACTION = 'yoast_restore_site';
  23. /**
  24. * Gets the available sites as choices, e.g. for a dropdown.
  25. *
  26. * @param bool $include_empty Optional. Whether to include an initial placeholder choice.
  27. * Default false.
  28. * @param bool $show_title Optional. Whether to show the title for each site. This requires
  29. * switching through the sites, so has performance implications for
  30. * sites that do not use a persistent cache.
  31. * Default false.
  32. *
  33. * @return array Choices as $site_id => $site_label pairs.
  34. */
  35. public function get_site_choices( $include_empty = false, $show_title = false ) {
  36. $choices = [];
  37. if ( $include_empty ) {
  38. $choices['-'] = __( 'None', 'wordpress-seo' );
  39. }
  40. $criteria = [
  41. 'deleted' => 0,
  42. 'network_id' => get_current_network_id(),
  43. ];
  44. $sites = get_sites( $criteria );
  45. foreach ( $sites as $site ) {
  46. $site_name = $site->domain . $site->path;
  47. if ( $show_title ) {
  48. $site_name = $site->blogname . ' (' . $site->domain . $site->path . ')';
  49. }
  50. $choices[ $site->blog_id ] = $site->blog_id . ': ' . $site_name;
  51. $site_states = $this->get_site_states( $site );
  52. if ( ! empty( $site_states ) ) {
  53. $choices[ $site->blog_id ] .= ' [' . implode( ', ', $site_states ) . ']';
  54. }
  55. }
  56. return $choices;
  57. }
  58. /**
  59. * Gets the states of a site.
  60. *
  61. * @param WP_Site $site Site object.
  62. *
  63. * @return array Array of $state_slug => $state_label pairs.
  64. */
  65. public function get_site_states( $site ) {
  66. $available_states = [
  67. 'public' => __( 'public', 'wordpress-seo' ),
  68. 'archived' => __( 'archived', 'wordpress-seo' ),
  69. 'mature' => __( 'mature', 'wordpress-seo' ),
  70. 'spam' => __( 'spam', 'wordpress-seo' ),
  71. 'deleted' => __( 'deleted', 'wordpress-seo' ),
  72. ];
  73. $site_states = [];
  74. foreach ( $available_states as $state_slug => $state_label ) {
  75. if ( $site->$state_slug === '1' ) {
  76. $site_states[ $state_slug ] = $state_label;
  77. }
  78. }
  79. return $site_states;
  80. }
  81. /**
  82. * Handles a request to update plugin network options.
  83. *
  84. * This method works similar to how option updates are handled in `wp-admin/options.php` and
  85. * `wp-admin/network/settings.php`.
  86. *
  87. * @return void
  88. */
  89. public function handle_update_options_request() {
  90. $option_group = filter_input( INPUT_POST, 'network_option_group', FILTER_SANITIZE_STRING );
  91. $this->verify_request( "{$option_group}-network-options" );
  92. $whitelist_options = Yoast_Network_Settings_API::get()->get_whitelist_options( $option_group );
  93. if ( empty( $whitelist_options ) ) {
  94. add_settings_error( $option_group, 'settings_updated', __( 'You are not allowed to modify unregistered network settings.', 'wordpress-seo' ), 'error' );
  95. $this->terminate_request();
  96. return;
  97. }
  98. foreach ( $whitelist_options as $option_name ) {
  99. $value = null;
  100. if ( isset( $_POST[ $option_name ] ) ) { // WPCS: CSRF ok.
  101. // Adding sanitize_text_field around this will break the saving of settings because it expects a string: https://github.com/Yoast/wordpress-seo/issues/12440.
  102. $value = wp_unslash( $_POST[ $option_name ] ); // WPCS: CSRF ok.
  103. }
  104. WPSEO_Options::update_site_option( $option_name, $value );
  105. }
  106. $settings_errors = get_settings_errors();
  107. if ( empty( $settings_errors ) ) {
  108. add_settings_error( $option_group, 'settings_updated', __( 'Settings Updated.', 'wordpress-seo' ), 'updated' );
  109. }
  110. $this->terminate_request();
  111. }
  112. /**
  113. * Handles a request to restore a site's default settings.
  114. *
  115. * @return void
  116. */
  117. public function handle_restore_site_request() {
  118. $this->verify_request( 'wpseo-network-restore', 'restore_site_nonce' );
  119. $option_group = 'wpseo_ms';
  120. $site_id = ! empty( $_POST[ $option_group ]['site_id'] ) ? (int) $_POST[ $option_group ]['site_id'] : 0; // WPCS: CSRF ok.
  121. if ( ! $site_id ) {
  122. add_settings_error( $option_group, 'settings_updated', __( 'No site has been selected to restore.', 'wordpress-seo' ), 'error' );
  123. $this->terminate_request();
  124. return;
  125. }
  126. $site = get_site( $site_id );
  127. if ( ! $site ) {
  128. /* translators: %s expands to the ID of a site within a multisite network. */
  129. add_settings_error( $option_group, 'settings_updated', sprintf( __( 'Site with ID %d not found.', 'wordpress-seo' ), $site_id ), 'error' );
  130. }
  131. else {
  132. WPSEO_Options::reset_ms_blog( $site_id );
  133. /* translators: %s expands to the name of a site within a multisite network. */
  134. add_settings_error( $option_group, 'settings_updated', sprintf( __( '%s restored to default SEO settings.', 'wordpress-seo' ), esc_html( $site->blogname ) ), 'updated' );
  135. }
  136. $this->terminate_request();
  137. }
  138. /**
  139. * Outputs nonce, action and option group fields for a network settings page in the plugin.
  140. *
  141. * @param string $option_group Option group name for the current page.
  142. *
  143. * @return void
  144. */
  145. public function settings_fields( $option_group ) {
  146. ?>
  147. <input type="hidden" name="network_option_group" value="<?php echo esc_attr( $option_group ); ?>" />
  148. <input type="hidden" name="action" value="<?php echo esc_attr( self::UPDATE_OPTIONS_ACTION ); ?>" />
  149. <?php
  150. wp_nonce_field( "$option_group-network-options" );
  151. }
  152. /**
  153. * Enqueues network admin assets.
  154. *
  155. * @return void
  156. */
  157. public function enqueue_assets() {
  158. $asset_manager = new WPSEO_Admin_Asset_Manager();
  159. $asset_manager->enqueue_script( 'network-admin-script' );
  160. $translations = [
  161. /* translators: %s: success message */
  162. 'success_prefix' => __( 'Success: %s', 'wordpress-seo' ),
  163. /* translators: %s: error message */
  164. 'error_prefix' => __( 'Error: %s', 'wordpress-seo' ),
  165. ];
  166. wp_localize_script(
  167. WPSEO_Admin_Asset_Manager::PREFIX . 'network-admin-script',
  168. 'wpseoNetworkAdminGlobalL10n',
  169. $translations
  170. );
  171. }
  172. /**
  173. * Hooks in the necessary actions and filters.
  174. *
  175. * @return void
  176. */
  177. public function register_hooks() {
  178. if ( ! $this->meets_requirements() ) {
  179. return;
  180. }
  181. add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
  182. add_action( 'admin_action_' . self::UPDATE_OPTIONS_ACTION, [ $this, 'handle_update_options_request' ] );
  183. add_action( 'admin_action_' . self::RESTORE_SITE_ACTION, [ $this, 'handle_restore_site_request' ] );
  184. }
  185. /**
  186. * Hooks in the necessary AJAX actions.
  187. *
  188. * @return void
  189. */
  190. public function register_ajax_hooks() {
  191. add_action( 'wp_ajax_' . self::UPDATE_OPTIONS_ACTION, [ $this, 'handle_update_options_request' ] );
  192. add_action( 'wp_ajax_' . self::RESTORE_SITE_ACTION, [ $this, 'handle_restore_site_request' ] );
  193. }
  194. /**
  195. * Checks whether the requirements to use this class are met.
  196. *
  197. * @return bool True if requirements are met, false otherwise.
  198. */
  199. public function meets_requirements() {
  200. return is_multisite() && is_network_admin();
  201. }
  202. /**
  203. * Verifies that the current request is valid.
  204. *
  205. * @param string $action Nonce action.
  206. * @param string $query_arg Optional. Nonce query argument. Default '_wpnonce'.
  207. *
  208. * @return void
  209. */
  210. public function verify_request( $action, $query_arg = '_wpnonce' ) {
  211. $has_access = current_user_can( 'wpseo_manage_network_options' );
  212. if ( wp_doing_ajax() ) {
  213. check_ajax_referer( $action, $query_arg );
  214. if ( ! $has_access ) {
  215. wp_die( -1, 403 );
  216. }
  217. return;
  218. }
  219. check_admin_referer( $action, $query_arg );
  220. if ( ! $has_access ) {
  221. wp_die( esc_html__( 'You are not allowed to perform this action.', 'wordpress-seo' ) );
  222. }
  223. }
  224. /**
  225. * Terminates the current request by either redirecting back or sending an AJAX response.
  226. *
  227. * @return void
  228. */
  229. public function terminate_request() {
  230. if ( wp_doing_ajax() ) {
  231. $settings_errors = get_settings_errors();
  232. if ( ! empty( $settings_errors ) && $settings_errors[0]['type'] === 'updated' ) {
  233. wp_send_json_success( $settings_errors, 200 );
  234. }
  235. wp_send_json_error( $settings_errors, 400 );
  236. }
  237. $this->persist_settings_errors();
  238. $this->redirect_back( [ 'settings-updated' => 'true' ] );
  239. }
  240. /**
  241. * Persists settings errors.
  242. *
  243. * Settings errors are stored in a transient for 30 seconds so that this transient
  244. * can be retrieved on the next page load.
  245. *
  246. * @return void
  247. */
  248. protected function persist_settings_errors() {
  249. /*
  250. * A regular transient is used here, since it is automatically cleared right after the redirect.
  251. * A network transient would be cleaner, but would require a lot of copied code from core for
  252. * just a minor adjustment when displaying settings errors.
  253. */
  254. set_transient( 'settings_errors', get_settings_errors(), 30 );
  255. }
  256. /**
  257. * Redirects back to the referer URL, with optional query arguments.
  258. *
  259. * @param array $query_args Optional. Query arguments to add to the redirect URL. Default none.
  260. *
  261. * @return void
  262. */
  263. protected function redirect_back( $query_args = [] ) {
  264. $sendback = wp_get_referer();
  265. if ( ! empty( $query_args ) ) {
  266. $sendback = add_query_arg( $query_args, $sendback );
  267. }
  268. wp_safe_redirect( $sendback );
  269. exit;
  270. }
  271. }